Debian Codegraph @

gcc/d/dmd/ob.d

raw
1 /**
2 * Flow analysis for Ownership/Borrowing
3 *
4 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/ob.d, _ob.d)
8 * Documentation: https://dlang.org/phobos/dmd_escape.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/ob.d
10 * References: https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1021.md Argument Ownership and Function Calls
11 */
12
13 module dmd.ob;
14
15 import core.stdc.stdio : printf;
16 import core.stdc.stdlib;
17 import core.stdc.string;
18
19 import dmd.root.array;
20 import dmd.rootobject;
21 import dmd.root.rmem;
22
23 import dmd.aggregate;
24 import dmd.arraytypes;
25 import dmd.astenums;
26 import dmd.declaration;
27 import dmd.dscope;
28 import dmd.dsymbol;
29 import dmd.dtemplate;
30 import dmd.errors;
31 import dmd.escape;
32 import dmd.expression;
33
34 import dmd.func;
35 import dmd.globals;
36 import dmd.hdrgen;
37 import dmd.identifier;
38 import dmd.init;
39 import dmd.location;
40 import dmd.mtype;
41 import dmd.printast;
42 import dmd.statement;
43 import dmd.stmtstate;
44 import dmd.tokens;
45 import dmd.typesem;
46 import dmd.visitor;
47 import dmd.visitor.foreachvar;
48
49 import dmd.root.bitarray;
50 import dmd.common.outbuffer;
51
52 /**********************************
53 * Perform ownership/borrowing checks for funcdecl.
54 * Does not modify the AST, just checks for errors.
55 */
56
57 void oblive(FuncDeclaration funcdecl)
58 {
59 //printf("oblive() %s\n", funcdecl.toChars());
60 //printf("fbody: %s\n", funcdecl.fbody.toChars());
61 ObState obstate;
62
63 /* Build the flow graph
64 */
65 setLabelStatementExtraFields(funcdecl.labtab);
66 toObNodes(obstate.nodes, funcdecl.fbody);
67 insertFinallyBlockCalls(obstate.nodes);
68 insertFinallyBlockGotos(obstate.nodes);
69 removeUnreachable(obstate.nodes);
70 computePreds(obstate.nodes);
71
72 numberNodes(obstate.nodes);
73 //foreach (ob; obstate.nodes) ob.print();
74
75 collectVars(funcdecl, obstate.vars);
76 allocStates(obstate);
77 doDataFlowAnalysis(obstate);
78
79 checkObErrors(obstate);
80 }
81
82 alias ObNodes = Array!(ObNode*);
83
84 alias StmtState = dmd.stmtstate.StmtState!ObNode;
85
86 /*******************************************
87 * Collect the state information.
88 */
89 struct ObState
90 {
91 ObNodes nodes;
92 VarDeclarations vars;
93
94 Array!size_t varStack; /// temporary storage
95 Array!bool mutableStack; /// parallel to varStack[], is type mutable?
96
97 PtrVarState[] varPool; /// memory pool
98
99 ~this()
100 {
101 mem.xfree(varPool.ptr);
102 }
103 }
104
105 /***********************************************
106 * A node in the function's expression graph, and its edges to predecessors and successors.
107 */
108 struct ObNode
109 {
110 Expression exp; /// expression for the node
111 ObNodes preds; /// predecessors
112 ObNodes succs; /// successors
113 ObNode* tryBlock; /// try-finally block we're inside
114 ObType obtype;
115 uint index; /// index of this in obnodes
116
117 PtrVarState[] gen; /// new states generated for this node
118 PtrVarState[] input; /// variable states on entry to exp
119 PtrVarState[] output; /// variable states on exit to exp
120
121 this(ObNode* tryBlock) scope
122 {
123 this.tryBlock = tryBlock;
124 }
125
126 void print()
127 {
128 printf("%d: %s %s\n", index, obtype.toString.ptr, exp ? exp.toChars() : "-");
129 printf(" preds: ");
130 foreach (ob; preds)
131 printf(" %d", ob.index);
132 printf("\n succs: ");
133 foreach (ob; succs)
134 printf(" %d", ob.index);
135 printf("\n\n");
136 }
137 }
138
139
140 enum ObType : ubyte
141 {
142 goto_, /// goto one of the succs[]
143 return_, /// returns from function
144 retexp, /// returns expression from function
145 throw_, /// exits with throw
146 exit, /// exits program
147 try_,
148 finally_,
149 fend,
150 }
151
152 string toString(ObType obtype) @safe
153 {
154 return obtype == ObType.goto_ ? "goto " :
155 obtype == ObType.return_ ? "ret " :
156 obtype == ObType.retexp ? "retexp" :
157 obtype == ObType.throw_ ? "throw" :
158 obtype == ObType.exit ? "exit" :
159 obtype == ObType.try_ ? "try" :
160 obtype == ObType.finally_ ? "finally" :
161 obtype == ObType.fend ? "fend" :
162 "---";
163 }
164
165 /***********
166 Pointer variable states:
167
168 Initial state is not known; ignore for now
169
170 Undefined not in a usable state
171
172 T* p = void;
173
174 Owner mutable pointer
175
176 T* p = initializer;
177
178 Borrowed scope mutable pointer, borrowed from [p]
179
180 T* p = initializer;
181 scope T* b = p;
182
183 Readonly scope const pointer, copied from [p]
184
185 T* p = initializer;
186 scope const(T)* cp = p;
187
188 Examples:
189
190 T* p = initializer; // p is owner
191 T** pp = &p; // pp borrows from p
192
193 T* p = initialize; // p is owner
194 T* q = p; // transfer: q is owner, p is undefined
195 */
196
197 enum PtrState : ubyte
198 {
199 Initial, Undefined, Owner, Borrowed, Readonly
200 }
201
202 /************
203 */
204 const(char)* PtrStateToChars(PtrState state)
205 {
206 return toString(state).ptr;
207 }
208
209 string toString(PtrState state) @safe
210 {
211 return ["Initial", "Undefined", "Owner", "Borrowed", "Readonly"][state];
212 }
213
214 /******
215 * Carries the state of a pointer variable.
216 */
217 struct PtrVarState
218 {
219 BitArray deps; /// dependencies
220 PtrState state; /// state the pointer variable is in
221
222 void opAssign(const ref PtrVarState pvs)
223 {
224 state = pvs.state;
225 deps = pvs.deps;
226 }
227
228 /* Combine `this` and `pvs` into `this`,
229 * on the idea that the `this` and the `pvs` paths
230 * are being merged
231 * Params:
232 * pvs = path to be merged with `this`
233 * vi = variable's index into gen[]
234 * gen = array of variable states
235 */
236 void combine(ref PtrVarState pvs, size_t vi, PtrVarState[] gen)
237 {
238 static uint X(PtrState x1, PtrState x2) { return x1 * (PtrState.max + 1) + x2; }
239
240 with (PtrState)
241 {
242 switch (X(state, pvs.state))
243 {
244 case X(Initial, Initial):
245 break;
246
247 case X(Initial, Owner ):
248 case X(Initial, Borrowed ):
249 case X(Initial, Readonly ):
250 // Transfer state to `this`
251 state = pvs.state;
252 deps = pvs.deps;
253 break;
254
255 case X(Owner, Initial):
256 case X(Borrowed, Initial):
257 case X(Readonly, Initial):
258 break;
259
260 case X(Undefined, Initial):
261 case X(Undefined, Undefined):
262 case X(Undefined, Owner ):
263 case X(Undefined, Borrowed ):
264 case X(Undefined, Readonly ):
265 break;
266
267 case X(Owner , Owner ):
268 break;
269
270 case X(Borrowed , Borrowed):
271 case X(Readonly , Readonly):
272 deps.or(pvs.deps);
273 break;
274
275 default:
276 makeUndefined(vi, gen);
277 break;
278 }
279 }
280 }
281
282 bool opEquals(const ref PtrVarState pvs) const
283 {
284 return state == pvs.state &&
285 deps == pvs.deps;
286 }
287
288 /***********************
289 * Print a bracketed list of all the variables that depend on 'this'
290 * Params:
291 * vars = variables that depend on 'this'
292 */
293 void print(VarDeclaration[] vars)
294 {
295 string s = toString(state);
296 printf("%.*s [", cast(int)s.length, s.ptr);
297 assert(vars.length == deps.length);
298 OutBuffer buf;
299 depsToBuf(buf, vars);
300 auto t = buf[];
301 printf("%.*s]\n", cast(int)t.length, t.ptr);
302 }
303
304 /*****************************
305 * Produce a user-readable comma separated string of the
306 * dependencies.
307 * Params:
308 * buf = write resulting string here
309 * vars = array from which to get the variable names
310 */
311 void depsToBuf(ref OutBuffer buf, const VarDeclaration[] vars)
312 {
313 bool any = false;
314 foreach (i; 0 .. deps.length)
315 {
316 if (deps[i])
317 {
318 if (any)
319 buf.writestring(", ");
320 buf.writestring(vars[i].toString());
321 any = true;
322 }
323 }
324 }
325 }
326
327
328 /*****************************************
329 * Set the `.extra` field for LabelStatements in labtab[].
330 */
331 void setLabelStatementExtraFields(DsymbolTable labtab)
332 {
333 if (labtab)
334 foreach (keyValue; labtab.tab.asRange)
335 {
336 //printf(" KV: %s = %s\n", keyValue.key.toChars(), keyValue.value.toChars());
337 auto label = cast(LabelDsymbol)keyValue.value;
338 if (label.statement)
339 label.statement.extra = cast(void*) new ObNode(null);
340 }
341 }
342
343 /*****************************************
344 * Convert statement into ObNodes.
345 */
346
347 void toObNodes(ref ObNodes obnodes, Statement s)
348 {
349 ObNode* curblock = new ObNode(null);
350 obnodes.push(curblock);
351
352 void visit(Statement s, StmtState* stmtstate)
353 {
354 if (!s)
355 return;
356
357 ObNode* newNode()
358 {
359 return new ObNode(stmtstate.tryBlock);
360 }
361
362 ObNode* nextNodeIs(ObNode* ob)
363 {
364 obnodes.push(ob);
365 curblock = ob;
366 return ob;
367 }
368
369 ObNode* nextNode()
370 {
371 return nextNodeIs(newNode());
372 }
373
374 ObNode* gotoNextNodeIs(ObNode* ob)
375 {
376 obnodes.push(ob);
377 curblock.succs.push(ob);
378 curblock = ob;
379 return ob;
380 }
381
382 // block_goto(blx, BC.goto_, null)
383 ObNode* gotoNextNode()
384 {
385 return gotoNextNodeIs(newNode());
386 }
387
388 /***
389 * Doing a goto to dest
390 */
391 ObNode* gotoDest(ObNode* dest)
392 {
393 curblock.succs.push(dest);
394 return nextNode();
395 }
396
397 void visitExp(ExpStatement s)
398 {
399 curblock.obtype = ObType.goto_;
400 curblock.exp = s.exp;
401 gotoNextNode();
402 }
403
404 void visitDtorExp(DtorExpStatement s)
405 {
406 visitExp(s);
407 }
408
409 void visitCompound(CompoundStatement s)
410 {
411 if (s.statements)
412 {
413 foreach (s2; *s.statements)
414 {
415 visit(s2, stmtstate);
416 }
417 }
418 }
419
420 void visitCompoundDeclaration(CompoundDeclarationStatement s)
421 {
422 visitCompound(s);
423 }
424
425 void visitUnrolledLoop(UnrolledLoopStatement s)
426 {
427 StmtState mystate = StmtState(stmtstate, s);
428 mystate.breakBlock = newNode();
429
430 gotoNextNode();
431
432 foreach (s2; *s.statements)
433 {
434 if (s2)
435 {
436 mystate.contBlock = newNode();
437
438 visit(s2, &mystate);
439
440 gotoNextNodeIs(mystate.contBlock);
441 }
442 }
443
444 gotoNextNodeIs(mystate.breakBlock);
445 }
446
447 void visitScope(ScopeStatement s)
448 {
449 if (s.statement)
450 {
451 StmtState mystate = StmtState(stmtstate, s);
452
453 if (mystate.prev.ident)
454 mystate.ident = mystate.prev.ident;
455
456 visit(s.statement, &mystate);
457
458 if (mystate.breakBlock)
459 gotoNextNodeIs(mystate.breakBlock);
460 }
461 }
462
463 void visitDo(DoStatement s)
464 {
465 StmtState mystate = StmtState(stmtstate, s);
466 mystate.breakBlock = newNode();
467 mystate.contBlock = newNode();
468
469 auto bpre = curblock;
470
471 auto ob = newNode();
472 obnodes.push(ob);
473 curblock.succs.push(ob);
474 curblock = ob;
475 bpre.succs.push(curblock);
476
477 mystate.contBlock.succs.push(curblock);
478 mystate.contBlock.succs.push(mystate.breakBlock);
479
480 visit(s._body, &mystate);
481
482 gotoNextNodeIs(mystate.contBlock);
483 mystate.contBlock.exp = s.condition;
484 nextNodeIs(mystate.breakBlock);
485 }
486
487 void visitFor(ForStatement s)
488 {
489 //printf("visit(ForStatement)) %u..%u\n", s.loc.linnum, s.endloc.linnum);
490 StmtState mystate = StmtState(stmtstate, s);
491 mystate.breakBlock = newNode();
492 mystate.contBlock = newNode();
493
494 visit(s._init, &mystate);
495
496 auto bcond = gotoNextNode();
497 mystate.contBlock.succs.push(bcond);
498
499 if (s.condition)
500 {
501 bcond.exp = s.condition;
502 auto ob = newNode();
503 obnodes.push(ob);
504 bcond.succs.push(ob);
505 bcond.succs.push(mystate.breakBlock);
506 curblock = ob;
507 }
508 else
509 { /* No conditional, it's a straight goto
510 */
511 bcond.exp = s.condition;
512 bcond.succs.push(nextNode());
513 }
514
515 visit(s._body, &mystate);
516 /* End of the body goes to the continue block
517 */
518 curblock.succs.push(mystate.contBlock);
519 nextNodeIs(mystate.contBlock);
520
521 if (s.increment)
522 curblock.exp = s.increment;
523
524 /* The 'break' block follows the for statement.
525 */
526 nextNodeIs(mystate.breakBlock);
527 }
528
529 void visitIf(IfStatement s)
530 {
531 StmtState mystate = StmtState(stmtstate, s);
532
533 // bexit is the block that gets control after this IfStatement is done
534 auto bexit = mystate.breakBlock ? mystate.breakBlock : newNode();
535
536 curblock.exp = s.condition;
537
538 auto bcond = curblock;
539 gotoNextNode();
540
541 visit(s.ifbody, &mystate);
542 curblock.succs.push(bexit);
543
544 if (s.elsebody)
545 {
546 bcond.succs.push(nextNode());
547
548 visit(s.elsebody, &mystate);
549
550 gotoNextNodeIs(bexit);
551 }
552 else
553 {
554 bcond.succs.push(bexit);
555 nextNodeIs(bexit);
556 }
557 }
558
559 void visitSwitch(SwitchStatement s)
560 {
561 StmtState mystate = StmtState(stmtstate, s);
562
563 mystate.switchBlock = curblock;
564
565 /* Block for where "break" goes to
566 */
567 mystate.breakBlock = newNode();
568
569 /* Block for where "default" goes to.
570 * If there is a default statement, then that is where default goes.
571 * If not, then do:
572 * default: break;
573 * by making the default block the same as the break block.
574 */
575 mystate.defaultBlock = s.sdefault ? newNode() : mystate.breakBlock;
576
577 const numcases = s.cases ? s.cases.length : 0;
578
579 /* allocate a block for each case
580 */
581 if (numcases)
582 foreach (cs; *s.cases)
583 {
584 cs.extra = cast(void*)newNode();
585 }
586
587 curblock.exp = s.condition;
588
589 if (s.hasVars)
590 { /* Generate a sequence of if-then-else blocks for the cases.
591 */
592 if (numcases)
593 foreach (cs; *s.cases)
594 {
595 auto ecase = newNode();
596 obnodes.push(ecase);
597 ecase.exp = cs.exp;
598 curblock.succs.push(ecase);
599
600 auto cn = cast(ObNode*)cs.extra;
601 ecase.succs.push(cn);
602 ecase.succs.push(nextNode());
603 }
604
605 /* The final 'else' clause goes to the default
606 */
607 curblock.succs.push(mystate.defaultBlock);
608 nextNode();
609
610 visit(s._body, &mystate);
611
612 /* Have the end of the switch body fall through to the block
613 * following the switch statement.
614 */
615 gotoNextNodeIs(mystate.breakBlock);
616 return;
617 }
618
619 auto ob = newNode();
620 obnodes.push(ob);
621 curblock = ob;
622
623 mystate.switchBlock.succs.push(mystate.defaultBlock);
624
625 visit(s._body, &mystate);
626
627 /* Have the end of the switch body fall through to the block
628 * following the switch statement.
629 */
630 gotoNextNodeIs(mystate.breakBlock);
631 }
632
633 void visitCase(CaseStatement s)
634 {
635 auto cb = cast(ObNode*)s.extra;
636 cb.tryBlock = stmtstate.tryBlock;
637 auto bsw = stmtstate.getSwitchBlock();
638 bsw.succs.push(cb);
639 gotoNextNodeIs(cb);
640
641 visit(s.statement, stmtstate);
642 }
643
644 void visitDefault(DefaultStatement s)
645 {
646 auto bdefault = stmtstate.getDefaultBlock;
647 bdefault.tryBlock = stmtstate.tryBlock;
648 gotoNextNodeIs(bdefault);
649 visit(s.statement, stmtstate);
650 }
651
652 void visitGotoDefault(GotoDefaultStatement s)
653 {
654 gotoDest(stmtstate.getDefaultBlock);
655 }
656
657 void visitGotoCase(GotoCaseStatement s)
658 {
659 gotoDest(cast(ObNode*)s.cs.extra);
660 }
661
662 void visitSwitchError(SwitchErrorStatement s)
663 {
664 curblock.obtype = ObType.throw_;
665 curblock.exp = s.exp;
666
667 nextNode();
668 }
669
670 void visitReturn(ReturnStatement s)
671 {
672 //printf("visitReturn() %s\n", s.toChars());
673 curblock.obtype = s.exp && s.exp.type.toBasetype().ty != Tvoid
674 ? ObType.retexp
675 : ObType.return_;
676 curblock.exp = s.exp;
677
678 nextNode();
679 }
680
681 void visitBreak(BreakStatement s)
682 {
683 gotoDest(stmtstate.getBreakBlock(s.ident));
684 }
685
686 void visitContinue(ContinueStatement s)
687 {
688 gotoDest(stmtstate.getContBlock(s.ident));
689 }
690
691 void visitWith(WithStatement s)
692 {
693 visit(s._body, stmtstate);
694 }
695
696 void visitTryCatch(TryCatchStatement s)
697 {
698 /* tryblock
699 * body
700 * breakBlock
701 * catches
702 * breakBlock2
703 */
704
705 StmtState mystate = StmtState(stmtstate, s);
706 mystate.breakBlock = newNode();
707
708 auto tryblock = gotoNextNode();
709
710 visit(s._body, &mystate);
711
712 gotoNextNodeIs(mystate.breakBlock);
713
714 // create new break block that follows all the catches
715 auto breakBlock2 = newNode();
716
717 gotoDest(breakBlock2);
718
719 foreach (cs; *s.catches)
720 {
721 /* Each catch block is a successor to tryblock
722 * and the last block of try body
723 */
724 StmtState catchState = StmtState(stmtstate, s);
725
726 auto bcatch = curblock;
727 tryblock.succs.push(bcatch);
728 mystate.breakBlock.succs.push(bcatch);
729
730 nextNode();
731
732 visit(cs.handler, &catchState);
733
734 gotoDest(breakBlock2);
735 }
736
737 curblock.succs.push(breakBlock2);
738 obnodes.push(breakBlock2);
739 curblock = breakBlock2;
740 }
741
742 void visitTryFinally(TryFinallyStatement s)
743 {
744 /* Build this:
745 * 1 goto [2]
746 * 2 try_ [3] [5] [7]
747 * 3 body
748 * 4 goto [8]
749 * 5 finally_ [6]
750 * 6 finalbody
751 * 7 fend [8]
752 * 8 lastblock
753 */
754
755 StmtState bodyState = StmtState(stmtstate, s);
756
757 auto b2 = gotoNextNode();
758 b2.obtype = ObType.try_;
759 bodyState.tryBlock = b2;
760
761 gotoNextNode();
762
763 visit(s._body, &bodyState);
764
765 auto b4 = gotoNextNode();
766
767 auto b5 = newNode();
768 b5.obtype = ObType.finally_;
769 nextNodeIs(b5);
770 gotoNextNode();
771
772 StmtState finallyState = StmtState(stmtstate, s);
773 visit(s.finalbody, &finallyState);
774
775 auto b7 = gotoNextNode();
776 b7.obtype = ObType.fend;
777
778 auto b8 = gotoNextNode();
779
780 b2.succs.push(b5);
781 b2.succs.push(b7);
782
783 b4.succs.push(b8);
784 }
785
786 void visitThrow(ThrowStatement s)
787 {
788 curblock.obtype = ObType.throw_;
789 curblock.exp = s.exp;
790 nextNode();
791 }
792
793 void visitGoto(GotoStatement s)
794 {
795 gotoDest(cast(ObNode*)s.label.statement.extra);
796 }
797
798 void visitLabel(LabelStatement s)
799 {
800 StmtState mystate = StmtState(stmtstate, s);
801 mystate.ident = s.ident;
802
803 auto ob = cast(ObNode*)s.extra;
804 ob.tryBlock = mystate.tryBlock;
805 visit(s.statement, &mystate);
806 }
807
808 final switch (s.stmt)
809 {
810 case STMT.Exp: visitExp(s.isExpStatement()); break;
811 case STMT.DtorExp: visitDtorExp(s.isDtorExpStatement()); break;
812 case STMT.Compound: visitCompound(s.isCompoundStatement()); break;
813 case STMT.CompoundDeclaration: visitCompoundDeclaration(s.isCompoundDeclarationStatement()); break;
814 case STMT.UnrolledLoop: visitUnrolledLoop(s.isUnrolledLoopStatement()); break;
815 case STMT.Scope: visitScope(s.isScopeStatement()); break;
816 case STMT.Do: visitDo(s.isDoStatement()); break;
817 case STMT.For: visitFor(s.isForStatement()); break;
818 case STMT.If: visitIf(s.isIfStatement()); break;
819 case STMT.Switch: visitSwitch(s.isSwitchStatement()); break;
820 case STMT.Case: visitCase(s.isCaseStatement()); break;
821 case STMT.Default: visitDefault(s.isDefaultStatement()); break;
822 case STMT.GotoDefault: visitGotoDefault(s.isGotoDefaultStatement()); break;
823 case STMT.GotoCase: visitGotoCase(s.isGotoCaseStatement()); break;
824 case STMT.SwitchError: visitSwitchError(s.isSwitchErrorStatement()); break;
825 case STMT.Return: visitReturn(s.isReturnStatement()); break;
826 case STMT.Break: visitBreak(s.isBreakStatement()); break;
827 case STMT.Continue: visitContinue(s.isContinueStatement()); break;
828 case STMT.With: visitWith(s.isWithStatement()); break;
829 case STMT.TryCatch: visitTryCatch(s.isTryCatchStatement()); break;
830 case STMT.TryFinally: visitTryFinally(s.isTryFinallyStatement()); break;
831 case STMT.Throw: visitThrow(s.isThrowStatement()); break;
832 case STMT.Goto: visitGoto(s.isGotoStatement()); break;
833 case STMT.Label: visitLabel(s.isLabelStatement()); break;
834
835 case STMT.CompoundAsm:
836 case STMT.Asm:
837 case STMT.InlineAsm:
838 case STMT.GccAsm:
839
840 case STMT.Pragma:
841 case STMT.Import:
842 case STMT.ScopeGuard:
843 case STMT.Error:
844 break; // ignore these
845
846 case STMT.Foreach:
847 case STMT.ForeachRange:
848 case STMT.Debug:
849 case STMT.CaseRange:
850 case STMT.StaticForeach:
851 case STMT.StaticAssert:
852 case STMT.Conditional:
853 case STMT.While:
854 case STMT.Forwarding:
855 case STMT.Mixin:
856 case STMT.Peel:
857 case STMT.Synchronized:
858 debug printf("s: %s\n", toChars(s));
859 assert(0); // should have been rewritten
860 }
861 }
862
863 StmtState stmtstate;
864 visit(s, &stmtstate);
865 curblock.obtype = ObType.return_;
866
867 static if (0)
868 {
869 printf("toObNodes()\n");
870 printf("------- before ----------\n");
871 numberNodes(obnodes);
872 foreach (ob; obnodes) ob.print();
873 printf("-------------------------\n");
874 }
875
876 assert(stmtstate.breakBlock is null);
877 assert(stmtstate.contBlock is null);
878 assert(stmtstate.switchBlock is null);
879 assert(stmtstate.defaultBlock is null);
880 assert(stmtstate.tryBlock is null);
881 }
882
883 /***************************************************
884 * Insert finally block calls when doing a goto from
885 * inside a try block to outside.
886 * Done after blocks are generated because then we know all
887 * the edges of the graph, but before the pred's are computed.
888 * Params:
889 * obnodes = graph of the function
890 */
891
892 void insertFinallyBlockCalls(ref ObNodes obnodes)
893 {
894 ObNode* bcret = null;
895 ObNode* bcretexp = null;
896
897 enum log = false;
898
899 static if (log)
900 {
901 printf("insertFinallyBlockCalls()\n");
902 printf("------- before ----------\n");
903 numberNodes(obnodes);
904 foreach (ob; obnodes) ob.print();
905 printf("-------------------------\n");
906 }
907
908 foreach (ob; obnodes)
909 {
910 if (!ob.tryBlock)
911 continue;
912
913 switch (ob.obtype)
914 {
915 case ObType.return_:
916 // Rewrite into a ObType.goto_ => ObType.return_
917 if (!bcret)
918 {
919 bcret = new ObNode();
920 bcret.obtype = ob.obtype;
921 }
922 ob.obtype = ObType.goto_;
923 ob.succs.push(bcret);
924 goto case_goto;
925
926 case ObType.retexp:
927 // Rewrite into a ObType.goto_ => ObType.retexp
928 if (!bcretexp)
929 {
930 bcretexp = new ObNode();
931 bcretexp.obtype = ob.obtype;
932 }
933 ob.obtype = ObType.goto_;
934 ob.succs.push(bcretexp);
935 goto case_goto;
936
937 case ObType.goto_:
938 if (ob.succs.length != 1)
939 break;
940
941 case_goto:
942 {
943 auto target = ob.succs[0]; // destination of goto
944 ob.succs.setDim(0);
945 auto lasttry = target.tryBlock;
946 auto blast = ob;
947 for (auto bt = ob.tryBlock; bt != lasttry; bt = bt.tryBlock)
948 {
949 assert(bt.obtype == ObType.try_);
950 auto bf = bt.succs[1];
951 assert(bf.obtype == ObType.finally_);
952 auto bfend = bt.succs[2];
953 assert(bfend.obtype == ObType.fend);
954
955 if (!blast.succs.contains(bf.succs[0]))
956 blast.succs.push(bf.succs[0]);
957
958 blast = bfend;
959 }
960 if (!blast.succs.contains(target))
961 blast.succs.push(target);
962
963 break;
964 }
965
966 default:
967 break;
968 }
969 }
970 if (bcret)
971 obnodes.push(bcret);
972 if (bcretexp)
973 obnodes.push(bcretexp);
974
975 static if (log)
976 {
977 printf("------- after ----------\n");
978 numberNodes(obnodes);
979 foreach (ob; obnodes) ob.print();
980 printf("-------------------------\n");
981 }
982 }
983
984 /***************************************************
985 * Remove try-finally scaffolding.
986 * Params:
987 * obnodes = nodes for the function
988 */
989
990 void insertFinallyBlockGotos(ref ObNodes obnodes)
991 {
992 /* Remove all the try_, finally_, lpad and ret nodes.
993 * Actually, just make them into no-ops.
994 */
995 foreach (ob; obnodes)
996 {
997 ob.tryBlock = null;
998 switch (ob.obtype)
999 {
1000 case ObType.try_:
1001 ob.obtype = ObType.goto_;
1002 ob.succs.remove(2); // remove fend
1003 ob.succs.remove(1); // remove finally_
1004 break;
1005
1006 case ObType.finally_:
1007 ob.obtype = ObType.goto_;
1008 break;
1009
1010 case ObType.fend:
1011 ob.obtype = ObType.goto_;
1012 break;
1013
1014 default:
1015 break;
1016 }
1017 }
1018 }
1019
1020 /*********************************
1021 * Set the `index` field of each ObNode
1022 * to its index in the `obnodes[]` array.
1023 */
1024 void numberNodes(ref ObNodes obnodes) @safe
1025 {
1026 //printf("numberNodes()\n");
1027 foreach (i, ob; obnodes)
1028 {
1029 //printf("ob = %d, %p\n", i, ob);
1030 ob.index = cast(uint)i;
1031 }
1032
1033 // Verify that nodes do not appear more than once in obnodes[]
1034 debug
1035 foreach (i, ob; obnodes)
1036 {
1037 assert(ob.index == cast(uint)i);
1038 }
1039 }
1040
1041
1042 /*********************************
1043 * Remove unreachable nodes and compress
1044 * them out of obnodes[].
1045 * Params:
1046 * obnodes = array of nodes
1047 */
1048 void removeUnreachable(ref ObNodes obnodes)
1049 {
1050 if (!obnodes.length)
1051 return;
1052
1053 /* Mark all nodes as unreachable,
1054 * temporarilly reusing ObNode.index
1055 */
1056 foreach (ob; obnodes)
1057 ob.index = 0;
1058
1059 /* Recursively mark ob and all its successors as reachable
1060 */
1061 static void mark(ObNode* ob)
1062 {
1063 ob.index = 1;
1064 foreach (succ; ob.succs)
1065 {
1066 if (!succ.index)
1067 mark(succ);
1068 }
1069 }
1070
1071 mark(obnodes[0]); // first node is entry point
1072
1073 /* Remove unreachable nodes by shifting the remainder left
1074 */
1075 size_t j = 1;
1076 foreach (i; 1 .. obnodes.length)
1077 {
1078 if (obnodes[i].index)
1079 {
1080 if (i != j)
1081 obnodes[j] = obnodes[i];
1082 ++j;
1083 }
1084 else
1085 {
1086 obnodes[i].destroy();
1087 }
1088 }
1089 obnodes.setDim(j);
1090 }
1091
1092
1093
1094 /*************************************
1095 * Compute predecessors.
1096 */
1097 void computePreds(ref ObNodes obnodes)
1098 {
1099 foreach (ob; obnodes)
1100 {
1101 foreach (succ; ob.succs)
1102 {
1103 succ.preds.push(ob);
1104 }
1105 }
1106 }
1107
1108 /*******************************
1109 * Are we interested in tracking variable `v`?
1110 */
1111 bool isTrackableVar(VarDeclaration v)
1112 {
1113 //printf("isTrackableVar() %s\n", v.toChars());
1114 auto tb = v.type.toBasetype();
1115
1116 /* Assume class references are managed by the GC,
1117 * don't need to track them
1118 */
1119 if (tb.ty == Tclass)
1120 return false;
1121
1122 /* Assume types with a destructor are doing their own tracking,
1123 * such as being a ref counted type
1124 */
1125 // if (v.needsScopeDtor())
1126 // return false;
1127
1128 /* Not tracking function parameters that are not mutable
1129 */
1130 if (v.storage_class & STC.parameter && !tb.hasPointersToMutableFields())
1131 return false;
1132
1133 /* Not tracking global variables
1134 */
1135 return !v.isDataseg();
1136 }
1137
1138 /*******************************
1139 * Are we interested in tracking this expression?
1140 * Returns:
1141 * variable if so, null if not
1142 */
1143 VarDeclaration isTrackableVarExp(Expression e)
1144 {
1145 if (auto ve = e.isVarExp())
1146 {
1147 if (auto v = ve.var.isVarDeclaration())
1148 if (isTrackableVar(v))
1149 return v;
1150 }
1151 return null;
1152 }
1153
1154
1155 /**************
1156 * Find the pointer variable declarations in this function,
1157 * and fill `vars` with them.
1158 * Params:
1159 * funcdecl = function we are in
1160 * vars = array to fill in
1161 */
1162 void collectVars(FuncDeclaration funcdecl, out VarDeclarations vars)
1163 {
1164 enum log = false;
1165 if (log)
1166 printf("----------------collectVars()---------------\n");
1167
1168 if (funcdecl.parameters)
1169 foreach (v; (*funcdecl.parameters)[])
1170 {
1171 if (isTrackableVar(v))
1172 vars.push(v);
1173 }
1174
1175 void dgVar(VarDeclaration v)
1176 {
1177 if (isTrackableVar(v))
1178 vars.push(v);
1179 }
1180
1181 void dgExp(Expression e)
1182 {
1183 foreachVar(e, &dgVar);
1184 }
1185
1186 foreachExpAndVar(funcdecl.fbody, &dgExp, &dgVar);
1187
1188 static if (log)
1189 {
1190 foreach (i, v; vars[])
1191 {
1192 printf("vars[%d] = %s\n", cast(int)i, v.toChars());
1193 }
1194 }
1195 }
1196
1197 /***********************************
1198 * Allocate BitArrays in PtrVarState.
1199 * Can be allocated much more efficiently by subdividing a single
1200 * large array of bits
1201 */
1202 void allocDeps(PtrVarState[] pvss)
1203 {
1204 //printf("allocDeps()\n");
1205 foreach (ref pvs; pvss)
1206 {
1207 pvs.deps.length = pvss.length;
1208 }
1209 }
1210
1211
1212 /**************************************
1213 * Allocate state variables foreach node.
1214 */
1215 void allocStates(ref ObState obstate)
1216 {
1217 //printf("---------------allocStates()------------------\n");
1218 const vlen = obstate.vars.length;
1219 PtrVarState* p = cast(PtrVarState*) mem.xcalloc(obstate.nodes.length * 3 * vlen, PtrVarState.sizeof);
1220 obstate.varPool = p[0 .. obstate.nodes.length * 3 * vlen];
1221 foreach (i, ob; obstate.nodes)
1222 {
1223 //printf(" [%d]\n", cast(int)i);
1224 // ob.kill.length = obstate.vars.length;
1225 // ob.comb.length = obstate.vars.length;
1226 ob.gen = p[0 .. vlen]; p += vlen;
1227 ob.input = p[0 .. vlen]; p += vlen;
1228 ob.output = p[0 .. vlen]; p += vlen;
1229
1230 allocDeps(ob.gen);
1231 allocDeps(ob.input);
1232 allocDeps(ob.output);
1233 }
1234 }
1235
1236 /******************************
1237 * Does v meet the definiton of a `Borrowed` pointer?
1238 * Returns:
1239 * true if it does
1240 */
1241 bool isBorrowedPtr(VarDeclaration v)
1242 {
1243 return v.isScope() && !v.isowner &&
1244 v.type.hasPointersToMutableFields();
1245 }
1246
1247 /******************************
1248 * Does v meet the definiton of a `Readonly` pointer?
1249 * Returns:
1250 * true if it does
1251 */
1252 bool isReadonlyPtr(VarDeclaration v)
1253 {
1254 return v.isScope() && !v.type.hasPointersToMutableFields();
1255 }
1256
1257 /***************************************
1258 * Compute the gen vector for ob.
1259 */
1260 void genKill(ref ObState obstate, ObNode* ob)
1261 {
1262 enum log = false;
1263 if (log)
1264 printf("-----------computeGenKill() %d -----------\n", ob.index);
1265
1266 /***************
1267 * Assigning result of expression `e` to variable `v`.
1268 */
1269 void dgWriteVar(ObNode* ob, VarDeclaration v, Expression e, bool initializer)
1270 {
1271 if (log)
1272 printf("dgWriteVar() %s := %s %d\n", v.toChars(), e.toChars(), initializer);
1273 const vi = obstate.vars.find(v);
1274 assert(vi != size_t.max);
1275 PtrVarState* pvs = &ob.gen[vi];
1276 readVar(ob, vi, true, ob.gen);
1277 if (e)
1278 {
1279 if (isBorrowedPtr(v))
1280 pvs.state = PtrState.Borrowed;
1281 else if (isReadonlyPtr(v))
1282 pvs.state = PtrState.Readonly;
1283 else
1284 pvs.state = PtrState.Owner;
1285 pvs.deps.zero();
1286
1287 bool any = false; // if any variables are assigned to v
1288
1289 void by(VarDeclaration r)
1290 {
1291 const ri = obstate.vars.find(r);
1292 if (ri != size_t.max && ri != vi)
1293 {
1294 pvs.deps[ri] = true; // v took from r
1295 auto pvsr = &ob.gen[ri];
1296 any = true;
1297
1298 if (isBorrowedPtr(v))
1299 {
1300 // v is borrowing from r
1301 pvs.state = PtrState.Borrowed;
1302 }
1303 else if (isReadonlyPtr(v))
1304 {
1305 pvs.state = PtrState.Readonly;
1306 }
1307 else
1308 {
1309 // move r to v, which "consumes" r
1310 pvsr.state = PtrState.Undefined;
1311 pvsr.deps.zero();
1312 }
1313 }
1314 }
1315
1316 escapeLive(e, &by);
1317
1318 /* Make v an Owner for initializations like:
1319 * scope v = malloc();
1320 */
1321 if (initializer && !any && isBorrowedPtr(v))
1322 {
1323 v.isowner = true;
1324 pvs.state = PtrState.Owner;
1325 }
1326 }
1327 else
1328 {
1329 if (isBorrowedPtr(v))
1330 pvs.state = PtrState.Borrowed;
1331 else if (isReadonlyPtr(v))
1332 pvs.state = PtrState.Readonly;
1333 else
1334 pvs.state = PtrState.Owner;
1335 pvs.deps.zero();
1336 }
1337 }
1338
1339 void dgReadVar(Loc loc, ObNode* ob, VarDeclaration v, bool mutable)
1340 {
1341 if (log)
1342 printf("dgReadVar() %s %d\n", v.toChars(), mutable);
1343 const vi = obstate.vars.find(v);
1344 assert(vi != size_t.max);
1345 readVar(ob, vi, mutable, ob.gen);
1346 }
1347
1348 void foreachExp(ObNode* ob, Expression e)
1349 {
1350 extern (C++) final class ExpWalker : Visitor
1351 {
1352 alias visit = typeof(super).visit;
1353 extern (D) void delegate(ObNode*, VarDeclaration, Expression, bool) dgWriteVar;
1354 extern (D) void delegate(Loc loc, ObNode* ob, VarDeclaration v, bool mutable) dgReadVar;
1355 ObNode* ob;
1356 ObState* obstate;
1357
1358 extern (D) this(void delegate(ObNode*, VarDeclaration, Expression, bool) dgWriteVar,
1359 void delegate(Loc loc, ObNode* ob, VarDeclaration v, bool mutable) dgReadVar,
1360 ObNode* ob, ref ObState obstate) scope
1361 {
1362 this.dgWriteVar = dgWriteVar;
1363 this.dgReadVar = dgReadVar;
1364 this.ob = ob;
1365 this.obstate = &obstate;
1366 }
1367
1368 override void visit(Expression e)
1369 {
1370 //printf("[%s] %s: %s\n", e.loc.toChars(), EXPtoString(e.op).ptr, e.toChars());
1371 //assert(0);
1372 }
1373
1374 void visitAssign(AssignExp ae, bool initializer)
1375 {
1376 ae.e2.accept(this);
1377 if (auto ve = ae.e1.isVarExp())
1378 {
1379 if (auto v = ve.var.isVarDeclaration())
1380 if (isTrackableVar(v))
1381 dgWriteVar(ob, v, ae.e2, initializer);
1382 }
1383 else
1384 ae.e1.accept(this);
1385 }
1386
1387 override void visit(AssignExp ae)
1388 {
1389 visitAssign(ae, false);
1390 }
1391
1392 override void visit(DeclarationExp e)
1393 {
1394 void Dsymbol_visit(Dsymbol s)
1395 {
1396 if (auto vd = s.isVarDeclaration())
1397 {
1398 s = s.toAlias();
1399 if (s != vd)
1400 return Dsymbol_visit(s);
1401 if (!isTrackableVar(vd))
1402 return;
1403
1404 if (!(vd._init && vd._init.isVoidInitializer()))
1405 {
1406 auto ei = vd._init ? vd._init.isExpInitializer() : null;
1407 if (ei)
1408 visitAssign(cast(AssignExp)ei.exp, true);
1409 else
1410 dgWriteVar(ob, vd, null, false);
1411 }
1412 }
1413 else if (auto td = s.isTupleDeclaration())
1414 {
1415 td.foreachVar(&Dsymbol_visit);
1416 }
1417 }
1418
1419 Dsymbol_visit(e.declaration);
1420 }
1421
1422 override void visit(VarExp ve)
1423 {
1424 //printf("VarExp: %s\n", ve.toChars());
1425 if (auto v = ve.var.isVarDeclaration())
1426 if (isTrackableVar(v))
1427 {
1428 dgReadVar(ve.loc, ob, v, isMutableRef(ve.type));
1429 }
1430 }
1431
1432 override void visit(CallExp ce)
1433 {
1434 //printf("CallExp() %s\n", ce.toChars());
1435 ce.e1.accept(this);
1436 auto t = ce.e1.type.toBasetype();
1437 auto tf = t.isTypeFunction();
1438 if (!tf)
1439 {
1440 assert(t.ty == Tdelegate);
1441 tf = t.nextOf().isTypeFunction();
1442 assert(tf);
1443
1444 }
1445
1446 if (auto dve = ce.e1.isDotVarExp())
1447 {
1448 if (!t.isTypeDelegate() && dve.e1.isVarExp())
1449 {
1450 //printf("dve: %s\n", dve.toChars());
1451
1452 void byf(VarDeclaration v)
1453 {
1454 //printf("byf v: %s\n", v.ident.toChars());
1455 if (!isTrackableVar(v))
1456 return;
1457
1458 const vi = obstate.vars.find(v);
1459 if (vi == size_t.max)
1460 return;
1461
1462 auto fd = dve.var.isFuncDeclaration();
1463 if (fd && fd.storage_class & STC.scope_)
1464 {
1465 // borrow
1466 obstate.varStack.push(vi);
1467 obstate.mutableStack.push(isMutableRef(dve.e1.type.toBasetype()));
1468 }
1469 else
1470 {
1471 // move (i.e. consume arg)
1472 makeUndefined(vi, ob.gen);
1473 }
1474 }
1475
1476 escapeLive(dve.e1, &byf);
1477 }
1478 }
1479
1480 // j=1 if _arguments[] is first argument
1481 const int j = tf.isDstyleVariadic();
1482 bool hasOut;
1483 const varStackSave = obstate.varStack.length;
1484
1485 foreach (const i, arg; (*ce.arguments)[])
1486 {
1487 if (i - j < tf.parameterList.length &&
1488 i >= j)
1489 {
1490 Parameter p = tf.parameterList[i - j];
1491 auto pt = p.type.toBasetype();
1492
1493
1494 if (!(p.storageClass & STC.out_ && arg.isVarExp()))
1495 arg.accept(this);
1496
1497 void by(VarDeclaration v)
1498 {
1499 //printf("by v: %s\n", v.ident.toChars());
1500 if (!isTrackableVar(v))
1501 return;
1502
1503 const vi = obstate.vars.find(v);
1504 if (vi == size_t.max)
1505 return;
1506
1507 if (p.storageClass & STC.out_)
1508 {
1509 /// initialize
1510 hasOut = true;
1511 makeUndefined(vi, ob.gen);
1512 }
1513 else if (p.storageClass & STC.scope_)
1514 {
1515 // borrow
1516 obstate.varStack.push(vi);
1517 obstate.mutableStack.push(isMutableRef(pt));
1518 }
1519 else
1520 {
1521 // move (i.e. consume arg)
1522 makeUndefined(vi, ob.gen);
1523 }
1524 }
1525
1526 escapeLive(arg, &by);
1527 }
1528 else // variadic args
1529 {
1530 arg.accept(this);
1531
1532 void byv(VarDeclaration v)
1533 {
1534 if (!isTrackableVar(v))
1535 return;
1536
1537 const vi = obstate.vars.find(v);
1538 if (vi == size_t.max)
1539 return;
1540
1541 if (tf.parameterList.stc & STC.scope_)
1542 {
1543 // borrow
1544 obstate.varStack.push(vi);
1545 obstate.mutableStack.push(isMutableRef(arg.type) &&
1546 !(tf.parameterList.stc & (STC.const_ | STC.immutable_)));
1547 }
1548 else
1549 // move (i.e. consume arg)
1550 makeUndefined(vi, ob.gen);
1551 }
1552
1553 escapeLive(arg, &byv);
1554 }
1555 }
1556
1557 /* Do a dummy 'read' of each variable passed to the function,
1558 * to detect O/B errors
1559 */
1560 assert(obstate.varStack.length == obstate.mutableStack.length);
1561 foreach (i; varStackSave .. obstate.varStack.length)
1562 {
1563 const vi = obstate.varStack[i];
1564 // auto pvs = &ob.gen[vi];
1565 auto v = obstate.vars[vi];
1566 //if (pvs.state == PtrState.Undefined)
1567 //v.error(ce.loc, "is Undefined, cannot pass to function");
1568
1569 dgReadVar(ce.loc, ob, v, obstate.mutableStack[i]);
1570 }
1571
1572 /* Pop off stack all variables for this function call
1573 */
1574 obstate.varStack.setDim(varStackSave);
1575 obstate.mutableStack.setDim(varStackSave);
1576
1577 if (hasOut)
1578 // Initialization of out's only happens after the function call
1579 foreach (const i, arg; (*ce.arguments)[])
1580 {
1581 if (i - j < tf.parameterList.length &&
1582 i >= j)
1583 {
1584 Parameter p = tf.parameterList[i - j];
1585 if (p.storageClass & STC.out_)
1586 {
1587 if (auto v = isTrackableVarExp(arg))
1588 dgWriteVar(ob, v, null, true);
1589 }
1590 }
1591 }
1592 }
1593
1594 override void visit(SymOffExp e)
1595 {
1596 if (auto v = e.var.isVarDeclaration())
1597 if (isTrackableVar(v))
1598 {
1599 dgReadVar(e.loc, ob, v, isMutableRef(e.type));
1600 }
1601 }
1602
1603 override void visit(LogicalExp e)
1604 {
1605 e.e1.accept(this);
1606
1607 const vlen = obstate.vars.length;
1608 auto p = cast(PtrVarState*)mem.xcalloc(vlen, PtrVarState.sizeof);
1609 PtrVarState[] gen1 = p[0 .. vlen];
1610 foreach (i, ref pvs; gen1)
1611 {
1612 pvs = ob.gen[i];
1613 }
1614
1615 e.e2.accept(this);
1616
1617 // Merge gen1 into ob.gen
1618 foreach (i; 0 .. vlen)
1619 {
1620 ob.gen[i].combine(gen1[i], i, ob.gen);
1621 }
1622
1623 mem.xfree(p); // should free .deps too
1624 }
1625
1626 override void visit(CondExp e)
1627 {
1628 e.econd.accept(this);
1629
1630 const vlen = obstate.vars.length;
1631 auto p = cast(PtrVarState*)mem.xcalloc(vlen, PtrVarState.sizeof);
1632 PtrVarState[] gen1 = p[0 .. vlen];
1633 foreach (i, ref pvs; gen1)
1634 {
1635 pvs = ob.gen[i];
1636 }
1637
1638 e.e1.accept(this);
1639
1640 // Swap gen1 with ob.gen
1641 foreach (i; 0 .. vlen)
1642 {
1643 gen1[i].deps.swap(ob.gen[i].deps);
1644 const state = gen1[i].state;
1645 gen1[i].state = ob.gen[i].state;
1646 ob.gen[i].state = state;
1647 }
1648
1649 e.e2.accept(this);
1650
1651 /* xxx1 is the state from expression e1, ob.xxx is the state from e2.
1652 * Merge xxx1 into ob.xxx to get the state from `e`.
1653 */
1654 foreach (i; 0 .. vlen)
1655 {
1656 ob.gen[i].combine(gen1[i], i, ob.gen);
1657 }
1658
1659 mem.xfree(p); // should free .deps too
1660 }
1661
1662 override void visit(AddrExp e)
1663 {
1664 /* Taking the address of struct literal is normally not
1665 * allowed, but CTFE can generate one out of a new expression,
1666 * but it'll be placed in static data so no need to check it.
1667 */
1668 if (e.e1.op != EXP.structLiteral)
1669 e.e1.accept(this);
1670 }
1671
1672 override void visit(UnaExp e)
1673 {
1674 e.e1.accept(this);
1675 }
1676
1677 override void visit(BinExp e)
1678 {
1679 e.e1.accept(this);
1680 e.e2.accept(this);
1681 }
1682
1683 override void visit(ArrayLiteralExp e)
1684 {
1685 Type tb = e.type.toBasetype();
1686 if (tb.isStaticOrDynamicArray())
1687 {
1688 if (e.basis)
1689 e.basis.accept(this);
1690 foreach (el; *e.elements)
1691 {
1692 if (el)
1693 el.accept(this);
1694 }
1695 }
1696 }
1697
1698 override void visit(StructLiteralExp e)
1699 {
1700 if (e.elements)
1701 {
1702 foreach (ex; *e.elements)
1703 {
1704 if (ex)
1705 ex.accept(this);
1706 }
1707 }
1708 }
1709
1710 override void visit(AssocArrayLiteralExp e)
1711 {
1712 if (e.keys)
1713 {
1714 foreach (i, key; *e.keys)
1715 {
1716 if (key)
1717 key.accept(this);
1718 if (auto value = (*e.values)[i])
1719 value.accept(this);
1720 }
1721 }
1722 }
1723
1724 override void visit(NewExp e)
1725 {
1726 if (e.placement)
1727 e.placement.accept(this);
1728 if (e.arguments)
1729 {
1730 foreach (ex; *e.arguments)
1731 {
1732 if (ex)
1733 ex.accept(this);
1734 }
1735 }
1736 }
1737
1738 override void visit(SliceExp e)
1739 {
1740 e.e1.accept(this);
1741 if (e.lwr)
1742 e.lwr.accept(this);
1743 if (e.upr)
1744 e.upr.accept(this);
1745 }
1746 }
1747
1748 if (e)
1749 {
1750 scope ExpWalker ew = new ExpWalker(&dgWriteVar, &dgReadVar, ob, obstate);
1751 e.accept(ew);
1752 }
1753 }
1754
1755 foreachExp(ob, ob.exp);
1756
1757 if (log)
1758 {
1759 printf(" gen:\n");
1760 foreach (i, ref pvs2; ob.gen[])
1761 {
1762 printf(" %s: ", obstate.vars[i].toChars()); pvs2.print(obstate.vars[]);
1763 }
1764 }
1765 }
1766
1767 /***************************************
1768 * Determine the state of a variable based on
1769 * its type and storage class.
1770 */
1771 PtrState toPtrState(VarDeclaration v)
1772 {
1773 /* pointer to mutable: Owner
1774 * pointer to mutable, scope: Borrowed
1775 * pointer to const: Owner
1776 * pointer to const, scope: Readonly
1777 * ref: Borrowed
1778 * const ref: Readonly
1779 */
1780
1781 auto t = v.type;
1782 if (v.isReference())
1783 {
1784 return t.hasMutableFields() ? PtrState.Borrowed : PtrState.Readonly;
1785 }
1786 if (v.isScope())
1787 {
1788 return t.hasPointersToMutableFields() ? PtrState.Borrowed : PtrState.Readonly;
1789 }
1790 else
1791 return PtrState.Owner;
1792 }
1793
1794 /**********************************
1795 * Does type `t` contain any pointers to mutable?
1796 */
1797 bool hasPointersToMutableFields(Type t)
1798 {
1799 auto tb = t.toBasetype();
1800 if (!tb.isMutable())
1801 return false;
1802 if (auto tsa = tb.isTypeSArray())
1803 {
1804 return tsa.nextOf().hasPointersToMutableFields();
1805 }
1806 if (auto ts = tb.isTypeStruct())
1807 {
1808 foreach (v; ts.sym.fields)
1809 {
1810 if (v.isReference())
1811 {
1812 if (v.type.hasMutableFields())
1813 return true;
1814 }
1815 else if (v.type.hasPointersToMutableFields())
1816 return true;
1817 }
1818 return false;
1819 }
1820 auto tbn = tb.nextOf();
1821 return tbn && tbn.hasMutableFields();
1822 }
1823
1824 /********************************
1825 * Does type `t` have any mutable fields?
1826 */
1827 bool hasMutableFields(Type t)
1828 {
1829 auto tb = t.toBasetype();
1830 if (!tb.isMutable())
1831 return false;
1832 if (auto tsa = tb.isTypeSArray())
1833 {
1834 return tsa.nextOf().hasMutableFields();
1835 }
1836 if (auto ts = tb.isTypeStruct())
1837 {
1838 foreach (v; ts.sym.fields)
1839 {
1840 if (v.type.hasMutableFields())
1841 return true;
1842 }
1843 return false;
1844 }
1845 return true;
1846 }
1847
1848
1849
1850 /***************************************
1851 * Do the data flow analysis (i.e. compute the input[]
1852 * and output[] vectors for each ObNode).
1853 */
1854 void doDataFlowAnalysis(ref ObState obstate)
1855 {
1856 enum log = false;
1857 if (log)
1858 {
1859 printf("-----------------doDataFlowAnalysis()-------------------------\n");
1860 foreach (ob; obstate.nodes) ob.print();
1861 printf("------------------------------------------\n");
1862 }
1863
1864 if (!obstate.nodes.length)
1865 return;
1866
1867 auto startnode = obstate.nodes[0];
1868 assert(startnode.preds.length == 0);
1869
1870 /* Set opening state `input[]` for first node
1871 */
1872 foreach (i, ref ps; startnode.input)
1873 {
1874 auto v = obstate.vars[i];
1875 auto state = toPtrState(v);
1876 if (v.isParameter())
1877 {
1878 if (v.isOut())
1879 state = PtrState.Undefined;
1880 else if (v.isBorrowedPtr())
1881 state = PtrState.Borrowed;
1882 else
1883 state = PtrState.Owner;
1884 }
1885 else
1886 state = PtrState.Undefined;
1887 ps.state = state;
1888 ps.deps.zero();
1889 startnode.gen[i] = ps;
1890 }
1891
1892 /* Set all output[]s to Initial
1893 */
1894 foreach (ob; obstate.nodes[])
1895 {
1896 foreach (ref ps; ob.output)
1897 {
1898 ps.state = PtrState.Initial;
1899 ps.deps.zero();
1900 }
1901 }
1902
1903 const vlen = obstate.vars.length;
1904 PtrVarState pvs;
1905 pvs.deps.length = vlen;
1906 int counter = 0;
1907 bool changes;
1908 do
1909 {
1910 changes = false;
1911 assert(++counter <= 1000); // should converge, but don't hang if it doesn't
1912 foreach (ob; obstate.nodes[])
1913 {
1914 /* Construct ob.gen[] by combining the .output[]s of each ob.preds[]
1915 * and set ob.input[] to the same state
1916 */
1917 if (ob != startnode)
1918 {
1919 assert(ob.preds.length);
1920
1921 foreach (i; 0 .. vlen)
1922 {
1923 ob.gen[i] = ob.preds[0].output[i];
1924 }
1925
1926 foreach (j; 1 .. ob.preds.length)
1927 {
1928 foreach (i; 0 .. vlen)
1929 {
1930 ob.gen[i].combine(ob.preds[j].output[i], i, ob.gen);
1931 }
1932 }
1933
1934 /* Set ob.input[] to ob.gen[],
1935 * if any changes were made we'll have to do another iteration
1936 */
1937 foreach (i; 0 .. vlen)
1938 {
1939 if (ob.gen[i] != ob.input[i])
1940 {
1941 ob.input[i] = ob.gen[i];
1942 changes = true;
1943 }
1944 }
1945 }
1946
1947 /* Compute gen[] for node ob
1948 */
1949 genKill(obstate, ob);
1950
1951 foreach (i; 0 .. vlen)
1952 {
1953 if (ob.gen[i] != ob.output[i])
1954 {
1955 ob.output[i] = ob.gen[i];
1956 changes = true;
1957 }
1958 }
1959 }
1960 } while (changes);
1961
1962 static if (log)
1963 {
1964 foreach (obi, ob; obstate.nodes)
1965 {
1966 printf("%d: %s\n", obi, ob.exp ? ob.exp.toChars() : "".ptr);
1967 printf(" input:\n");
1968 foreach (i, ref pvs2; ob.input[])
1969 {
1970 printf(" %s: ", obstate.vars[i].toChars()); pvs2.print(obstate.vars[]);
1971 }
1972
1973 printf(" gen:\n");
1974 foreach (i, ref pvs2; ob.gen[])
1975 {
1976 printf(" %s: ", obstate.vars[i].toChars()); pvs2.print(obstate.vars[]);
1977 }
1978 printf(" output:\n");
1979 foreach (i, ref pvs2; ob.output[])
1980 {
1981 printf(" %s: ", obstate.vars[i].toChars()); pvs2.print(obstate.vars[]);
1982 }
1983 }
1984 printf("\n");
1985 }
1986 }
1987
1988
1989 /***************************************
1990 * Check for escaping variables using DIP1000's `escapeByValue`, with `live` set to `true`
1991 * Params:
1992 * e = expression to check
1993 * onVar = gets called for each variable escaped through `e`, either by value or by ref
1994 */
1995 void escapeLive(Expression e, scope void delegate(VarDeclaration) onVar)
1996 {
1997 scope EscapeByResults er = EscapeByResults(
1998 (VarDeclaration v, bool) => onVar(v),
1999 onVar,
2000 (FuncDeclaration f, bool) {},
2001 (Expression e, bool) {},
2002 true,
2003 );
2004
2005 escapeByValue(e, er);
2006 }
2007
2008 /***************************************
2009 * Check for Ownership/Borrowing errors.
2010 */
2011 void checkObErrors(ref ObState obstate)
2012 {
2013 enum log = false;
2014 if (log)
2015 printf("------------checkObErrors()----------\n");
2016
2017 void dgWriteVar(ObNode* ob, PtrVarState[] cpvs, VarDeclaration v, Expression e)
2018 {
2019 if (log) printf("dgWriteVar(v:%s, e:%s)\n", v.toChars(), e ? e.toChars() : "null");
2020 const vi = obstate.vars.find(v);
2021 assert(vi != size_t.max);
2022 PtrVarState* pvs = &cpvs[vi];
2023 readVar(ob, vi, true, cpvs);
2024 if (e)
2025 {
2026 if (isBorrowedPtr(v))
2027 pvs.state = PtrState.Borrowed;
2028 else if (isReadonlyPtr(v))
2029 pvs.state = PtrState.Readonly;
2030 else
2031 {
2032 if (pvs.state == PtrState.Owner && v.type.hasPointersToMutableFields())
2033 .error(e.loc, "%s `%s` assigning to Owner without disposing of owned value", v.kind, v.toPrettyChars);
2034
2035 pvs.state = PtrState.Owner;
2036 }
2037 pvs.deps.zero();
2038
2039
2040 void by(VarDeclaration r) // `v` = `r`
2041 {
2042 //printf(" by(%s)\n", r.toChars());
2043 const ri = obstate.vars.find(r);
2044 if (ri == size_t.max)
2045 return;
2046
2047 with (PtrState)
2048 {
2049 pvs.deps[ri] = true; // v took from r
2050 auto pvsr = &cpvs[ri];
2051
2052 if (pvsr.state == Undefined)
2053 {
2054 .error(e.loc, "%s `%s` is reading from `%s` which is Undefined", v.kind, v.toPrettyChars, r.toChars());
2055 }
2056 else if (isBorrowedPtr(v)) // v is going to borrow from r
2057 {
2058 if (pvsr.state == Readonly)
2059 .error(e.loc, "%s `%s` is borrowing from `%s` which is Readonly", v.kind, v.toPrettyChars, r.toChars());
2060
2061 pvs.state = Borrowed;
2062 }
2063 else if (isReadonlyPtr(v))
2064 {
2065 pvs.state = Readonly;
2066 }
2067 else
2068 {
2069 // move from r to v
2070 pvsr.state = Undefined;
2071 pvsr.deps.zero();
2072 }
2073 }
2074 }
2075
2076 escapeLive(e, &by);
2077 }
2078 else
2079 {
2080 if (isBorrowedPtr(v))
2081 pvs.state = PtrState.Borrowed;
2082 else if (isReadonlyPtr(v))
2083 pvs.state = PtrState.Readonly;
2084 else
2085 pvs.state = PtrState.Owner;
2086 pvs.deps.zero();
2087 }
2088 }
2089
2090 void dgReadVar(Loc loc, ObNode* ob, VarDeclaration v, bool mutable, PtrVarState[] gen)
2091 {
2092 if (log) printf("dgReadVar() %s\n", v.toChars());
2093 const vi = obstate.vars.find(v);
2094 assert(vi != size_t.max);
2095 auto pvs = &gen[vi];
2096 if (pvs.state == PtrState.Undefined)
2097 .error(loc, "%s `%s` has undefined state and cannot be read", v.kind, v.toPrettyChars);
2098
2099 readVar(ob, vi, mutable, gen);
2100 }
2101
2102 void foreachExp(ObNode* ob, Expression e, PtrVarState[] cpvs)
2103 {
2104 extern (C++) final class ExpWalker : Visitor
2105 {
2106 alias visit = typeof(super).visit;
2107 extern (D) void delegate(ObNode*, PtrVarState[], VarDeclaration, Expression) dgWriteVar;
2108 extern (D) void delegate(Loc loc, ObNode* ob, VarDeclaration v, bool mutable, PtrVarState[]) dgReadVar;
2109 PtrVarState[] cpvs;
2110 ObNode* ob;
2111 ObState* obstate;
2112
2113 extern (D) this(void delegate(Loc loc, ObNode* ob, VarDeclaration v, bool mutable, PtrVarState[]) dgReadVar,
2114 void delegate(ObNode*, PtrVarState[], VarDeclaration, Expression) dgWriteVar,
2115 PtrVarState[] cpvs, ObNode* ob, ref ObState obstate) scope
2116 {
2117 this.dgReadVar = dgReadVar;
2118 this.dgWriteVar = dgWriteVar;
2119 this.cpvs = cpvs;
2120 this.ob = ob;
2121 this.obstate = &obstate;
2122 }
2123
2124 override void visit(Expression)
2125 {
2126 }
2127
2128 override void visit(DeclarationExp e)
2129 {
2130 void Dsymbol_visit(Dsymbol s)
2131 {
2132 if (auto vd = s.isVarDeclaration())
2133 {
2134 s = s.toAlias();
2135 if (s != vd)
2136 return Dsymbol_visit(s);
2137 if (!isTrackableVar(vd))
2138 return;
2139
2140 if (vd._init && vd._init.isVoidInitializer())
2141 return;
2142
2143 auto ei = vd._init ? vd._init.isExpInitializer() : null;
2144 if (ei)
2145 {
2146 auto e = ei.exp;
2147 if (auto ae = e.isConstructExp())
2148 e = ae.e2;
2149 dgWriteVar(ob, cpvs, vd, e);
2150 }
2151 else
2152 dgWriteVar(ob, cpvs, vd, null);
2153 }
2154 else if (auto td = s.isTupleDeclaration())
2155 {
2156 td.foreachVar(&Dsymbol_visit);
2157 }
2158 }
2159
2160 Dsymbol_visit(e.declaration);
2161 }
2162
2163 override void visit(AssignExp ae)
2164 {
2165 ae.e2.accept(this);
2166 if (auto ve = ae.e1.isVarExp())
2167 {
2168 if (auto v = ve.var.isVarDeclaration())
2169 if (isTrackableVar(v))
2170 dgWriteVar(ob, cpvs, v, ae.e2);
2171 }
2172 else
2173 ae.e1.accept(this);
2174 }
2175
2176 override void visit(VarExp ve)
2177 {
2178 //printf("VarExp: %s\n", ve.toChars());
2179 if (auto v = ve.var.isVarDeclaration())
2180 if (isTrackableVar(v))
2181 {
2182 dgReadVar(ve.loc, ob, v, isMutableRef(ve.type), cpvs);
2183 }
2184 }
2185
2186 override void visit(CallExp ce)
2187 {
2188 //printf("CallExp(%s)\n", ce.toChars());
2189 ce.e1.accept(this);
2190 auto t = ce.e1.type.toBasetype();
2191 auto tf = t.isTypeFunction();
2192 if (!tf)
2193 {
2194 assert(t.ty == Tdelegate);
2195 tf = t.nextOf().isTypeFunction();
2196 assert(tf);
2197 }
2198
2199 // j=1 if _arguments[] is first argument
2200 const int j = tf.isDstyleVariadic();
2201 bool hasOut;
2202 const varStackSave = obstate.varStack.length;
2203
2204 foreach (const i, arg; (*ce.arguments)[])
2205 {
2206 if (i - j < tf.parameterList.length &&
2207 i >= j)
2208 {
2209 Parameter p = tf.parameterList[i - j];
2210 auto pt = p.type.toBasetype();
2211
2212 if (!(p.storageClass & STC.out_ && arg.isVarExp()))
2213 arg.accept(this);
2214
2215
2216 void by(VarDeclaration v)
2217 {
2218 if (!isTrackableVar(v))
2219 return;
2220
2221 const vi = obstate.vars.find(v);
2222 if (vi == size_t.max)
2223 return;
2224
2225 auto pvs = &cpvs[vi];
2226
2227 if (p.storageClass & STC.out_)
2228 {
2229 /// initialize
2230 hasOut = true;
2231 makeUndefined(vi, cpvs);
2232 }
2233 else if (p.storageClass & STC.scope_)
2234 {
2235 // borrow
2236 obstate.varStack.push(vi);
2237 obstate.mutableStack.push(isMutableRef(pt));
2238 }
2239 else
2240 {
2241 // move (i.e. consume arg)
2242 if (pvs.state != PtrState.Owner)
2243 .error(arg.loc, "%s `%s` is not Owner, cannot consume its value", v.kind, v.toPrettyChars);
2244 makeUndefined(vi, cpvs);
2245 }
2246 }
2247
2248 escapeLive(arg, &by);
2249 }
2250 else // variadic args
2251 {
2252 arg.accept(this);
2253 void byv(VarDeclaration v)
2254 {
2255 if (!isTrackableVar(v))
2256 return;
2257
2258 const vi = obstate.vars.find(v);
2259 if (vi == size_t.max)
2260 return;
2261
2262 auto pvs = &cpvs[vi];
2263
2264 if (tf.parameterList.stc & STC.scope_)
2265 {
2266 // borrow
2267 obstate.varStack.push(vi);
2268 obstate.mutableStack.push(isMutableRef(arg.type) &&
2269 !(tf.parameterList.stc & (STC.const_ | STC.immutable_)));
2270 }
2271 else
2272 {
2273 // move (i.e. consume arg)
2274 if (pvs.state != PtrState.Owner)
2275 .error(arg.loc, "%s `%s` is not Owner, cannot consume its value", v.kind, v.toPrettyChars);
2276 makeUndefined(vi, cpvs);
2277 }
2278 }
2279
2280 escapeLive(arg, &byv);
2281 }
2282 }
2283
2284 /* Do a dummy 'read' of each variable passed to the function,
2285 * to detect O/B errors
2286 */
2287 assert(obstate.varStack.length == obstate.mutableStack.length);
2288 foreach (i; varStackSave .. obstate.varStack.length)
2289 {
2290 const vi = obstate.varStack[i];
2291 auto pvs = &cpvs[vi];
2292 auto v = obstate.vars[vi];
2293 //if (pvs.state == PtrState.Undefined)
2294 //v.error(ce.loc, "is Undefined, cannot pass to function");
2295
2296 dgReadVar(ce.loc, ob, v, obstate.mutableStack[i], cpvs);
2297
2298 if (pvs.state == PtrState.Owner)
2299 {
2300 for (size_t k = i + 1; k < obstate.varStack.length;++k)
2301 {
2302 const vk = obstate.varStack[k];
2303 if (vk == vi)
2304 {
2305 if (obstate.mutableStack[vi] || obstate.mutableStack[vk])
2306 {
2307 .error(ce.loc, "%s `%s` is passed as Owner more than once", v.kind, v.toPrettyChars);
2308 break; // no need to continue
2309 }
2310 }
2311 }
2312 }
2313 }
2314
2315 /* Pop off stack all variables for this function call
2316 */
2317 obstate.varStack.setDim(varStackSave);
2318 obstate.mutableStack.setDim(varStackSave);
2319
2320 if (hasOut)
2321 // Initialization of out's only happens after the function call
2322 foreach (const i, arg; (*ce.arguments)[])
2323 {
2324 if (i - j < tf.parameterList.length &&
2325 i >= j)
2326 {
2327 Parameter p = tf.parameterList[i - j];
2328 if (p.storageClass & STC.out_)
2329 {
2330 if (auto v = isTrackableVarExp(arg))
2331 {
2332 dgWriteVar(ob, cpvs, v, null);
2333 }
2334 }
2335 }
2336 }
2337 }
2338
2339 override void visit(SymOffExp e)
2340 {
2341 if (auto v = e.var.isVarDeclaration())
2342 if (isTrackableVar(v))
2343 {
2344 dgReadVar(e.loc, ob, v, isMutableRef(e.type), cpvs);
2345 }
2346 }
2347
2348 override void visit(LogicalExp e)
2349 {
2350 e.e1.accept(this);
2351
2352 const vlen = obstate.vars.length;
2353 auto p = cast(PtrVarState*)mem.xcalloc(vlen, PtrVarState.sizeof);
2354 PtrVarState[] out1 = p[0 .. vlen];
2355 foreach (i, ref pvs; out1)
2356 {
2357 pvs = cpvs[i];
2358 }
2359
2360 e.e2.accept(this);
2361
2362 // Merge out1 into cpvs
2363 foreach (i; 0 .. vlen)
2364 {
2365 cpvs[i].combine(out1[i], i, cpvs);
2366 }
2367
2368 mem.xfree(p); // should free .deps too
2369 }
2370
2371 override void visit(CondExp e)
2372 {
2373 e.econd.accept(this);
2374
2375 const vlen = obstate.vars.length;
2376 auto p = cast(PtrVarState*)mem.xcalloc(vlen, PtrVarState.sizeof);
2377 PtrVarState[] out1 = p[0 .. vlen];
2378 foreach (i, ref pvs; out1)
2379 {
2380 pvs = cpvs[i];
2381 }
2382
2383 e.e1.accept(this);
2384
2385 // Swap out1 with cpvs
2386 foreach (i; 0 .. vlen)
2387 {
2388 out1[i].deps.swap(cpvs[i].deps);
2389 const state = out1[i].state;
2390 out1[i].state = cpvs[i].state;
2391 cpvs[i].state = state;
2392 }
2393
2394 e.e2.accept(this);
2395
2396 // Merge out1 into cpvs
2397 foreach (i; 0 .. vlen)
2398 {
2399 cpvs[i].combine(out1[i], i, cpvs);
2400 }
2401
2402 mem.xfree(p); // should free .deps too
2403 }
2404
2405 override void visit(AddrExp e)
2406 {
2407 /* Taking the address of struct literal is normally not
2408 * allowed, but CTFE can generate one out of a new expression,
2409 * but it'll be placed in static data so no need to check it.
2410 */
2411 if (e.e1.op != EXP.structLiteral)
2412 e.e1.accept(this);
2413 }
2414
2415 override void visit(UnaExp e)
2416 {
2417 e.e1.accept(this);
2418 }
2419
2420 override void visit(BinExp e)
2421 {
2422 e.e1.accept(this);
2423 e.e2.accept(this);
2424 }
2425
2426 override void visit(ArrayLiteralExp e)
2427 {
2428 Type tb = e.type.toBasetype();
2429 if (tb.isStaticOrDynamicArray())
2430 {
2431 if (e.basis)
2432 e.basis.accept(this);
2433 foreach (el; *e.elements)
2434 {
2435 if (el)
2436 el.accept(this);
2437 }
2438 }
2439 }
2440
2441 override void visit(StructLiteralExp e)
2442 {
2443 if (e.elements)
2444 {
2445 foreach (ex; *e.elements)
2446 {
2447 if (ex)
2448 ex.accept(this);
2449 }
2450 }
2451 }
2452
2453 override void visit(AssocArrayLiteralExp e)
2454 {
2455 if (e.keys)
2456 {
2457 foreach (i, key; *e.keys)
2458 {
2459 if (key)
2460 key.accept(this);
2461 if (auto value = (*e.values)[i])
2462 value.accept(this);
2463 }
2464 }
2465 }
2466
2467 override void visit(NewExp e)
2468 {
2469 if (e.placement)
2470 e.placement.accept(this);
2471
2472 if (e.arguments)
2473 {
2474 foreach (ex; *e.arguments)
2475 {
2476 if (ex)
2477 ex.accept(this);
2478 }
2479 }
2480 }
2481
2482 override void visit(SliceExp e)
2483 {
2484 e.e1.accept(this);
2485 if (e.lwr)
2486 e.lwr.accept(this);
2487 if (e.upr)
2488 e.upr.accept(this);
2489 }
2490 }
2491
2492 if (e)
2493 {
2494 scope ExpWalker ew = new ExpWalker(&dgReadVar, &dgWriteVar, cpvs, ob, obstate);
2495 e.accept(ew);
2496 }
2497 }
2498
2499 const vlen = obstate.vars.length;
2500 auto p = cast(PtrVarState*)mem.xcalloc(vlen, PtrVarState.sizeof);
2501 PtrVarState[] cpvs = p[0 .. vlen];
2502 foreach (ref pvs; cpvs)
2503 pvs.deps.length = vlen;
2504
2505 foreach (obi, ob; obstate.nodes)
2506 {
2507 static if (log)
2508 {
2509 printf("%d: %s\n", cast(int) obi, ob.exp ? ob.exp.toChars() : "".ptr);
2510 printf(" input:\n");
2511 foreach (i, ref pvs; ob.input[])
2512 {
2513 printf(" %s: ", obstate.vars[i].toChars()); pvs.print(obstate.vars[]);
2514 }
2515 }
2516
2517 /* Combine the .output[]s of each ob.preds[] looking for errors
2518 */
2519 if (obi) // skip startnode
2520 {
2521 assert(ob.preds.length);
2522
2523 foreach (i; 0 .. vlen)
2524 {
2525 ob.gen[i] = ob.preds[0].output[i];
2526 }
2527
2528 foreach (j; 1 .. ob.preds.length)
2529 {
2530 foreach (i; 0 .. vlen)
2531 {
2532 auto pvs1 = &ob.gen[i];
2533 auto pvs2 = &ob.preds[j].output[i];
2534 const s1 = pvs1.state;
2535 const s2 = pvs2.state;
2536 if (s1 != s2 && (s1 == PtrState.Owner || s2 == PtrState.Owner))
2537 {
2538 auto v = obstate.vars[i];
2539 // Don't worry about non-pointers
2540 if (hasPointers(v.type))
2541 .error(ob.exp ? ob.exp.loc : v.loc, "%s `%s` is both %s and %s", v.kind, v.toPrettyChars, PtrStateToChars(s1), PtrStateToChars(s2));
2542 }
2543 pvs1.combine(*pvs2, i, ob.gen);
2544 }
2545 }
2546 }
2547
2548 /* Prolly should use gen[] instead of cpvs[], or vice versa
2549 */
2550 foreach (i, ref pvs; ob.input)
2551 {
2552 cpvs[i] = pvs;
2553 }
2554
2555 foreachExp(ob, ob.exp, cpvs);
2556
2557 static if (log)
2558 {
2559 printf(" cpvs:\n");
2560 foreach (i, ref pvs; cpvs[])
2561 {
2562 printf(" %s: ", obstate.vars[i].toChars()); pvs.print(obstate.vars[]);
2563 }
2564 printf(" output:\n");
2565 foreach (i, ref pvs; ob.output[])
2566 {
2567 printf(" %s: ", obstate.vars[i].toChars()); pvs.print(obstate.vars[]);
2568 }
2569 }
2570
2571 if (ob.obtype == ObType.retexp)
2572 {
2573 void by(VarDeclaration r) // `r` is the rvalue
2574 {
2575 const ri = obstate.vars.find(r);
2576 if (ri == size_t.max)
2577 return;
2578 with (PtrState)
2579 {
2580 auto pvsr = &ob.output[ri];
2581 switch (pvsr.state)
2582 {
2583 case Undefined:
2584 .error(ob.exp.loc, "%s `%s` is returned but is Undefined", r.kind, r.toPrettyChars);
2585 break;
2586
2587 case Owner:
2588 pvsr.state = Undefined; // returning a pointer "consumes" it
2589 break;
2590
2591 case Borrowed:
2592 case Readonly:
2593 break;
2594
2595 default:
2596 assert(0);
2597 }
2598 }
2599 }
2600 escapeLive(ob.exp, &by);
2601 }
2602
2603 if (ob.obtype == ObType.return_ || ob.obtype == ObType.retexp)
2604 {
2605 foreach (i, ref pvs; ob.output[])
2606 {
2607 //printf("%s: ", obstate.vars[i].toChars()); pvs.print(obstate.vars[]);
2608 if (pvs.state == PtrState.Owner)
2609 {
2610 import dmd.typesem : hasPointers;
2611 auto v = obstate.vars[i];
2612 if (v.type.hasPointers())
2613 .error(v.loc, "%s `%s` is not disposed of before return", v.kind, v.toPrettyChars);
2614 }
2615 }
2616 }
2617 }
2618 }
2619
2620
2621 /***************************************************
2622 * Read from variable vi.
2623 * The beginning of the 'scope' of a variable is when it is first read.
2624 * Hence, when a read is done, instead of when assignment to the variable is done, the O/B rules are enforced.
2625 * (Also called "non-lexical scoping".)
2626 */
2627 void readVar(ObNode* ob, const size_t vi, bool mutable, PtrVarState[] gen)
2628 {
2629 //printf("readVar(v%d)\n", cast(int)vi);
2630 auto pvso = &gen[vi];
2631 switch (pvso.state)
2632 {
2633 case PtrState.Owner:
2634 //printf("t: %s\n", t.toChars());
2635 if (mutable) // if mutable read
2636 {
2637 makeChildrenUndefined(vi, gen);
2638 }
2639 else // const read
2640 {
2641 // If there's a Borrow child, set that to Undefined
2642 foreach (di; 0 .. gen.length)
2643 {
2644 auto pvsd = &gen[di];
2645 if (pvsd.deps[vi] && pvsd.state == PtrState.Borrowed) // if di borrowed vi
2646 {
2647 makeUndefined(di, gen);
2648 }
2649 }
2650 }
2651 break;
2652
2653 case PtrState.Borrowed:
2654 /* All children become Undefined
2655 */
2656 makeChildrenUndefined(vi, gen);
2657 break;
2658
2659 case PtrState.Readonly:
2660 break;
2661
2662 case PtrState.Undefined:
2663 break;
2664
2665 default:
2666 break;
2667 }
2668 }
2669
2670 /********************
2671 * Recursively make Undefined all who list vi as a dependency
2672 */
2673 void makeChildrenUndefined(size_t vi, PtrVarState[] gen)
2674 {
2675 //printf("makeChildrenUndefined(%d)\n", vi);
2676 foreach (di; 0 .. gen.length)
2677 {
2678 if (gen[di].deps[vi]) // if di depends on vi
2679 {
2680 if (gen[di].state != PtrState.Undefined)
2681 {
2682 gen[di].state = PtrState.Undefined; // set this first to avoid infinite recursion
2683 makeChildrenUndefined(di, gen);
2684 gen[di].deps.zero();
2685 }
2686 }
2687 }
2688 }
2689
2690
2691 /********************
2692 * Recursively make Undefined vi undefined and all who list vi as a dependency
2693 * Params:
2694 * vi = variable's index
2695 * gen = array of the states of variables
2696 */
2697 void makeUndefined(size_t vi, PtrVarState[] gen)
2698 {
2699 auto pvs = &gen[vi];
2700 pvs.state = PtrState.Undefined; // set this first to avoid infinite recursion
2701 makeChildrenUndefined(vi, gen);
2702 pvs.deps.zero();
2703 }
2704
2705 /*************************
2706 * Is type `t` a reference to a const or a reference to a mutable?
2707 */
2708 bool isMutableRef(Type t)
2709 {
2710 auto tb = t.toBasetype();
2711 return (tb.nextOf() ? tb.nextOf() : tb).isMutable();
2712 }