2 * Most of the logic to implement scoped pointers and scoped references is here.
4 * Copyright: Copyright (C) 1999-2022 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/src/dmd/escape.d, _escape.d)
8 * Documentation: https://dlang.org/phobos/dmd_escape.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/escape.d
14 import core.stdc.stdio : printf;
15 import core.stdc.stdlib;
16 import core.stdc.string;
22 import dmd.declaration;
26 import dmd.expression;
30 import dmd.identifier;
34 import dmd.root.rootobject;
37 import dmd.arraytypes;
39 /******************************************************
40 * Checks memory objects passed to a function.
41 * Checks that if a memory object is passed by ref or by pointer,
42 * all of the refs or pointers are const, or there is only one mutable
43 * ref or pointer to it.
47 * sc = used to determine current function and module
48 * fd = function being called
50 * ethis = if not null, the `this` pointer
51 * arguments = actual arguments to function
52 * gag = do not print error messages
56 bool checkMutableArguments(Scope* sc, FuncDeclaration fd, TypeFunction tf,
57 Expression ethis, Expressions* arguments, bool gag)
60 if (log) printf("[%s] checkMutableArguments, fd: `%s`\n", fd.loc.toChars(), fd.toChars());
61 if (log && ethis) printf("ethis: `%s`\n", ethis.toChars());
64 /* Outer variable references are treated as if they are extra arguments
65 * passed by ref to the function (which they essentially are via the static link).
67 VarDeclaration[] outerVars = fd ? fd.outerVars[] : null;
69 const len = arguments.length + (ethis !is null) + outerVars.length;
76 Parameter param; // null if no Parameter for this argument
77 bool isMutable; // true if reference to mutable
80 /* Store escapeBy as static data escapeByStorage so we can keep reusing the same
81 * arrays rather than reallocating them.
83 __gshared EscapeBy[] escapeByStorage;
84 auto escapeBy = escapeByStorage;
85 if (escapeBy.length < len)
87 auto newPtr = cast(EscapeBy*)mem.xrealloc(escapeBy.ptr, len * EscapeBy.sizeof);
88 // Clear the new section
89 memset(newPtr + escapeBy.length, 0, (len - escapeBy.length) * EscapeBy.sizeof);
90 escapeBy = newPtr[0 .. len];
91 escapeByStorage = escapeBy;
94 escapeBy = escapeBy[0 .. len];
96 const paramLength = tf.parameterList.length;
98 // Fill in escapeBy[] with arguments[], ethis, and outerVars[]
99 foreach (const i, ref eb; escapeBy)
103 if (i < arguments.length)
105 arg = (*arguments)[i];
108 eb.param = tf.parameterList[i];
109 refs = eb.param.isReference();
110 eb.isMutable = eb.param.isReferenceToMutable(arg.type);
116 eb.isMutable = arg.type.isReferenceToMutable();
121 /* ethis is passed by value if a class reference,
122 * by ref if a struct value
126 auto ad = fd.isThis();
129 if (ad.isClassDeclaration())
132 eb.isMutable = arg.type.isReferenceToMutable();
136 assert(ad.isStructDeclaration());
138 eb.isMutable = arg.type.isMutable();
143 // outer variables are passed by ref
146 auto var = outerVars[i - (len - outerVars.length)];
147 eb.isMutable = var.type.isMutable();
148 eb.er.byref.push(var);
153 escapeByRef(arg, &eb.er);
155 escapeByValue(arg, &eb.er);
158 void checkOnePair(size_t i, ref EscapeBy eb, ref EscapeBy eb2,
159 VarDeclaration v, VarDeclaration v2, bool of)
161 if (log) printf("v2: `%s`\n", v2.toChars());
164 //printf("v %d v2 %d\n", eb.isMutable, eb2.isMutable);
165 if (!(eb.isMutable || eb2.isMutable))
168 if (!(global.params.useDIP1000 == FeatureState.enabled && sc.func.setUnsafe()))
173 // int i; funcThatEscapes(ref int i);
174 // funcThatEscapes(i); // error escaping reference _to_ `i`
175 // int* j; funcThatEscapes2(int* j);
176 // funcThatEscapes2(j); // error escaping reference _of_ `i`
177 const(char)* referenceVerb = of ? "of" : "to";
178 const(char)* msg = eb.isMutable && eb2.isMutable
179 ? "more than one mutable reference %s `%s` in arguments to `%s()`"
180 : "mutable and const references %s `%s` in arguments to `%s()`";
181 error((*arguments)[i].loc, msg,
184 fd ? fd.toPrettyChars() : "indirectly");
189 void escape(size_t i, ref EscapeBy eb, bool byval)
191 foreach (VarDeclaration v; byval ? eb.er.byvalue : eb.er.byref)
195 const(char)* by = byval ? "byval" : "byref";
196 printf("%s %s\n", by, v.toChars());
198 if (byval && !v.type.hasPointers())
200 foreach (ref eb2; escapeBy[i + 1 .. $])
202 foreach (VarDeclaration v2; byval ? eb2.er.byvalue : eb2.er.byref)
204 checkOnePair(i, eb, eb2, v, v2, byval);
209 foreach (const i, ref eb; escapeBy[0 .. $ - 1])
212 escape(i, eb, false);
215 /* Reset the arrays in escapeBy[] so we can reuse them next time through
217 foreach (ref eb; escapeBy)
225 /******************************************
226 * Array literal is going to be allocated on the GC heap.
227 * Check its elements to see if any would escape by going on the heap.
229 * sc = used to determine current function and module
230 * ae = array literal expression
231 * gag = do not print error messages
233 * `true` if any elements escaped
235 bool checkArrayLiteralEscape(Scope *sc, ArrayLiteralExp ae, bool gag)
239 errors = checkNewEscape(sc, ae.basis, gag);
240 foreach (ex; *ae.elements)
243 errors |= checkNewEscape(sc, ex, gag);
248 /******************************************
249 * Associative array literal is going to be allocated on the GC heap.
250 * Check its elements to see if any would escape by going on the heap.
252 * sc = used to determine current function and module
253 * ae = associative array literal expression
254 * gag = do not print error messages
256 * `true` if any elements escaped
258 bool checkAssocArrayLiteralEscape(Scope *sc, AssocArrayLiteralExp ae, bool gag)
261 foreach (ex; *ae.keys)
264 errors |= checkNewEscape(sc, ex, gag);
266 foreach (ex; *ae.values)
269 errors |= checkNewEscape(sc, ex, gag);
274 /****************************************
275 * Function parameter `par` is being initialized to `arg`,
276 * and `par` may escape.
277 * Detect if scoped values can escape this way.
278 * Print error messages when these are detected.
280 * sc = used to determine current function and module
281 * fdc = function being called, `null` if called indirectly
282 * par = function parameter (`this` if null)
283 * arg = initializer for param
284 * assertmsg = true if the parameter is the msg argument to assert(bool, msg).
285 * gag = do not print error messages
287 * `true` if pointers to the stack can escape via assignment
289 bool checkParamArgumentEscape(Scope* sc, FuncDeclaration fdc, Parameter par, Expression arg, bool assertmsg, bool gag)
292 if (log) printf("checkParamArgumentEscape(arg: %s par: %s)\n",
293 arg ? arg.toChars() : "null",
294 par ? par.toChars() : "this");
295 //printf("type = %s, %d\n", arg.type.toChars(), arg.type.hasPointers());
297 if (!arg.type.hasPointers())
302 escapeByValue(arg, &er);
304 if (!er.byref.dim && !er.byvalue.dim && !er.byfunc.dim && !er.byexp.dim)
310 if (par && fdc && fdc.type.isTypeFunction())
311 psr = buildScopeRef(par.storageClass);
315 /* 'v' is assigned unsafely to 'par'
317 void unsafeAssign(VarDeclaration v, const char* desc)
319 if (setUnsafeDIP1000(sc.func))
325 previewErrorFunc(sc.isDeprecated(), global.params.useDIP1000)
326 (arg.loc, "%s `%s` assigned to non-scope parameter calling `assert()`",
331 previewErrorFunc(sc.isDeprecated(), global.params.useDIP1000)
332 (arg.loc, "%s `%s` assigned to non-scope parameter `%s` calling %s",
334 par ? par.toChars() : "this",
335 fdc ? fdc.toPrettyChars() : "indirectly");
338 if (global.params.useDIP1000 == FeatureState.enabled)
343 foreach (VarDeclaration v; er.byvalue)
345 if (log) printf("byvalue %s\n", v.toChars());
349 Dsymbol p = v.toParent2();
355 unsafeAssign(v, "scope variable");
357 else if (v.storage_class & STC.variadic && p == sc.func)
359 Type tb = v.type.toBasetype();
360 if (tb.ty == Tarray || tb.ty == Tsarray)
362 unsafeAssign(v, "variadic variable");
367 /* v is not 'scope', and is assigned to a parameter that may escape.
368 * Therefore, v can never be 'scope'.
370 if (log) printf("no infer for %s in %s loc %s, fdc %s, %d\n",
371 v.toChars(), sc.func.ident.toChars(), sc.func.loc.toChars(), fdc.ident.toChars(), __LINE__);
372 v.doNotInferScope = true;
376 foreach (VarDeclaration v; er.byref)
378 if (log) printf("byref %s\n", v.toChars());
382 Dsymbol p = v.toParent2();
388 if (psr == ScopeRef.Scope ||
389 psr == ScopeRef.RefScope ||
390 psr == ScopeRef.ReturnRef_Scope)
395 unsafeAssign(v, "reference to local variable");
400 foreach (FuncDeclaration fd; er.byfunc)
402 //printf("fd = %s, %d\n", fd.toChars(), fd.tookAddressOf);
403 VarDeclarations vars;
404 findAllOuterAccessedVariables(fd, &vars);
408 //printf("v = %s\n", v.toChars());
409 assert(!v.isDataseg()); // these are not put in the closureVars[]
411 Dsymbol p = v.toParent2();
415 if ((v.isReference() || v.isScope()) && p == sc.func)
417 unsafeAssign(v, "reference to local");
423 foreach (Expression ee; er.byexp)
425 if (sc.func && sc.func.setUnsafe())
428 error(ee.loc, "reference to stack allocated value returned by `%s` assigned to non-scope parameter `%s`",
430 par ? par.toChars() : "this");
438 /*****************************************************
439 * Function argument initializes a `return` parameter,
440 * and that parameter gets assigned to `firstArg`.
441 * Essentially, treat as `firstArg = arg;`
443 * sc = used to determine current function and module
444 * firstArg = `ref` argument through which `arg` may be assigned
445 * arg = initializer for parameter
446 * param = parameter declaration corresponding to `arg`
447 * gag = do not print error messages
449 * `true` if assignment to `firstArg` would cause an error
451 bool checkParamArgumentReturn(Scope* sc, Expression firstArg, Expression arg, Parameter param, bool gag)
454 if (log) printf("checkParamArgumentReturn(firstArg: %s arg: %s)\n",
455 firstArg.toChars(), arg.toChars());
456 //printf("type = %s, %d\n", arg.type.toChars(), arg.type.hasPointers());
458 if (!(param.storageClass & STC.return_))
461 if (!arg.type.hasPointers() && !param.isReference())
464 // `byRef` needed for `assign(ref int* x, ref int i) {x = &i};`
465 // Note: taking address of scope pointer is not allowed
466 // `assign(ref int** x, return ref scope int* i) {x = &i};`
467 // Thus no return ref/return scope ambiguity here
468 const byRef = param.isReference() && !(param.storageClass & STC.scope_)
469 && !(param.storageClass & STC.returnScope); // fixme: it's possible to infer returnScope without scope with vaIsFirstRef
471 scope e = new AssignExp(arg.loc, firstArg, arg);
472 return checkAssignEscape(sc, e, gag, byRef);
475 /*****************************************************
476 * Check struct constructor of the form `s.this(args)`, by
477 * checking each `return` parameter to see if it gets
480 * sc = used to determine current function and module
481 * ce = constructor call of the form `s.this(args)`
482 * gag = do not print error messages
484 * `true` if construction would cause an escaping reference error
486 bool checkConstructorEscape(Scope* sc, CallExp ce, bool gag)
489 if (log) printf("checkConstructorEscape(%s, %s)\n", ce.toChars(), ce.type.toChars());
490 Type tthis = ce.type.toBasetype();
491 assert(tthis.ty == Tstruct);
492 if (!tthis.hasPointers())
495 if (!ce.arguments && ce.arguments.dim)
498 DotVarExp dve = ce.e1.isDotVarExp();
499 CtorDeclaration ctor = dve.var.isCtorDeclaration();
500 TypeFunction tf = ctor.type.isTypeFunction();
502 const nparams = tf.parameterList.length;
503 const n = ce.arguments.dim;
505 // j=1 if _arguments[] is first argument
506 const j = tf.isDstyleVariadic();
508 /* Attempt to assign each `return` arg to the `this` reference
510 foreach (const i; 0 .. n)
512 Expression arg = (*ce.arguments)[i];
513 //printf("\targ[%d]: %s\n", i, arg.toChars());
515 if (i - j < nparams && i >= j)
517 Parameter p = tf.parameterList[i - j];
518 if (checkParamArgumentReturn(sc, dve.e1, arg, p, gag))
526 /****************************************
527 * Given an `AssignExp`, determine if the lvalue will cause
528 * the contents of the rvalue to escape.
529 * Print error messages when these are detected.
530 * Infer `scope` attribute for the lvalue where possible, in order
531 * to eliminate the error.
533 * sc = used to determine current function and module
534 * e = `AssignExp` or `CatAssignExp` to check for any pointers to the stack
535 * gag = do not print error messages
536 * byRef = set to `true` if `e1` of `e` gets assigned a reference to `e2`
538 * `true` if pointers to the stack can escape via assignment
540 bool checkAssignEscape(Scope* sc, Expression e, bool gag, bool byRef)
543 if (log) printf("checkAssignEscape(e: %s, byRef: %d)\n", e.toChars(), byRef);
544 if (e.op != EXP.assign && e.op != EXP.blit && e.op != EXP.construct &&
545 e.op != EXP.concatenateAssign && e.op != EXP.concatenateElemAssign && e.op != EXP.concatenateDcharAssign)
547 auto ae = cast(BinExp)e;
548 Expression e1 = ae.e1;
549 Expression e2 = ae.e2;
550 //printf("type = %s, %d\n", e1.type.toChars(), e1.type.hasPointers());
552 if (!e1.type.hasPointers())
558 /* The struct literal case can arise from the S(e2) constructor call:
560 * and appears in this function as:
561 * structLiteral = e2;
562 * Such an assignment does not necessarily remove scope-ness.
564 if (e1.isStructLiteralExp())
570 escapeByRef(e2, &er);
572 escapeByValue(e2, &er);
574 if (!er.byref.dim && !er.byvalue.dim && !er.byfunc.dim && !er.byexp.dim)
577 VarDeclaration va = expToVariable(e1);
579 if (va && e.op == EXP.concatenateElemAssign)
581 /* https://issues.dlang.org/show_bug.cgi?id=17842
582 * Draw an equivalence between:
586 * since we are not assigning to va, but are assigning indirectly through va.
591 if (va && e1.isDotVarExp() && va.type.toBasetype().isTypeClass())
593 /* https://issues.dlang.org/show_bug.cgi?id=17949
594 * Draw an equivalence between:
598 * since we are not assigning to va, but are assigning indirectly through class reference va.
603 if (log && va) printf("va: %s\n", va.toChars());
605 FuncDeclaration fd = sc.func;
608 // Determine if va is a parameter that is an indirect reference
609 const bool vaIsRef = va && va.storage_class & STC.parameter &&
610 (va.isReference() || va.type.toBasetype().isTypeClass()); // ref, out, or class
611 if (log && vaIsRef) printf("va is ref `%s`\n", va.toChars());
613 /* Determine if va is the first parameter, through which other 'return' parameters
615 * This works the same as returning the value via a return statement.
616 * Although va is marked as `ref`, it is not regarded as returning by `ref`.
617 * https://dlang.org.spec/function.html#return-ref-parameters
623 Dsymbol p = va.toParent2();
624 if (p == fd && fd.type && fd.type.isTypeFunction())
626 TypeFunction tf = fd.type.isTypeFunction();
627 if (!tf.nextOf() || (tf.nextOf().ty != Tvoid && !fd.isCtorDeclaration()))
629 if (va == fd.vthis) // `this` of a non-static member function is considered to be the first parameter
631 if (!fd.vthis && fd.parameters && fd.parameters.length && (*fd.parameters)[0] == va) // va is first parameter
636 const bool vaIsFirstRef = isFirstRef();
637 if (log && vaIsFirstRef) printf("va is first ref `%s`\n", va.toChars());
640 foreach (VarDeclaration v; er.byvalue)
642 if (log) printf("byvalue: %s\n", v.toChars());
649 Dsymbol p = v.toParent2();
651 if (va && !vaIsRef && !va.isScope() && !v.isScope() &&
652 (va.storage_class & v.storage_class & (STC.maybescope | STC.variadic)) == STC.maybescope &&
655 /* Add v to va's list of dependencies
662 (v.isScope() || (v.storage_class & STC.maybescope)) &&
663 !(v.storage_class & STC.return_) &&
665 fd.flags & FUNCFLAG.returnInprocess &&
668 if (log) printf("inferring 'return' for parameter %s in function %s\n", v.toChars(), fd.toChars());
669 inferReturn(fd, v, /*returnScope:*/ true); // infer addition of 'return' to make `return scope`
672 if (!(va && va.isScope()) || vaIsRef)
677 if (vaIsFirstRef && v.isParameter() && v.storage_class & STC.return_)
679 // va=v, where v is `return scope`
683 if (!va.doNotInferScope)
685 if (log) printf("inferring scope for lvalue %s\n", va.toChars());
686 va.storage_class |= STC.scope_ | STC.scopeinferred;
691 if (va && va.isScope() && va.storage_class & STC.return_ && !(v.storage_class & STC.return_) &&
694 // va may return its value, but v does not allow that, so this is an error
696 error(ae.loc, "scope variable `%s` assigned to return scope `%s`", v.toChars(), va.toChars());
701 // If va's lifetime encloses v's, then error
702 if (va && !va.isDataseg() &&
703 ((va.enclosesLifetimeOf(v) && !(v.storage_class & STC.temp)) || vaIsRef) &&
707 error(ae.loc, "scope variable `%s` assigned to `%s` with longer lifetime", v.toChars(), va.toChars());
712 if (va && !va.isDataseg() && !va.doNotInferScope)
715 { /* v is scope, and va is not scope, so va needs to
718 if (log) printf("inferring scope for %s\n", va.toChars());
719 va.storage_class |= STC.scope_ | STC.scopeinferred;
720 /* v returns, and va does not return, so va needs
723 if (v.storage_class & STC.return_ &&
724 !(va.storage_class & STC.return_))
726 if (log) printf("infer return for %s\n", va.toChars());
727 va.storage_class |= STC.return_ | STC.returninferred;
729 // Added "return scope" so don't confuse it with "return ref"
730 if (isRefReturnScope(va.storage_class))
731 va.storage_class |= STC.returnScope;
739 error(ae.loc, "scope variable `%s` assigned to non-scope `%s`", v.toChars(), e1.toChars());
743 else if (v.storage_class & STC.variadic && p == fd)
745 Type tb = v.type.toBasetype();
746 if (tb.ty == Tarray || tb.ty == Tsarray)
748 if (va && !va.isDataseg() && !va.doNotInferScope)
751 { //printf("inferring scope for %s\n", va.toChars());
752 va.storage_class |= STC.scope_ | STC.scopeinferred;
759 error(ae.loc, "variadic variable `%s` assigned to non-scope `%s`", v.toChars(), e1.toChars());
766 /* v is not 'scope', and we didn't check the scope of where we assigned it to.
767 * It may escape via that assignment, therefore, v can never be 'scope'.
769 //printf("no infer for %s in %s, %d\n", v.toChars(), fd.ident.toChars(), __LINE__);
770 v.doNotInferScope = true;
774 foreach (VarDeclaration v; er.byref)
776 if (log) printf("byref: %s\n", v.toChars());
780 if (global.params.useDIP1000 != FeatureState.disabled)
782 if (va && va.isScope() && !v.isReference())
784 if (!(va.storage_class & STC.return_))
786 va.doNotInferReturn = true;
788 else if (setUnsafeDIP1000(fd))
791 previewErrorFunc(sc.isDeprecated(), global.params.useDIP1000)
792 (ae.loc, "address of local variable `%s` assigned to return scope `%s`", v.toChars(), va.toChars());
795 if (global.params.useDIP1000 == FeatureState.enabled)
804 Dsymbol p = v.toParent2();
806 if (vaIsFirstRef && v.isParameter() &&
807 !(v.storage_class & STC.return_) &&
808 fd.flags & FUNCFLAG.returnInprocess &&
811 //if (log) printf("inferring 'return' for parameter %s in function %s\n", v.toChars(), fd.toChars());
812 inferReturn(fd, v, /*returnScope:*/ false);
815 // If va's lifetime encloses v's, then error
817 !(vaIsFirstRef && (v.storage_class & STC.return_)) &&
818 (va.enclosesLifetimeOf(v) || (va.isReference() && !(va.storage_class & STC.temp)) || va.isDataseg()) &&
822 error(ae.loc, "address of variable `%s` assigned to `%s` with longer lifetime", v.toChars(), va.toChars());
827 if (!(va && va.isScope()))
830 if ((global.params.useDIP1000 != FeatureState.enabled && v.isReference()) || p != sc.func)
833 if (va && !va.isDataseg() && !va.doNotInferScope)
836 { //printf("inferring scope for %s\n", va.toChars());
837 va.storage_class |= STC.scope_ | STC.scopeinferred;
839 if (v.storage_class & STC.return_ && !(va.storage_class & STC.return_))
840 va.storage_class |= STC.return_ | STC.returninferred;
843 if (e1.op == EXP.structLiteral)
848 error(ae.loc, "reference to local variable `%s` assigned to non-scope `%s`", v.toChars(), e1.toChars());
853 foreach (FuncDeclaration func; er.byfunc)
855 if (log) printf("byfunc: %s, %d\n", func.toChars(), func.tookAddressOf);
856 VarDeclarations vars;
857 findAllOuterAccessedVariables(func, &vars);
859 /* https://issues.dlang.org/show_bug.cgi?id=16037
860 * If assigning the address of a delegate to a scope variable,
861 * then uncount that address of. This is so it won't cause a
862 * closure to be allocated.
864 if (va && va.isScope() && !(va.storage_class & STC.return_) && func.tookAddressOf)
865 --func.tookAddressOf;
869 //printf("v = %s\n", v.toChars());
870 assert(!v.isDataseg()); // these are not put in the closureVars[]
872 Dsymbol p = v.toParent2();
874 if (!(va && va.isScope()))
877 if (!(v.isReference() || v.isScope()) || p != fd)
880 if (va && !va.isDataseg() && !va.doNotInferScope)
882 /* Don't infer STC.scope_ for va, because then a closure
883 * won't be generated for fd.
886 //va.storage_class |= STC.scope_ | STC.scopeinferred;
892 error(ae.loc, "reference to local `%s` assigned to non-scope `%s` in @safe code", v.toChars(), e1.toChars());
898 foreach (Expression ee; er.byexp)
900 if (log) printf("byexp: %s\n", ee.toChars());
902 /* Do not allow slicing of a static array returned by a function
904 if (ee.op == EXP.call && ee.type.toBasetype().isTypeSArray() && e1.type.toBasetype().isTypeDArray() &&
905 !(va && va.storage_class & STC.temp))
908 deprecation(ee.loc, "slice of static array temporary returned by `%s` assigned to longer lived variable `%s`",
909 ee.toChars(), e1.toChars());
914 if (ee.op == EXP.call && ee.type.toBasetype().isTypeStruct() &&
915 (!va || !(va.storage_class & STC.temp)) &&
919 error(ee.loc, "address of struct temporary returned by `%s` assigned to longer lived variable `%s`",
920 ee.toChars(), e1.toChars());
925 if (ee.op == EXP.structLiteral &&
926 (!va || !(va.storage_class & STC.temp)) &&
930 error(ee.loc, "address of struct literal `%s` assigned to longer lived variable `%s`",
931 ee.toChars(), e1.toChars());
936 if (va && !va.isDataseg() && !va.doNotInferScope)
939 { //printf("inferring scope for %s\n", va.toChars());
940 va.storage_class |= STC.scope_ | STC.scopeinferred;
948 error(ee.loc, "reference to stack allocated value returned by `%s` assigned to non-scope `%s`",
949 ee.toChars(), e1.toChars());
957 /************************************
958 * Detect cases where pointers to the stack can escape the
959 * lifetime of the stack frame when throwing `e`.
960 * Print error messages when these are detected.
962 * sc = used to determine current function and module
963 * e = expression to check for any pointers to the stack
964 * gag = do not print error messages
966 * `true` if pointers to the stack can escape
968 bool checkThrowEscape(Scope* sc, Expression e, bool gag)
970 //printf("[%s] checkThrowEscape, e = %s\n", e.loc.toChars(), e.toChars());
973 escapeByValue(e, &er);
975 if (!er.byref.dim && !er.byvalue.dim && !er.byexp.dim)
979 foreach (VarDeclaration v; er.byvalue)
981 //printf("byvalue %s\n", v.toChars());
985 if (v.isScope() && !v.iscatchvar) // special case: allow catch var to be rethrown
986 // despite being `scope`
989 previewErrorFunc(sc.isDeprecated(), global.params.useDIP1000)
990 (e.loc, "scope variable `%s` may not be thrown", v.toChars());
991 if (global.params.useDIP1000 == FeatureState.enabled) // https://issues.dlang.org/show_bug.cgi?id=17029
997 //printf("no infer for %s in %s, %d\n", v.toChars(), sc.func.ident.toChars(), __LINE__);
998 v.doNotInferScope = true;
1004 /************************************
1005 * Detect cases where pointers to the stack can escape the
1006 * lifetime of the stack frame by being placed into a GC allocated object.
1007 * Print error messages when these are detected.
1009 * sc = used to determine current function and module
1010 * e = expression to check for any pointers to the stack
1011 * gag = do not print error messages
1013 * `true` if pointers to the stack can escape
1015 bool checkNewEscape(Scope* sc, Expression e, bool gag)
1017 import dmd.globals: FeatureState;
1018 import dmd.errors: previewErrorFunc;
1020 //printf("[%s] checkNewEscape, e = %s\n", e.loc.toChars(), e.toChars());
1022 if (log) printf("[%s] checkNewEscape, e: `%s`\n", e.loc.toChars(), e.toChars());
1025 escapeByValue(e, &er);
1027 if (!er.byref.dim && !er.byvalue.dim && !er.byexp.dim)
1030 bool result = false;
1031 foreach (VarDeclaration v; er.byvalue)
1033 if (log) printf("byvalue `%s`\n", v.toChars());
1037 Dsymbol p = v.toParent2();
1042 /* This case comes up when the ReturnStatement of a __foreachbody is
1043 * checked for escapes by the caller of __foreachbody. Skip it.
1045 * struct S { static int opApply(int delegate(S*) dg); }
1047 * foreach (S* s; S) // create __foreachbody for body of foreach
1048 * return s; // s is inferred as 'scope' but incorrectly tested in foo()
1051 !(p.parent == sc.func))
1053 if (setUnsafeDIP1000(sc.func)) // https://issues.dlang.org/show_bug.cgi?id=20868
1055 // Only look for errors if in module listed on command line
1057 previewErrorFunc(sc.isDeprecated(), global.params.useDIP1000)
1058 (e.loc, "scope variable `%s` may not be copied into allocated memory", v.toChars());
1059 if (global.params.useDIP1000 == FeatureState.enabled)
1066 else if (v.storage_class & STC.variadic && p == sc.func)
1068 Type tb = v.type.toBasetype();
1069 if (tb.ty == Tarray || tb.ty == Tsarray)
1072 error(e.loc, "copying `%s` into allocated memory escapes a reference to variadic parameter `%s`", e.toChars(), v.toChars());
1078 //printf("no infer for %s in %s, %d\n", v.toChars(), sc.func.ident.toChars(), __LINE__);
1079 v.doNotInferScope = true;
1083 foreach (VarDeclaration v; er.byref)
1085 if (log) printf("byref `%s`\n", v.toChars());
1087 // 'featureState' tells us whether to emit an error or a deprecation,
1088 // depending on the flag passed to the CLI for DIP25
1089 void escapingRef(VarDeclaration v, FeatureState featureState = FeatureState.enabled)
1093 const(char)* kind = (v.storage_class & STC.parameter) ? "parameter" : "local";
1094 const(char)* msg = "copying `%s` into allocated memory escapes a reference to %s variable `%s`";
1095 previewErrorFunc(sc.isDeprecated(), featureState)(e.loc, msg, e.toChars(), kind, v.toChars());
1097 result |= (featureState == FeatureState.enabled);
1103 Dsymbol p = v.toParent2();
1105 if (!v.isReference())
1114 /* Check for returning a ref variable by 'ref', but should be 'return ref'
1115 * Infer the addition of 'return', or set result to be the offending expression.
1117 if (!v.isReference())
1120 // https://dlang.org/spec/function.html#return-ref-parameters
1123 //printf("escaping reference to local ref variable %s\n", v.toChars());
1124 //printf("storage class = x%llx\n", v.storage_class);
1125 escapingRef(v, global.params.useDIP25);
1128 // Don't need to be concerned if v's parent does not return a ref
1129 FuncDeclaration func = p.isFuncDeclaration();
1130 if (!func || !func.type)
1132 if (auto tf = func.type.isTypeFunction())
1137 const(char)* msg = "storing reference to outer local variable `%s` into allocated memory causes it to escape";
1140 previewErrorFunc(sc.isDeprecated(), global.params.useDIP25)(e.loc, msg, v.toChars());
1143 // If -preview=dip25 is used, the user wants an error
1144 // Otherwise, issue a deprecation
1145 result |= (global.params.useDIP25 == FeatureState.enabled);
1149 foreach (Expression ee; er.byexp)
1151 if (log) printf("byexp %s\n", ee.toChars());
1153 error(ee.loc, "storing reference to stack allocated value returned by `%s` into allocated memory causes it to escape",
1162 /************************************
1163 * Detect cases where pointers to the stack can escape the
1164 * lifetime of the stack frame by returning `e` by value.
1165 * Print error messages when these are detected.
1167 * sc = used to determine current function and module
1168 * e = expression to check for any pointers to the stack
1169 * gag = do not print error messages
1171 * `true` if pointers to the stack can escape
1173 bool checkReturnEscape(Scope* sc, Expression e, bool gag)
1175 //printf("[%s] checkReturnEscape, e: %s\n", e.loc.toChars(), e.toChars());
1176 return checkReturnEscapeImpl(sc, e, false, gag);
1179 /************************************
1180 * Detect cases where returning `e` by `ref` can result in a reference to the stack
1182 * Print error messages when these are detected.
1184 * sc = used to determine current function and module
1185 * e = expression to check
1186 * gag = do not print error messages
1188 * `true` if references to the stack can escape
1190 bool checkReturnEscapeRef(Scope* sc, Expression e, bool gag)
1194 printf("[%s] checkReturnEscapeRef, e = %s\n", e.loc.toChars(), e.toChars());
1195 printf("current function %s\n", sc.func.toChars());
1196 printf("parent2 function %s\n", sc.func.toParent2().toChars());
1199 return checkReturnEscapeImpl(sc, e, true, gag);
1202 /***************************************
1203 * Implementation of checking for escapes in return expressions.
1205 * sc = used to determine current function and module
1206 * e = expression to check
1207 * refs = `true`: escape by value, `false`: escape by `ref`
1208 * gag = do not print error messages
1210 * `true` if references to the stack can escape
1212 private bool checkReturnEscapeImpl(Scope* sc, Expression e, bool refs, bool gag)
1215 if (log) printf("[%s] checkReturnEscapeImpl, refs: %d e: `%s`\n", e.loc.toChars(), refs, e.toChars());
1219 escapeByRef(e, &er);
1221 escapeByValue(e, &er);
1223 if (!er.byref.dim && !er.byvalue.dim && !er.byexp.dim)
1226 bool result = false;
1227 foreach (VarDeclaration v; er.byvalue)
1229 if (log) printf("byvalue `%s`\n", v.toChars());
1233 Dsymbol p = v.toParent2();
1235 if ((v.isScope() || (v.storage_class & STC.maybescope)) &&
1236 !(v.storage_class & STC.return_) &&
1238 !v.doNotInferReturn &&
1239 sc.func.flags & FUNCFLAG.returnInprocess &&
1242 inferReturn(sc.func, v, /*returnScope:*/ true); // infer addition of 'return'
1248 if (v.storage_class & STC.return_)
1251 auto pfunc = p.isFuncDeclaration();
1253 /* This case comes up when the ReturnStatement of a __foreachbody is
1254 * checked for escapes by the caller of __foreachbody. Skip it.
1256 * struct S { static int opApply(int delegate(S*) dg); }
1258 * foreach (S* s; S) // create __foreachbody for body of foreach
1259 * return s; // s is inferred as 'scope' but incorrectly tested in foo()
1262 !(!refs && p.parent == sc.func && pfunc.fes) &&
1264 * auto p(scope string s) {
1265 * string scfunc() { return s; }
1268 !(!refs && sc.func.isFuncDeclaration().getLevel(pfunc, sc.intypeof) > 0)
1271 // https://issues.dlang.org/show_bug.cgi?id=17029
1272 if (setUnsafeDIP1000(sc.func))
1275 previewErrorFunc(sc.isDeprecated(), global.params.useDIP1000)
1276 (e.loc, "scope variable `%s` may not be returned", v.toChars());
1277 if (global.params.useDIP1000 == FeatureState.enabled)
1283 else if (v.storage_class & STC.variadic && p == sc.func)
1285 Type tb = v.type.toBasetype();
1286 if (tb.ty == Tarray || tb.ty == Tsarray)
1289 error(e.loc, "returning `%s` escapes a reference to variadic parameter `%s`", e.toChars(), v.toChars());
1295 //printf("no infer for %s in %s, %d\n", v.toChars(), sc.func.ident.toChars(), __LINE__);
1296 v.doNotInferScope = true;
1300 foreach (VarDeclaration v; er.byref)
1304 printf("byref `%s` %s\n", v.toChars(), toChars(buildScopeRef(v.storage_class)));
1307 // 'featureState' tells us whether to emit an error or a deprecation,
1308 // depending on the flag passed to the CLI for DIP25
1309 void escapingRef(VarDeclaration v, ScopeRef vsr, FeatureState featureState = FeatureState.enabled)
1313 const(char)* varKind = v.isParameter() ? "parameter" : "local variable";
1314 previewErrorFunc(sc.isDeprecated(), featureState)(e.loc,
1315 "returning `%s` escapes a reference to %s `%s`", e.toChars(), varKind, v.toChars());
1317 if (v.isParameter() && v.isReference())
1319 if (v.storage_class & STC.returnScope)
1321 previewSupplementalFunc(sc.isDeprecated(), featureState)(v.loc,
1322 "perhaps change the `return scope` into `scope return`");
1326 const(char)* annotateKind = (v.ident is Id.This) ? "function" : "parameter";
1327 previewSupplementalFunc(sc.isDeprecated(), featureState)(v.loc,
1328 "perhaps annotate the %s with `return`", annotateKind);
1338 const vsr = buildScopeRef(v.storage_class);
1340 Dsymbol p = v.toParent2();
1342 // https://issues.dlang.org/show_bug.cgi?id=19965
1343 if (!refs && sc.func.vthis == v)
1346 if (!v.isReference())
1350 escapingRef(v, vsr, FeatureState.enabled);
1353 FuncDeclaration fd = p.isFuncDeclaration();
1354 if (fd && sc.func.flags & FUNCFLAG.returnInprocess)
1358 * auto dg = () { return &x; }
1360 * auto dg = () return { return &x; }
1361 * Because dg.ptr points to x, this is returning dt.ptr+offset
1363 if (global.params.useDIP1000 == FeatureState.enabled)
1365 sc.func.storage_class |= STC.return_ | STC.returninferred;
1370 /* Check for returning a ref variable by 'ref', but should be 'return ref'
1371 * Infer the addition of 'return', or set result to be the offending expression.
1373 if ((vsr == ScopeRef.Ref ||
1374 vsr == ScopeRef.RefScope ||
1375 vsr == ScopeRef.Ref_ReturnScope) &&
1376 !(v.storage_class & STC.foreach_))
1378 if (sc.func.flags & FUNCFLAG.returnInprocess && p == sc.func &&
1379 (vsr == ScopeRef.Ref || vsr == ScopeRef.RefScope))
1381 inferReturn(sc.func, v, /*returnScope:*/ false); // infer addition of 'return'
1385 // https://dlang.org/spec/function.html#return-ref-parameters
1386 // Only look for errors if in module listed on command line
1389 //printf("escaping reference to local ref variable %s\n", v.toChars());
1390 //printf("storage class = x%llx\n", v.storage_class);
1391 escapingRef(v, vsr, global.params.useDIP25);
1394 // Don't need to be concerned if v's parent does not return a ref
1395 FuncDeclaration fd = p.isFuncDeclaration();
1396 if (fd && fd.type && fd.type.ty == Tfunction)
1398 TypeFunction tf = fd.type.isTypeFunction();
1401 const(char)* msg = "escaping reference to outer local variable `%s`";
1403 previewErrorFunc(sc.isDeprecated(), global.params.useDIP25)(e.loc, msg, v.toChars());
1413 foreach (Expression ee; er.byexp)
1415 if (log) printf("byexp %s\n", ee.toChars());
1417 error(ee.loc, "escaping reference to stack allocated value returned by `%s`", ee.toChars());
1425 /*************************************
1426 * Variable v needs to have 'return' inferred for it.
1428 * fd = function that v is a parameter to
1429 * v = parameter that needs to be STC.return_
1430 * returnScope = infer `return scope` instead of `return ref`
1432 private void inferReturn(FuncDeclaration fd, VarDeclaration v, bool returnScope)
1434 // v is a local in the current function
1436 //printf("for function '%s' inferring 'return' for variable '%s', returnScope: %d\n", fd.toChars(), v.toChars(), returnScope);
1437 auto newStcs = STC.return_ | STC.returninferred | (returnScope ? STC.returnScope : 0);
1438 v.storage_class |= newStcs;
1442 /* v is the 'this' reference, so mark the function
1444 fd.storage_class |= newStcs;
1445 if (auto tf = fd.type.isTypeFunction())
1447 //printf("'this' too %p %s\n", tf, sc.func.toChars());
1448 tf.isreturnscope = returnScope;
1450 tf.isreturninferred = true;
1455 // Perform 'return' inference on parameter
1456 if (auto tf = fd.type.isTypeFunction())
1458 foreach (i, p; tf.parameterList)
1460 if (p.ident == v.ident)
1462 p.storageClass |= newStcs;
1463 break; // there can be only one
1471 /****************************************
1472 * e is an expression to be returned by value, and that value contains pointers.
1473 * Walk e to determine which variables are possibly being
1474 * returned by value, such as:
1475 * int* function(int* p) { return p; }
1476 * If e is a form of &p, determine which variables have content
1477 * which is being returned as ref, such as:
1478 * int* function(int i) { return &i; }
1479 * Multiple variables can be inserted, because of expressions like this:
1480 * int function(bool b, int i, int* p) { return b ? &i : p; }
1485 * e = expression to be returned by value
1486 * er = where to place collected data
1487 * live = if @live semantics apply, i.e. expressions `p`, `*p`, `**p`, etc., all return `p`.
1489 void escapeByValue(Expression e, EscapeByResults* er, bool live = false)
1491 //printf("[%s] escapeByValue, e: %s\n", e.loc.toChars(), e.toChars());
1492 extern (C++) final class EscapeVisitor : Visitor
1494 alias visit = Visitor.visit;
1496 EscapeByResults* er;
1499 extern (D) this(EscapeByResults* er, bool live)
1505 override void visit(Expression e)
1509 override void visit(AddrExp e)
1511 /* Taking the address of struct literal is normally not
1512 * allowed, but CTFE can generate one out of a new expression,
1513 * but it'll be placed in static data so no need to check it.
1515 if (e.e1.op != EXP.structLiteral)
1516 escapeByRef(e.e1, er, live);
1519 override void visit(SymOffExp e)
1521 VarDeclaration v = e.var.isVarDeclaration();
1526 override void visit(VarExp e)
1528 if (auto v = e.var.isVarDeclaration())
1530 if (v.type.hasPointers() || // not tracking non-pointers
1531 v.storage_class & STC.lazy_) // lazy variables are actually pointers
1536 override void visit(ThisExp e)
1539 er.byvalue.push(e.var);
1542 override void visit(PtrExp e)
1544 if (live && e.type.hasPointers())
1548 override void visit(DotVarExp e)
1550 auto t = e.e1.type.toBasetype();
1551 if (e.type.hasPointers() && (live || t.ty == Tstruct))
1557 override void visit(DelegateExp e)
1559 Type t = e.e1.type.toBasetype();
1560 if (t.ty == Tclass || t.ty == Tpointer)
1561 escapeByValue(e.e1, er, live);
1563 escapeByRef(e.e1, er, live);
1564 er.byfunc.push(e.func);
1567 override void visit(FuncExp e)
1569 if (e.fd.tok == TOK.delegate_)
1570 er.byfunc.push(e.fd);
1573 override void visit(TupleExp e)
1575 assert(0); // should have been lowered by now
1578 override void visit(ArrayLiteralExp e)
1580 Type tb = e.type.toBasetype();
1581 if (tb.ty == Tsarray || tb.ty == Tarray)
1584 e.basis.accept(this);
1585 foreach (el; *e.elements)
1593 override void visit(StructLiteralExp e)
1597 foreach (ex; *e.elements)
1605 override void visit(NewExp e)
1607 Type tb = e.newtype.toBasetype();
1608 if (tb.ty == Tstruct && !e.member && e.arguments)
1610 foreach (ex; *e.arguments)
1618 override void visit(CastExp e)
1620 if (!e.type.hasPointers())
1622 Type tb = e.type.toBasetype();
1623 if (tb.ty == Tarray && e.e1.type.toBasetype().ty == Tsarray)
1625 escapeByRef(e.e1, er, live);
1631 override void visit(SliceExp e)
1633 if (auto ve = e.e1.isVarExp())
1635 VarDeclaration v = ve.var.isVarDeclaration();
1636 Type tb = e.type.toBasetype();
1639 if (tb.ty == Tsarray)
1641 if (v.storage_class & STC.variadic)
1648 Type t1b = e.e1.type.toBasetype();
1649 if (t1b.ty == Tsarray)
1651 Type tb = e.type.toBasetype();
1652 if (tb.ty != Tsarray)
1653 escapeByRef(e.e1, er, live);
1659 override void visit(IndexExp e)
1661 if (e.e1.type.toBasetype().ty == Tsarray ||
1662 live && e.type.hasPointers())
1668 override void visit(BinExp e)
1670 Type tb = e.type.toBasetype();
1671 if (tb.ty == Tpointer)
1678 override void visit(BinAssignExp e)
1683 override void visit(AssignExp e)
1688 override void visit(CommaExp e)
1693 override void visit(CondExp e)
1699 override void visit(CallExp e)
1701 //printf("CallExp(): %s\n", e.toChars());
1702 /* Check each argument that is
1703 * passed as 'return scope'.
1705 Type t1 = e.e1.type.toBasetype();
1708 if (t1.ty == Tdelegate)
1710 dg = t1.isTypeDelegate();
1711 tf = dg.next.isTypeFunction();
1713 else if (t1.ty == Tfunction)
1714 tf = t1.isTypeFunction();
1718 if (!e.type.hasPointers())
1721 if (e.arguments && e.arguments.dim)
1723 /* j=1 if _arguments[] is first argument,
1724 * skip it because it is not passed by ref
1726 int j = tf.isDstyleVariadic();
1727 for (size_t i = j; i < e.arguments.dim; ++i)
1729 Expression arg = (*e.arguments)[i];
1730 size_t nparams = tf.parameterList.length;
1731 if (i - j < nparams && i >= j)
1733 Parameter p = tf.parameterList[i - j];
1734 const stc = tf.parameterStorageClass(null, p);
1735 ScopeRef psr = buildScopeRef(stc);
1736 if (psr == ScopeRef.ReturnScope || psr == ScopeRef.Ref_ReturnScope)
1738 else if (psr == ScopeRef.ReturnRef || psr == ScopeRef.ReturnRef_Scope)
1743 * ref P foo(return ref P p)
1750 escapeByRef(arg, er, live);
1755 // If 'this' is returned, check it too
1756 if (e.e1.op == EXP.dotVariable && t1.ty == Tfunction)
1758 DotVarExp dve = e.e1.isDotVarExp();
1759 FuncDeclaration fd = dve.var.isFuncDeclaration();
1760 if (global.params.useDIP1000 == FeatureState.enabled)
1762 if (fd && fd.isThis())
1764 /* Calling a non-static member function dve.var, which is returning `this`, and with dve.e1 representing `this`
1767 /*****************************
1768 * Concoct storage class for member function's implicit `this` parameter.
1770 * fd = member function
1772 * storage class for fd's `this`
1774 StorageClass getThisStorageClass(FuncDeclaration fd)
1777 auto tf = fd.type.toBasetype().isTypeFunction();
1780 if (tf.isreturnscope)
1781 stc |= STC.returnScope;
1782 auto ad = fd.isThis();
1783 if (ad.isClassDeclaration() || tf.isScopeQual)
1785 if (ad.isStructDeclaration())
1786 stc |= STC.ref_; // `this` for a struct member function is passed by `ref`
1790 const psr = buildScopeRef(getThisStorageClass(fd));
1791 if (psr == ScopeRef.ReturnScope || psr == ScopeRef.Ref_ReturnScope)
1792 dve.e1.accept(this);
1793 else if (psr == ScopeRef.ReturnRef || psr == ScopeRef.ReturnRef_Scope)
1798 * struct S { ref S foo() return; }
1802 dve.e1.accept(this);
1805 escapeByRef(dve.e1, er, live);
1811 // Calling member function before dip1000
1812 StorageClass stc = dve.var.storage_class & (STC.return_ | STC.scope_ | STC.ref_);
1816 const psr = buildScopeRef(stc);
1817 if (psr == ScopeRef.ReturnScope || psr == ScopeRef.Ref_ReturnScope)
1818 dve.e1.accept(this);
1819 else if (psr == ScopeRef.ReturnRef || psr == ScopeRef.ReturnRef_Scope)
1820 escapeByRef(dve.e1, er, live);
1823 // If it's also a nested function that is 'return scope'
1824 if (fd && fd.isNested())
1826 if (tf.isreturn && tf.isScopeQual)
1831 /* If returning the result of a delegate call, the .ptr
1832 * field of the delegate must be checked.
1840 /* If it's a nested function that is 'return scope'
1842 if (auto ve = e.e1.isVarExp())
1844 FuncDeclaration fd = ve.var.isFuncDeclaration();
1845 if (fd && fd.isNested())
1847 if (tf.isreturn && tf.isScopeQual)
1854 scope EscapeVisitor v = new EscapeVisitor(er, live);
1859 /****************************************
1860 * e is an expression to be returned by 'ref'.
1861 * Walk e to determine which variables are possibly being
1862 * returned by ref, such as:
1863 * ref int function(int i) { return i; }
1864 * If e is a form of *p, determine which variables have content
1865 * which is being returned as ref, such as:
1866 * ref int function(int* p) { return *p; }
1867 * Multiple variables can be inserted, because of expressions like this:
1868 * ref int function(bool b, int i, int* p) { return b ? i : *p; }
1873 * e = expression to be returned by 'ref'
1874 * er = where to place collected data
1875 * live = if @live semantics apply, i.e. expressions `p`, `*p`, `**p`, etc., all return `p`.
1877 void escapeByRef(Expression e, EscapeByResults* er, bool live = false)
1879 //printf("[%s] escapeByRef, e: %s\n", e.loc.toChars(), e.toChars());
1880 extern (C++) final class EscapeRefVisitor : Visitor
1882 alias visit = Visitor.visit;
1884 EscapeByResults* er;
1887 extern (D) this(EscapeByResults* er, bool live)
1893 override void visit(Expression e)
1897 override void visit(VarExp e)
1899 auto v = e.var.isVarDeclaration();
1902 if (v.storage_class & STC.ref_ && v.storage_class & (STC.foreach_ | STC.temp) && v._init)
1904 /* If compiler generated ref temporary
1906 * look at the initializer instead
1908 if (ExpInitializer ez = v._init.isExpInitializer())
1910 if (auto ce = ez.exp.isConstructExp())
1913 ez.exp.accept(this);
1921 override void visit(ThisExp e)
1923 if (e.var && e.var.toParent2().isFuncDeclaration().hasDualContext())
1924 escapeByValue(e, er, live);
1926 er.byref.push(e.var);
1929 override void visit(PtrExp e)
1931 escapeByValue(e.e1, er, live);
1934 override void visit(IndexExp e)
1936 Type tb = e.e1.type.toBasetype();
1937 if (auto ve = e.e1.isVarExp())
1939 VarDeclaration v = ve.var.isVarDeclaration();
1940 if (tb.ty == Tarray || tb.ty == Tsarray)
1942 if (v && v.storage_class & STC.variadic)
1949 if (tb.ty == Tsarray)
1953 else if (tb.ty == Tarray)
1955 escapeByValue(e.e1, er, live);
1959 override void visit(StructLiteralExp e)
1963 foreach (ex; *e.elements)
1972 override void visit(DotVarExp e)
1974 Type t1b = e.e1.type.toBasetype();
1975 if (t1b.ty == Tclass)
1976 escapeByValue(e.e1, er, live);
1981 override void visit(BinAssignExp e)
1986 override void visit(AssignExp e)
1991 override void visit(CommaExp e)
1996 override void visit(CondExp e)
2002 override void visit(CallExp e)
2004 //printf("escapeByRef.CallExp(): %s\n", e.toChars());
2005 /* If the function returns by ref, check each argument that is
2006 * passed as 'return ref'.
2008 Type t1 = e.e1.type.toBasetype();
2010 if (t1.ty == Tdelegate)
2011 tf = t1.isTypeDelegate().next.isTypeFunction();
2012 else if (t1.ty == Tfunction)
2013 tf = t1.isTypeFunction();
2018 if (e.arguments && e.arguments.dim)
2020 /* j=1 if _arguments[] is first argument,
2021 * skip it because it is not passed by ref
2023 int j = tf.isDstyleVariadic();
2024 for (size_t i = j; i < e.arguments.dim; ++i)
2026 Expression arg = (*e.arguments)[i];
2027 size_t nparams = tf.parameterList.length;
2028 if (i - j < nparams && i >= j)
2030 Parameter p = tf.parameterList[i - j];
2031 const stc = tf.parameterStorageClass(null, p);
2032 ScopeRef psr = buildScopeRef(stc);
2033 if (psr == ScopeRef.ReturnRef || psr == ScopeRef.ReturnRef_Scope)
2035 else if (psr == ScopeRef.ReturnScope || psr == ScopeRef.Ref_ReturnScope)
2037 if (auto de = arg.isDelegateExp())
2039 if (de.func.isNested())
2043 escapeByValue(arg, er, live);
2048 // If 'this' is returned by ref, check it too
2049 if (e.e1.op == EXP.dotVariable && t1.ty == Tfunction)
2051 DotVarExp dve = e.e1.isDotVarExp();
2053 // https://issues.dlang.org/show_bug.cgi?id=20149#c10
2054 if (dve.var.isCtorDeclaration())
2060 StorageClass stc = dve.var.storage_class & (STC.return_ | STC.scope_ | STC.ref_);
2067 if (tf.isreturnscope)
2068 stc |= STC.returnScope;
2070 const psr = buildScopeRef(stc);
2071 if (psr == ScopeRef.ReturnRef || psr == ScopeRef.ReturnRef_Scope)
2072 dve.e1.accept(this);
2073 else if (psr == ScopeRef.ReturnScope || psr == ScopeRef.Ref_ReturnScope)
2074 escapeByValue(dve.e1, er, live);
2076 // If it's also a nested function that is 'return ref'
2077 if (FuncDeclaration fd = dve.var.isFuncDeclaration())
2079 if (fd.isNested() && tf.isreturn)
2085 // If it's a delegate, check it too
2086 if (e.e1.op == EXP.variable && t1.ty == Tdelegate)
2088 escapeByValue(e.e1, er, live);
2091 /* If it's a nested function that is 'return ref'
2093 if (auto ve = e.e1.isVarExp())
2095 FuncDeclaration fd = ve.var.isFuncDeclaration();
2096 if (fd && fd.isNested())
2108 scope EscapeRefVisitor v = new EscapeRefVisitor(er, live);
2113 /************************************
2114 * Aggregate the data collected by the escapeBy??() functions.
2116 struct EscapeByResults
2118 VarDeclarations byref; // array into which variables being returned by ref are inserted
2119 VarDeclarations byvalue; // array into which variables with values containing pointers are inserted
2120 FuncDeclarations byfunc; // nested functions that are turned into delegates
2121 Expressions byexp; // array into which temporaries being returned by ref are inserted
2123 /** Reset arrays so the storage can be used again
2134 /*************************
2135 * Find all variables accessed by this delegate that are
2136 * in functions enclosing it.
2139 * vars = array to append found variables to
2141 public void findAllOuterAccessedVariables(FuncDeclaration fd, VarDeclarations* vars)
2143 //printf("findAllOuterAccessedVariables(fd: %s)\n", fd.toChars());
2144 for (auto p = fd.parent; p; p = p.parent)
2146 auto fdp = p.isFuncDeclaration();
2150 foreach (v; fdp.closureVars)
2152 foreach (const fdv; v.nestedrefs)
2156 //printf("accessed: %s, type %s\n", v.toChars(), v.type.toChars());
2164 /***********************************
2165 * Turn off `STC.maybescope` for variable `v`.
2167 * This exists in order to find where `STC.maybescope` is getting turned off.
2173 public void notMaybeScope(string file = __FILE__, int line = __LINE__)(VarDeclaration v)
2175 printf("%.*s(%d): notMaybeScope('%s')\n", cast(int)file.length, file.ptr, line, v.toChars());
2176 v.storage_class &= ~STC.maybescope;
2181 public void notMaybeScope(VarDeclaration v)
2183 v.storage_class &= ~STC.maybescope;
2188 /**********************************************
2189 * Have some variables that are maybescopes that were
2190 * assigned values from other maybescope variables.
2191 * Now that semantic analysis of the function is
2192 * complete, we can finalize this by turning off
2193 * maybescope for array elements that cannot be scope.
2195 * $(TABLE2 Scope Table,
2196 * $(THEAD `va`, `v`, =>, `va` , `v` )
2197 * $(TROW maybe, maybe, =>, scope, scope)
2198 * $(TROW scope, scope, =>, scope, scope)
2199 * $(TROW scope, maybe, =>, scope, scope)
2200 * $(TROW maybe, scope, =>, scope, scope)
2201 * $(TROW - , - , =>, - , - )
2202 * $(TROW - , maybe, =>, - , - )
2203 * $(TROW - , scope, =>, error, error)
2204 * $(TROW maybe, - , =>, scope, - )
2205 * $(TROW scope, - , =>, scope, - )
2208 * array = array of variables that were assigned to from maybescope variables
2210 public void eliminateMaybeScopes(VarDeclaration[] array)
2213 if (log) printf("eliminateMaybeScopes()\n");
2220 if (log) printf(" va = %s\n", va.toChars());
2221 if (!(va.storage_class & (STC.maybescope | STC.scope_)))
2225 foreach (v; *va.maybes)
2227 if (log) printf(" v = %s\n", v.toChars());
2228 if (v.storage_class & STC.maybescope)
2230 // v cannot be scope since it is assigned to a non-scope va
2232 if (!v.isReference())
2233 v.storage_class &= ~(STC.return_ | STC.returninferred);
2243 /************************************************
2244 * Is type a reference to a mutable value?
2246 * This is used to determine if an argument that does not have a corresponding
2247 * Parameter, i.e. a variadic argument, is a pointer to mutable data.
2249 * t = type of the argument
2251 * true if it's a pointer (or reference) to mutable data
2253 bool isReferenceToMutable(Type t)
2257 if (!t.isMutable() ||
2264 if (t.nextOf().isTypeFunction())
2271 if (t.nextOf().isMutable())
2276 return true; // even if the class fields are not mutable
2279 // Have to look at each field
2280 foreach (VarDeclaration v; t.isTypeStruct().sym.fields)
2282 if (v.storage_class & STC.ref_)
2284 if (v.type.isMutable())
2287 else if (v.type.isReferenceToMutable())
2298 /****************************************
2299 * Is parameter a reference to a mutable value?
2301 * This is used if an argument has a corresponding Parameter.
2302 * The argument type is necessary if the Parameter is inout.
2304 * p = Parameter to check
2305 * t = type of corresponding argument
2307 * true if it's a pointer (or reference) to mutable data
2309 bool isReferenceToMutable(Parameter p, Type t)
2311 if (p.isReference())
2313 if (p.type.isConst() || p.type.isImmutable())
2315 if (p.type.isWild())
2317 return t.isMutable();
2319 return p.type.isMutable();
2321 return isReferenceToMutable(p.type);
2324 /**********************************
2325 * Determine if `va` has a lifetime that lasts past
2326 * the destruction of `v`
2328 * va = variable assigned to
2329 * v = variable being assigned
2333 private bool enclosesLifetimeOf(const VarDeclaration va, const VarDeclaration v) pure
2335 assert(va.sequenceNumber != va.sequenceNumber.init);
2336 assert(v.sequenceNumber != v.sequenceNumber.init);
2337 return va.sequenceNumber < v.sequenceNumber;
2340 /***************************************
2341 * Add variable `v` to maybes[]
2343 * When a maybescope variable `v` is assigned to a maybescope variable `va`,
2344 * we cannot determine if `this` is actually scope until the semantic
2345 * analysis for the function is completed. Thus, we save the data
2348 * v = an `STC.maybescope` variable that was assigned to `this`
2350 private void addMaybe(VarDeclaration va, VarDeclaration v)
2352 //printf("add %s to %s's list of dependencies\n", v.toChars(), toChars());
2354 va.maybes = new VarDeclarations();
2359 private bool setUnsafeDIP1000(FuncDeclaration f)
2361 return global.params.useDIP1000 == FeatureState.enabled
2363 : false; // reverted for 2.100, retry in 2.101