2 * Most of the logic to implement scoped pointers and scoped references is here.
4 * Copyright: Copyright (C) 1999-2021 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 http://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 (global.params.useDIP1000 == FeatureState.enabled && sc.func.setUnsafe())
325 error(arg.loc, "%s `%s` assigned to non-scope parameter calling `assert()`",
330 error(arg.loc, "%s `%s` assigned to non-scope parameter `%s` calling %s",
332 par ? par.toChars() : "this",
333 fdc ? fdc.toPrettyChars() : "indirectly");
340 foreach (VarDeclaration v; er.byvalue)
342 if (log) printf("byvalue %s\n", v.toChars());
346 Dsymbol p = v.toParent2();
352 unsafeAssign(v, "scope variable");
354 else if (v.storage_class & STC.variadic && p == sc.func)
356 Type tb = v.type.toBasetype();
357 if (tb.ty == Tarray || tb.ty == Tsarray)
359 unsafeAssign(v, "variadic variable");
364 /* v is not 'scope', and is assigned to a parameter that may escape.
365 * Therefore, v can never be 'scope'.
367 if (log) printf("no infer for %s in %s loc %s, fdc %s, %d\n",
368 v.toChars(), sc.func.ident.toChars(), sc.func.loc.toChars(), fdc.ident.toChars(), __LINE__);
369 v.doNotInferScope = true;
373 foreach (VarDeclaration v; er.byref)
375 if (log) printf("byref %s\n", v.toChars());
379 Dsymbol p = v.toParent2();
383 if (!v.isReference() && p == sc.func)
385 if (psr == ScopeRef.Scope ||
386 psr == ScopeRef.RefScope ||
387 psr == ScopeRef.ReturnRef_Scope)
392 unsafeAssign(v, "reference to local variable");
397 foreach (FuncDeclaration fd; er.byfunc)
399 //printf("fd = %s, %d\n", fd.toChars(), fd.tookAddressOf);
400 VarDeclarations vars;
401 findAllOuterAccessedVariables(fd, &vars);
405 //printf("v = %s\n", v.toChars());
406 assert(!v.isDataseg()); // these are not put in the closureVars[]
408 Dsymbol p = v.toParent2();
412 if ((v.isReference() || v.isScope()) && p == sc.func)
414 unsafeAssign(v, "reference to local");
420 foreach (Expression ee; er.byexp)
422 if (sc.func && sc.func.setUnsafe())
425 error(ee.loc, "reference to stack allocated value returned by `%s` assigned to non-scope parameter `%s`",
427 par ? par.toChars() : "this");
435 /*****************************************************
436 * Function argument initializes a `return` parameter,
437 * and that parameter gets assigned to `firstArg`.
438 * Essentially, treat as `firstArg = arg;`
440 * sc = used to determine current function and module
441 * firstArg = `ref` argument through which `arg` may be assigned
442 * arg = initializer for parameter
443 * gag = do not print error messages
445 * `true` if assignment to `firstArg` would cause an error
447 bool checkParamArgumentReturn(Scope* sc, Expression firstArg, Expression arg, bool gag)
450 if (log) printf("checkParamArgumentReturn(firstArg: %s arg: %s)\n",
451 firstArg.toChars(), arg.toChars());
452 //printf("type = %s, %d\n", arg.type.toChars(), arg.type.hasPointers());
454 if (!arg.type.hasPointers())
457 scope e = new AssignExp(arg.loc, firstArg, arg);
458 return checkAssignEscape(sc, e, gag);
461 /*****************************************************
462 * Check struct constructor of the form `s.this(args)`, by
463 * checking each `return` parameter to see if it gets
466 * sc = used to determine current function and module
467 * ce = constructor call of the form `s.this(args)`
468 * gag = do not print error messages
470 * `true` if construction would cause an escaping reference error
472 bool checkConstructorEscape(Scope* sc, CallExp ce, bool gag)
475 if (log) printf("checkConstructorEscape(%s, %s)\n", ce.toChars(), ce.type.toChars());
476 Type tthis = ce.type.toBasetype();
477 assert(tthis.ty == Tstruct);
478 if (!tthis.hasPointers())
481 if (!ce.arguments && ce.arguments.dim)
484 DotVarExp dve = ce.e1.isDotVarExp();
485 CtorDeclaration ctor = dve.var.isCtorDeclaration();
486 TypeFunction tf = ctor.type.isTypeFunction();
488 const nparams = tf.parameterList.length;
489 const n = ce.arguments.dim;
491 // j=1 if _arguments[] is first argument
492 const j = tf.isDstyleVariadic();
494 /* Attempt to assign each `return` arg to the `this` reference
496 foreach (const i; 0 .. n)
498 Expression arg = (*ce.arguments)[i];
499 if (!arg.type.hasPointers())
502 //printf("\targ[%d]: %s\n", i, arg.toChars());
504 if (i - j < nparams && i >= j)
506 Parameter p = tf.parameterList[i - j];
508 if (p.storageClass & STC.return_)
510 /* Fake `dve.e1 = arg;` and look for scope violations
512 scope e = new AssignExp(arg.loc, dve.e1, arg);
513 if (checkAssignEscape(sc, e, gag))
522 /****************************************
523 * Given an `AssignExp`, determine if the lvalue will cause
524 * the contents of the rvalue to escape.
525 * Print error messages when these are detected.
526 * Infer `scope` attribute for the lvalue where possible, in order
527 * to eliminate the error.
529 * sc = used to determine current function and module
530 * e = `AssignExp` or `CatAssignExp` to check for any pointers to the stack
531 * gag = do not print error messages
533 * `true` if pointers to the stack can escape via assignment
535 bool checkAssignEscape(Scope* sc, Expression e, bool gag)
538 if (log) printf("checkAssignEscape(e: %s)\n", e.toChars());
539 if (e.op != TOK.assign && e.op != TOK.blit && e.op != TOK.construct &&
540 e.op != TOK.concatenateAssign && e.op != TOK.concatenateElemAssign && e.op != TOK.concatenateDcharAssign)
542 auto ae = cast(BinExp)e;
543 Expression e1 = ae.e1;
544 Expression e2 = ae.e2;
545 //printf("type = %s, %d\n", e1.type.toChars(), e1.type.hasPointers());
547 if (!e1.type.hasPointers())
553 /* The struct literal case can arise from the S(e2) constructor call:
555 * and appears in this function as:
556 * structLiteral = e2;
557 * Such an assignment does not necessarily remove scope-ness.
559 if (e1.isStructLiteralExp())
564 escapeByValue(e2, &er);
566 if (!er.byref.dim && !er.byvalue.dim && !er.byfunc.dim && !er.byexp.dim)
569 VarDeclaration va = expToVariable(e1);
571 if (va && e.op == TOK.concatenateElemAssign)
573 /* https://issues.dlang.org/show_bug.cgi?id=17842
574 * Draw an equivalence between:
578 * since we are not assigning to va, but are assigning indirectly through va.
583 if (va && e1.isDotVarExp() && va.type.toBasetype().isTypeClass())
585 /* https://issues.dlang.org/show_bug.cgi?id=17949
586 * Draw an equivalence between:
590 * since we are not assigning to va, but are assigning indirectly through class reference va.
595 if (log && va) printf("va: %s\n", va.toChars());
597 FuncDeclaration fd = sc.func;
599 // Try to infer 'scope' for va if in a function not marked @system
600 bool inferScope = false;
601 if (va && fd && fd.type && fd.type.isTypeFunction())
602 inferScope = fd.type.isTypeFunction().trust != TRUST.system;
603 //printf("inferScope = %d, %d\n", inferScope, (va.storage_class & STCmaybescope) != 0);
605 // Determine if va is a parameter that is an indirect reference
606 const bool vaIsRef = va && va.storage_class & STC.parameter &&
607 (va.isReference() || va.type.toBasetype().isTypeClass()); // ref, out, or class
608 if (log && vaIsRef) printf("va is ref `%s`\n", va.toChars());
610 /* Determine if va is the first parameter, through which other 'return' parameters
612 * This works the same as returning the value via a return statement.
613 * Although va is marked as `ref`, it is not regarded as returning by `ref`.
614 * https://dlang.org.spec/function.html#return-ref-parameters
620 Dsymbol p = va.toParent2();
621 if (p == fd && fd.type && fd.type.isTypeFunction())
623 TypeFunction tf = fd.type.isTypeFunction();
624 if (!tf.nextOf() || (tf.nextOf().ty != Tvoid && !fd.isCtorDeclaration()))
626 if (va == fd.vthis) // `this` of a non-static member function is considered to be the first parameter
628 if (fd.parameters && fd.parameters.length && (*fd.parameters)[0] == va) // va is first parameter
633 const bool vaIsFirstRef = isFirstRef();
634 if (log && vaIsFirstRef) printf("va is first ref `%s`\n", va.toChars());
637 foreach (VarDeclaration v; er.byvalue)
639 if (log) printf("byvalue: %s\n", v.toChars());
646 Dsymbol p = v.toParent2();
648 if (va && !vaIsRef && !va.isScope() && !v.isScope() &&
649 (va.storage_class & v.storage_class & (STC.maybescope | STC.variadic)) == STC.maybescope &&
652 /* Add v to va's list of dependencies
659 (v.isScope() || (v.storage_class & STC.maybescope)) &&
660 !(v.storage_class & STC.return_) &&
662 fd.flags & FUNCFLAG.returnInprocess &&
665 if (log) printf("inferring 'return' for parameter %s in function %s\n", v.toChars(), fd.toChars());
666 inferReturn(fd, v); // infer addition of 'return' to make `return scope`
669 if (!(va && va.isScope()) || vaIsRef)
674 if (vaIsFirstRef && v.isParameter() && v.storage_class & STC.return_)
676 // va=v, where v is `return scope`
680 if (inferScope && !va.doNotInferScope)
682 if (log) printf("inferring scope for lvalue %s\n", va.toChars());
683 va.storage_class |= STC.scope_ | STC.scopeinferred;
688 if (va && va.isScope() && va.storage_class & STC.return_ && !(v.storage_class & STC.return_) &&
691 // va may return its value, but v does not allow that, so this is an error
693 error(ae.loc, "scope variable `%s` assigned to return scope `%s`", v.toChars(), va.toChars());
698 // If va's lifetime encloses v's, then error
700 (va.enclosesLifetimeOf(v) && !(v.storage_class & (STC.parameter | STC.temp)) ||
701 // va is class reference
702 ae.e1.isDotVarExp() && va.type.toBasetype().isTypeClass() && (va.enclosesLifetimeOf(v) ||
705 va.isReference() && !(v.storage_class & (STC.parameter | STC.temp))) &&
709 error(ae.loc, "scope variable `%s` assigned to `%s` with longer lifetime", v.toChars(), va.toChars());
714 if (va && !va.isDataseg() && !va.doNotInferScope)
716 if (!va.isScope() && inferScope)
717 { /* v is scope, and va is not scope, so va needs to
720 if (log) printf("inferring scope for %s\n", va.toChars());
721 va.storage_class |= STC.scope_ | STC.scopeinferred;
722 /* v returns, and va does not return, so va needs
725 if (v.storage_class & STC.return_ &&
726 !(va.storage_class & STC.return_))
728 if (log) printf("infer return for %s\n", va.toChars());
729 va.storage_class |= STC.return_ | STC.returninferred;
731 // Added "return scope" so don't confuse it with "return ref"
732 if (isRefReturnScope(va.storage_class))
733 va.storage_class |= STC.returnScope;
741 error(ae.loc, "scope variable `%s` assigned to non-scope `%s`", v.toChars(), e1.toChars());
745 else if (v.storage_class & STC.variadic && p == fd)
747 Type tb = v.type.toBasetype();
748 if (tb.ty == Tarray || tb.ty == Tsarray)
750 if (va && !va.isDataseg() && !va.doNotInferScope)
752 if (!va.isScope() && inferScope)
753 { //printf("inferring scope for %s\n", va.toChars());
754 va.storage_class |= STC.scope_ | STC.scopeinferred;
761 error(ae.loc, "variadic variable `%s` assigned to non-scope `%s`", v.toChars(), e1.toChars());
768 /* v is not 'scope', and we didn't check the scope of where we assigned it to.
769 * It may escape via that assignment, therefore, v can never be 'scope'.
771 //printf("no infer for %s in %s, %d\n", v.toChars(), fd.ident.toChars(), __LINE__);
772 v.doNotInferScope = true;
777 foreach (VarDeclaration v; er.byref)
779 if (log) printf("byref: %s\n", v.toChars());
783 if (global.params.useDIP1000 == FeatureState.enabled)
785 if (va && va.isScope() && !v.isReference())
787 if (!(va.storage_class & STC.return_))
789 va.doNotInferReturn = true;
791 else if (fd.setUnsafe())
794 error(ae.loc, "address of local variable `%s` assigned to return scope `%s`", v.toChars(), va.toChars());
801 Dsymbol p = v.toParent2();
803 // If va's lifetime encloses v's, then error
805 (va.enclosesLifetimeOf(v) && !(v.isParameter() && v.isRef()) ||
810 error(ae.loc, "address of variable `%s` assigned to `%s` with longer lifetime", v.toChars(), va.toChars());
815 if (va && v.isReference())
817 Dsymbol pva = va.toParent2();
818 for (Dsymbol pv = p; pv; )
821 if (pva == pv) // if v is nested inside pva
826 error(ae.loc, "reference `%s` assigned to `%s` with longer lifetime", v.toChars(), va.toChars());
835 if (!(va && va.isScope()))
838 if ((global.params.useDIP1000 != FeatureState.enabled && v.isReference()) || p != sc.func)
841 if (va && !va.isDataseg() && !va.doNotInferScope)
843 if (!va.isScope() && inferScope)
844 { //printf("inferring scope for %s\n", va.toChars());
845 va.storage_class |= STC.scope_ | STC.scopeinferred;
847 if (v.storage_class & STC.return_ && !(va.storage_class & STC.return_))
848 va.storage_class |= STC.return_ | STC.returninferred;
851 if (e1.op == TOK.structLiteral)
856 error(ae.loc, "reference to local variable `%s` assigned to non-scope `%s`", v.toChars(), e1.toChars());
861 foreach (FuncDeclaration func; er.byfunc)
863 if (log) printf("byfunc: %s, %d\n", func.toChars(), func.tookAddressOf);
864 VarDeclarations vars;
865 findAllOuterAccessedVariables(func, &vars);
867 /* https://issues.dlang.org/show_bug.cgi?id=16037
868 * If assigning the address of a delegate to a scope variable,
869 * then uncount that address of. This is so it won't cause a
870 * closure to be allocated.
872 if (va && va.isScope() && !(va.storage_class & STC.return_) && func.tookAddressOf)
873 --func.tookAddressOf;
877 //printf("v = %s\n", v.toChars());
878 assert(!v.isDataseg()); // these are not put in the closureVars[]
880 Dsymbol p = v.toParent2();
882 if (!(va && va.isScope()))
885 if (!(v.isReference() || v.isScope()) || p != fd)
888 if (va && !va.isDataseg() && !va.doNotInferScope)
890 /* Don't infer STC.scope_ for va, because then a closure
891 * won't be generated for fd.
893 //if (!va.isScope() && inferScope)
894 //va.storage_class |= STC.scope_ | STC.scopeinferred;
900 error(ae.loc, "reference to local `%s` assigned to non-scope `%s` in @safe code", v.toChars(), e1.toChars());
906 foreach (Expression ee; er.byexp)
908 if (log) printf("byexp: %s\n", ee.toChars());
910 /* Do not allow slicing of a static array returned by a function
912 if (ee.op == TOK.call && ee.type.toBasetype().isTypeSArray() && e1.type.toBasetype().isTypeDArray() &&
913 !(va && va.storage_class & STC.temp))
916 deprecation(ee.loc, "slice of static array temporary returned by `%s` assigned to longer lived variable `%s`",
917 ee.toChars(), e1.toChars());
922 if (ee.op == TOK.call && ee.type.toBasetype().isTypeStruct() &&
923 (!va || !(va.storage_class & STC.temp)) &&
927 error(ee.loc, "address of struct temporary returned by `%s` assigned to longer lived variable `%s`",
928 ee.toChars(), e1.toChars());
933 if (ee.op == TOK.structLiteral &&
934 (!va || !(va.storage_class & STC.temp)) &&
938 error(ee.loc, "address of struct literal `%s` assigned to longer lived variable `%s`",
939 ee.toChars(), e1.toChars());
944 if (va && !va.isDataseg() && !va.doNotInferScope)
946 if (!va.isScope() && inferScope)
947 { //printf("inferring scope for %s\n", va.toChars());
948 va.storage_class |= STC.scope_ | STC.scopeinferred;
956 error(ee.loc, "reference to stack allocated value returned by `%s` assigned to non-scope `%s`",
957 ee.toChars(), e1.toChars());
965 /************************************
966 * Detect cases where pointers to the stack can escape the
967 * lifetime of the stack frame when throwing `e`.
968 * Print error messages when these are detected.
970 * sc = used to determine current function and module
971 * e = expression to check for any pointers to the stack
972 * gag = do not print error messages
974 * `true` if pointers to the stack can escape
976 bool checkThrowEscape(Scope* sc, Expression e, bool gag)
978 //printf("[%s] checkThrowEscape, e = %s\n", e.loc.toChars(), e.toChars());
981 escapeByValue(e, &er);
983 if (!er.byref.dim && !er.byvalue.dim && !er.byexp.dim)
987 foreach (VarDeclaration v; er.byvalue)
989 //printf("byvalue %s\n", v.toChars());
993 if (v.isScope() && !v.iscatchvar) // special case: allow catch var to be rethrown
994 // despite being `scope`
996 if (sc._module && sc._module.isRoot())
998 // Only look for errors if in module listed on command line
999 if (global.params.useDIP1000 == FeatureState.enabled) // https://issues.dlang.org/show_bug.cgi?id=17029
1002 error(e.loc, "scope variable `%s` may not be thrown", v.toChars());
1010 //printf("no infer for %s in %s, %d\n", v.toChars(), sc.func.ident.toChars(), __LINE__);
1011 v.doNotInferScope = true;
1017 /************************************
1018 * Detect cases where pointers to the stack can escape the
1019 * lifetime of the stack frame by being placed into a GC allocated object.
1020 * Print error messages when these are detected.
1022 * sc = used to determine current function and module
1023 * e = expression to check for any pointers to the stack
1024 * gag = do not print error messages
1026 * `true` if pointers to the stack can escape
1028 bool checkNewEscape(Scope* sc, Expression e, bool gag)
1030 import dmd.globals: FeatureState;
1031 import dmd.errors: previewErrorFunc;
1033 //printf("[%s] checkNewEscape, e = %s\n", e.loc.toChars(), e.toChars());
1035 if (log) printf("[%s] checkNewEscape, e: `%s`\n", e.loc.toChars(), e.toChars());
1038 escapeByValue(e, &er);
1040 if (!er.byref.dim && !er.byvalue.dim && !er.byexp.dim)
1043 bool result = false;
1044 foreach (VarDeclaration v; er.byvalue)
1046 if (log) printf("byvalue `%s`\n", v.toChars());
1050 Dsymbol p = v.toParent2();
1054 if (sc._module && sc._module.isRoot() &&
1055 /* This case comes up when the ReturnStatement of a __foreachbody is
1056 * checked for escapes by the caller of __foreachbody. Skip it.
1058 * struct S { static int opApply(int delegate(S*) dg); }
1060 * foreach (S* s; S) // create __foreachbody for body of foreach
1061 * return s; // s is inferred as 'scope' but incorrectly tested in foo()
1064 !(p.parent == sc.func))
1066 // Only look for errors if in module listed on command line
1067 if (global.params.useDIP1000 == FeatureState.enabled // https://issues.dlang.org/show_bug.cgi?id=17029
1068 && sc.func.setUnsafe()) // https://issues.dlang.org/show_bug.cgi?id=20868
1071 error(e.loc, "scope variable `%s` may not be copied into allocated memory", v.toChars());
1077 else if (v.storage_class & STC.variadic && p == sc.func)
1079 Type tb = v.type.toBasetype();
1080 if (tb.ty == Tarray || tb.ty == Tsarray)
1083 error(e.loc, "copying `%s` into allocated memory escapes a reference to variadic parameter `%s`", e.toChars(), v.toChars());
1089 //printf("no infer for %s in %s, %d\n", v.toChars(), sc.func.ident.toChars(), __LINE__);
1090 v.doNotInferScope = true;
1094 foreach (VarDeclaration v; er.byref)
1096 if (log) printf("byref `%s`\n", v.toChars());
1098 // 'featureState' tells us whether to emit an error or a deprecation,
1099 // depending on the flag passed to the CLI for DIP25
1100 void escapingRef(VarDeclaration v, FeatureState featureState = FeatureState.enabled)
1104 const(char)* kind = (v.storage_class & STC.parameter) ? "parameter" : "local";
1105 const(char)* msg = "copying `%s` into allocated memory escapes a reference to %s variable `%s`";
1106 previewErrorFunc(sc.isDeprecated(), featureState)(e.loc, msg, e.toChars(), kind, v.toChars());
1108 result |= (featureState == FeatureState.enabled);
1114 Dsymbol p = v.toParent2();
1116 if (!v.isReference())
1125 /* Check for returning a ref variable by 'ref', but should be 'return ref'
1126 * Infer the addition of 'return', or set result to be the offending expression.
1128 if (!v.isReference())
1131 if (!sc._module || !sc._module.isRoot())
1134 // https://dlang.org/spec/function.html#return-ref-parameters
1135 // Only look for errors if in module listed on command line
1138 //printf("escaping reference to local ref variable %s\n", v.toChars());
1139 //printf("storage class = x%llx\n", v.storage_class);
1140 escapingRef(v, global.params.useDIP25);
1143 // Don't need to be concerned if v's parent does not return a ref
1144 FuncDeclaration func = p.isFuncDeclaration();
1145 if (!func || !func.type)
1147 if (auto tf = func.type.isTypeFunction())
1152 const(char)* msg = "storing reference to outer local variable `%s` into allocated memory causes it to escape";
1155 previewErrorFunc(sc.isDeprecated(), global.params.useDIP25)(e.loc, msg, v.toChars());
1158 // If -preview=dip25 is used, the user wants an error
1159 // Otherwise, issue a deprecation
1160 result |= (global.params.useDIP25 == FeatureState.enabled);
1164 foreach (Expression ee; er.byexp)
1166 if (log) printf("byexp %s\n", ee.toChars());
1168 error(ee.loc, "storing reference to stack allocated value returned by `%s` into allocated memory causes it to escape",
1177 /************************************
1178 * Detect cases where pointers to the stack can escape the
1179 * lifetime of the stack frame by returning `e` by value.
1180 * Print error messages when these are detected.
1182 * sc = used to determine current function and module
1183 * e = expression to check for any pointers to the stack
1184 * gag = do not print error messages
1186 * `true` if pointers to the stack can escape
1188 bool checkReturnEscape(Scope* sc, Expression e, bool gag)
1190 //printf("[%s] checkReturnEscape, e: %s\n", e.loc.toChars(), e.toChars());
1191 return checkReturnEscapeImpl(sc, e, false, gag);
1194 /************************************
1195 * Detect cases where returning `e` by `ref` can result in a reference to the stack
1197 * Print error messages when these are detected.
1199 * sc = used to determine current function and module
1200 * e = expression to check
1201 * gag = do not print error messages
1203 * `true` if references to the stack can escape
1205 bool checkReturnEscapeRef(Scope* sc, Expression e, bool gag)
1209 printf("[%s] checkReturnEscapeRef, e = %s\n", e.loc.toChars(), e.toChars());
1210 printf("current function %s\n", sc.func.toChars());
1211 printf("parent2 function %s\n", sc.func.toParent2().toChars());
1214 return checkReturnEscapeImpl(sc, e, true, gag);
1217 /***************************************
1218 * Implementation of checking for escapes in return expressions.
1220 * sc = used to determine current function and module
1221 * e = expression to check
1222 * refs = `true`: escape by value, `false`: escape by `ref`
1223 * gag = do not print error messages
1225 * `true` if references to the stack can escape
1227 private bool checkReturnEscapeImpl(Scope* sc, Expression e, bool refs, bool gag)
1230 if (log) printf("[%s] checkReturnEscapeImpl, refs: %d e: `%s`\n", e.loc.toChars(), refs, e.toChars());
1234 escapeByRef(e, &er);
1236 escapeByValue(e, &er);
1238 if (!er.byref.dim && !er.byvalue.dim && !er.byexp.dim)
1241 bool result = false;
1242 foreach (VarDeclaration v; er.byvalue)
1244 if (log) printf("byvalue `%s`\n", v.toChars());
1248 Dsymbol p = v.toParent2();
1250 if ((v.isScope() || (v.storage_class & STC.maybescope)) &&
1251 !(v.storage_class & STC.return_) &&
1253 !v.doNotInferReturn &&
1254 sc.func.flags & FUNCFLAG.returnInprocess &&
1257 inferReturn(sc.func, v); // infer addition of 'return'
1263 if (v.storage_class & STC.return_)
1266 auto pfunc = p.isFuncDeclaration();
1267 if (pfunc && sc._module && sc._module.isRoot() &&
1268 /* This case comes up when the ReturnStatement of a __foreachbody is
1269 * checked for escapes by the caller of __foreachbody. Skip it.
1271 * struct S { static int opApply(int delegate(S*) dg); }
1273 * foreach (S* s; S) // create __foreachbody for body of foreach
1274 * return s; // s is inferred as 'scope' but incorrectly tested in foo()
1277 !(!refs && p.parent == sc.func && pfunc.fes) &&
1279 * auto p(scope string s) {
1280 * string scfunc() { return s; }
1283 !(!refs && sc.func.isFuncDeclaration().getLevel(pfunc, sc.intypeof) > 0)
1286 // Only look for errors if in module listed on command line
1287 if (global.params.useDIP1000 == FeatureState.enabled) // https://issues.dlang.org/show_bug.cgi?id=17029
1290 error(e.loc, "scope variable `%s` may not be returned", v.toChars());
1296 else if (v.storage_class & STC.variadic && p == sc.func)
1298 Type tb = v.type.toBasetype();
1299 if (tb.ty == Tarray || tb.ty == Tsarray)
1302 error(e.loc, "returning `%s` escapes a reference to variadic parameter `%s`", e.toChars(), v.toChars());
1308 //printf("no infer for %s in %s, %d\n", v.toChars(), sc.func.ident.toChars(), __LINE__);
1309 v.doNotInferScope = true;
1313 foreach (VarDeclaration v; er.byref)
1317 printf("byref `%s`\n", v.toChars());
1318 if (v.storage_class & STC.return_) printf(" return");
1319 if (v.storage_class & STC.ref_) printf(" ref");
1320 if (v.storage_class & STC.scope_) printf(" scope");
1324 // 'featureState' tells us whether to emit an error or a deprecation,
1325 // depending on the flag passed to the CLI for DIP25
1326 void escapingRef(VarDeclaration v, ScopeRef vsr, FeatureState featureState = FeatureState.enabled)
1330 const(char)* msg, supplemental;
1331 if (v.storage_class & STC.parameter &&
1332 (v.type.hasPointers() || v.storage_class & STC.ref_))
1334 msg = "returning `%s` escapes a reference to parameter `%s`";
1335 supplemental = vsr == ScopeRef.Ref_ReturnScope
1336 ? "perhaps remove `scope` parameter annotation so `return` applies to `ref`"
1337 : "perhaps annotate the parameter with `return`";
1341 msg = "returning `%s` escapes a reference to local variable `%s`";
1342 if (v.ident is Id.This)
1343 supplemental = "perhaps annotate the function with `return`";
1346 previewErrorFunc(sc.isDeprecated(), featureState)(e.loc, msg, e.toChars(), v.toChars());
1348 previewSupplementalFunc(sc.isDeprecated(), featureState)(e.loc, supplemental);
1356 const vsr = buildScopeRef(v.storage_class);
1358 Dsymbol p = v.toParent2();
1360 // https://issues.dlang.org/show_bug.cgi?id=19965
1361 if (!refs && sc.func.vthis == v)
1364 if (!v.isReference())
1368 escapingRef(v, vsr, FeatureState.enabled);
1371 FuncDeclaration fd = p.isFuncDeclaration();
1372 if (fd && sc.func.flags & FUNCFLAG.returnInprocess)
1376 * auto dg = () { return &x; }
1378 * auto dg = () return { return &x; }
1379 * Because dg.ptr points to x, this is returning dt.ptr+offset
1381 if (global.params.useDIP1000 == FeatureState.enabled)
1383 sc.func.storage_class |= STC.return_ | STC.returninferred;
1388 /* Check for returning a ref variable by 'ref', but should be 'return ref'
1389 * Infer the addition of 'return', or set result to be the offending expression.
1391 if ((vsr == ScopeRef.Ref ||
1392 vsr == ScopeRef.RefScope ||
1393 vsr == ScopeRef.Ref_ReturnScope) &&
1394 !(v.storage_class & STC.foreach_))
1396 if (sc.func.flags & FUNCFLAG.returnInprocess && p == sc.func &&
1397 (vsr == ScopeRef.Ref || vsr == ScopeRef.RefScope))
1399 inferReturn(sc.func, v); // infer addition of 'return'
1401 else if (sc._module && sc._module.isRoot())
1403 // https://dlang.org/spec/function.html#return-ref-parameters
1404 // Only look for errors if in module listed on command line
1407 //printf("escaping reference to local ref variable %s\n", v.toChars());
1408 //printf("storage class = x%llx\n", v.storage_class);
1409 escapingRef(v, vsr, global.params.useDIP25);
1412 // Don't need to be concerned if v's parent does not return a ref
1413 FuncDeclaration fd = p.isFuncDeclaration();
1414 if (fd && fd.type && fd.type.ty == Tfunction)
1416 TypeFunction tf = fd.type.isTypeFunction();
1419 const(char)* msg = "escaping reference to outer local variable `%s`";
1421 previewErrorFunc(sc.isDeprecated(), global.params.useDIP25)(e.loc, msg, v.toChars());
1431 foreach (Expression ee; er.byexp)
1433 if (log) printf("byexp %s\n", ee.toChars());
1435 error(ee.loc, "escaping reference to stack allocated value returned by `%s`", ee.toChars());
1443 /*************************************
1444 * Variable v needs to have 'return' inferred for it.
1446 * fd = function that v is a parameter to
1447 * v = parameter that needs to be STC.return_
1450 private void inferReturn(FuncDeclaration fd, VarDeclaration v)
1452 // v is a local in the current function
1454 //printf("for function '%s' inferring 'return' for variable '%s'\n", fd.toChars(), v.toChars());
1455 v.storage_class |= STC.return_ | STC.returninferred;
1459 /* v is the 'this' reference, so mark the function
1461 fd.storage_class |= STC.return_ | STC.returninferred;
1462 if (auto tf = fd.type.isTypeFunction())
1464 //printf("'this' too %p %s\n", tf, sc.func.toChars());
1466 tf.isreturninferred = true;
1471 // Perform 'return' inference on parameter
1472 if (auto tf = fd.type.isTypeFunction())
1474 foreach (i, p; tf.parameterList)
1476 if (p.ident == v.ident)
1478 p.storageClass |= STC.return_ | STC.returninferred;
1479 break; // there can be only one
1487 /****************************************
1488 * e is an expression to be returned by value, and that value contains pointers.
1489 * Walk e to determine which variables are possibly being
1490 * returned by value, such as:
1491 * int* function(int* p) { return p; }
1492 * If e is a form of &p, determine which variables have content
1493 * which is being returned as ref, such as:
1494 * int* function(int i) { return &i; }
1495 * Multiple variables can be inserted, because of expressions like this:
1496 * int function(bool b, int i, int* p) { return b ? &i : p; }
1501 * e = expression to be returned by value
1502 * er = where to place collected data
1503 * live = if @live semantics apply, i.e. expressions `p`, `*p`, `**p`, etc., all return `p`.
1505 void escapeByValue(Expression e, EscapeByResults* er, bool live = false)
1507 //printf("[%s] escapeByValue, e: %s\n", e.loc.toChars(), e.toChars());
1508 extern (C++) final class EscapeVisitor : Visitor
1510 alias visit = Visitor.visit;
1512 EscapeByResults* er;
1515 extern (D) this(EscapeByResults* er, bool live)
1521 override void visit(Expression e)
1525 override void visit(AddrExp e)
1527 /* Taking the address of struct literal is normally not
1528 * allowed, but CTFE can generate one out of a new expression,
1529 * but it'll be placed in static data so no need to check it.
1531 if (e.e1.op != TOK.structLiteral)
1532 escapeByRef(e.e1, er, live);
1535 override void visit(SymOffExp e)
1537 VarDeclaration v = e.var.isVarDeclaration();
1542 override void visit(VarExp e)
1544 if (auto v = e.var.isVarDeclaration())
1546 if (v.type.hasPointers() || // not tracking non-pointers
1547 v.storage_class & STC.lazy_) // lazy variables are actually pointers
1552 override void visit(ThisExp e)
1555 er.byvalue.push(e.var);
1558 override void visit(PtrExp e)
1560 if (live && e.type.hasPointers())
1564 override void visit(DotVarExp e)
1566 auto t = e.e1.type.toBasetype();
1567 if (e.type.hasPointers() && (live || t.ty == Tstruct))
1573 override void visit(DelegateExp e)
1575 Type t = e.e1.type.toBasetype();
1576 if (t.ty == Tclass || t.ty == Tpointer)
1577 escapeByValue(e.e1, er, live);
1579 escapeByRef(e.e1, er, live);
1580 er.byfunc.push(e.func);
1583 override void visit(FuncExp e)
1585 if (e.fd.tok == TOK.delegate_)
1586 er.byfunc.push(e.fd);
1589 override void visit(TupleExp e)
1591 assert(0); // should have been lowered by now
1594 override void visit(ArrayLiteralExp e)
1596 Type tb = e.type.toBasetype();
1597 if (tb.ty == Tsarray || tb.ty == Tarray)
1600 e.basis.accept(this);
1601 foreach (el; *e.elements)
1609 override void visit(StructLiteralExp e)
1613 foreach (ex; *e.elements)
1621 override void visit(NewExp e)
1623 Type tb = e.newtype.toBasetype();
1624 if (tb.ty == Tstruct && !e.member && e.arguments)
1626 foreach (ex; *e.arguments)
1634 override void visit(CastExp e)
1636 if (!e.type.hasPointers())
1638 Type tb = e.type.toBasetype();
1639 if (tb.ty == Tarray && e.e1.type.toBasetype().ty == Tsarray)
1641 escapeByRef(e.e1, er, live);
1647 override void visit(SliceExp e)
1649 if (auto ve = e.e1.isVarExp())
1651 VarDeclaration v = ve.var.isVarDeclaration();
1652 Type tb = e.type.toBasetype();
1655 if (tb.ty == Tsarray)
1657 if (v.storage_class & STC.variadic)
1664 Type t1b = e.e1.type.toBasetype();
1665 if (t1b.ty == Tsarray)
1667 Type tb = e.type.toBasetype();
1668 if (tb.ty != Tsarray)
1669 escapeByRef(e.e1, er, live);
1675 override void visit(IndexExp e)
1677 if (e.e1.type.toBasetype().ty == Tsarray ||
1678 live && e.type.hasPointers())
1684 override void visit(BinExp e)
1686 Type tb = e.type.toBasetype();
1687 if (tb.ty == Tpointer)
1694 override void visit(BinAssignExp e)
1699 override void visit(AssignExp e)
1704 override void visit(CommaExp e)
1709 override void visit(CondExp e)
1715 override void visit(CallExp e)
1717 //printf("CallExp(): %s\n", e.toChars());
1718 /* Check each argument that is
1719 * passed as 'return scope'.
1721 Type t1 = e.e1.type.toBasetype();
1724 if (t1.ty == Tdelegate)
1726 dg = t1.isTypeDelegate();
1727 tf = dg.next.isTypeFunction();
1729 else if (t1.ty == Tfunction)
1730 tf = t1.isTypeFunction();
1734 if (!e.type.hasPointers())
1737 if (e.arguments && e.arguments.dim)
1739 /* j=1 if _arguments[] is first argument,
1740 * skip it because it is not passed by ref
1742 int j = tf.isDstyleVariadic();
1743 for (size_t i = j; i < e.arguments.dim; ++i)
1745 Expression arg = (*e.arguments)[i];
1746 size_t nparams = tf.parameterList.length;
1747 if (i - j < nparams && i >= j)
1749 Parameter p = tf.parameterList[i - j];
1750 const stc = tf.parameterStorageClass(null, p);
1751 if ((stc & (STC.scope_)) && (stc & STC.return_))
1753 else if ((stc & (STC.ref_)) && (stc & STC.return_))
1758 * ref P foo(return ref P p)
1765 escapeByRef(arg, er, live);
1770 // If 'this' is returned, check it too
1771 if (e.e1.op == TOK.dotVariable && t1.ty == Tfunction)
1773 DotVarExp dve = e.e1.isDotVarExp();
1774 FuncDeclaration fd = dve.var.isFuncDeclaration();
1775 AggregateDeclaration ad;
1776 if (global.params.useDIP1000 == FeatureState.enabled && tf.isreturn && fd && (ad = fd.isThis()) !is null)
1778 if (ad.isClassDeclaration() || tf.isScopeQual) // this is 'return scope'
1779 dve.e1.accept(this);
1780 else if (ad.isStructDeclaration()) // this is 'return ref'
1785 * struct S { ref S foo() return; }
1789 dve.e1.accept(this);
1792 escapeByRef(dve.e1, er, live);
1795 else if (dve.var.storage_class & STC.return_ || tf.isreturn)
1797 if (dve.var.storage_class & STC.scope_)
1798 dve.e1.accept(this);
1799 else if (dve.var.storage_class & STC.ref_)
1800 escapeByRef(dve.e1, er, live);
1802 // If it's also a nested function that is 'return scope'
1803 if (fd && fd.isNested())
1805 if (tf.isreturn && tf.isScopeQual)
1810 /* If returning the result of a delegate call, the .ptr
1811 * field of the delegate must be checked.
1819 /* If it's a nested function that is 'return scope'
1821 if (auto ve = e.e1.isVarExp())
1823 FuncDeclaration fd = ve.var.isFuncDeclaration();
1824 if (fd && fd.isNested())
1826 if (tf.isreturn && tf.isScopeQual)
1833 scope EscapeVisitor v = new EscapeVisitor(er, live);
1838 /****************************************
1839 * e is an expression to be returned by 'ref'.
1840 * Walk e to determine which variables are possibly being
1841 * returned by ref, such as:
1842 * ref int function(int i) { return i; }
1843 * If e is a form of *p, determine which variables have content
1844 * which is being returned as ref, such as:
1845 * ref int function(int* p) { return *p; }
1846 * Multiple variables can be inserted, because of expressions like this:
1847 * ref int function(bool b, int i, int* p) { return b ? i : *p; }
1852 * e = expression to be returned by 'ref'
1853 * er = where to place collected data
1854 * live = if @live semantics apply, i.e. expressions `p`, `*p`, `**p`, etc., all return `p`.
1856 void escapeByRef(Expression e, EscapeByResults* er, bool live = false)
1858 //printf("[%s] escapeByRef, e: %s\n", e.loc.toChars(), e.toChars());
1859 extern (C++) final class EscapeRefVisitor : Visitor
1861 alias visit = Visitor.visit;
1863 EscapeByResults* er;
1866 extern (D) this(EscapeByResults* er, bool live)
1872 override void visit(Expression e)
1876 override void visit(VarExp e)
1878 auto v = e.var.isVarDeclaration();
1881 if (v.storage_class & STC.ref_ && v.storage_class & (STC.foreach_ | STC.temp) && v._init)
1883 /* If compiler generated ref temporary
1885 * look at the initializer instead
1887 if (ExpInitializer ez = v._init.isExpInitializer())
1889 if (auto ce = ez.exp.isConstructExp())
1892 ez.exp.accept(this);
1900 override void visit(ThisExp e)
1902 if (e.var && e.var.toParent2().isFuncDeclaration().isThis2)
1903 escapeByValue(e, er, live);
1905 er.byref.push(e.var);
1908 override void visit(PtrExp e)
1910 escapeByValue(e.e1, er, live);
1913 override void visit(IndexExp e)
1915 Type tb = e.e1.type.toBasetype();
1916 if (auto ve = e.e1.isVarExp())
1918 VarDeclaration v = ve.var.isVarDeclaration();
1919 if (tb.ty == Tarray || tb.ty == Tsarray)
1921 if (v && v.storage_class & STC.variadic)
1928 if (tb.ty == Tsarray)
1932 else if (tb.ty == Tarray)
1934 escapeByValue(e.e1, er, live);
1938 override void visit(StructLiteralExp e)
1942 foreach (ex; *e.elements)
1951 override void visit(DotVarExp e)
1953 Type t1b = e.e1.type.toBasetype();
1954 if (t1b.ty == Tclass)
1955 escapeByValue(e.e1, er, live);
1960 override void visit(BinAssignExp e)
1965 override void visit(AssignExp e)
1970 override void visit(CommaExp e)
1975 override void visit(CondExp e)
1981 override void visit(CallExp e)
1983 //printf("escapeByRef.CallExp(): %s\n", e.toChars());
1984 /* If the function returns by ref, check each argument that is
1985 * passed as 'return ref'.
1987 Type t1 = e.e1.type.toBasetype();
1989 if (t1.ty == Tdelegate)
1990 tf = t1.isTypeDelegate().next.isTypeFunction();
1991 else if (t1.ty == Tfunction)
1992 tf = t1.isTypeFunction();
1997 if (e.arguments && e.arguments.dim)
1999 /* j=1 if _arguments[] is first argument,
2000 * skip it because it is not passed by ref
2002 int j = tf.isDstyleVariadic();
2003 for (size_t i = j; i < e.arguments.dim; ++i)
2005 Expression arg = (*e.arguments)[i];
2006 size_t nparams = tf.parameterList.length;
2007 if (i - j < nparams && i >= j)
2009 Parameter p = tf.parameterList[i - j];
2010 const stc = tf.parameterStorageClass(null, p);
2011 if ((stc & (STC.out_ | STC.ref_)) && (stc & STC.return_))
2013 else if ((stc & STC.scope_) && (stc & STC.return_))
2015 if (auto de = arg.isDelegateExp())
2017 if (de.func.isNested())
2021 escapeByValue(arg, er, live);
2026 // If 'this' is returned by ref, check it too
2027 if (e.e1.op == TOK.dotVariable && t1.ty == Tfunction)
2029 DotVarExp dve = e.e1.isDotVarExp();
2031 // https://issues.dlang.org/show_bug.cgi?id=20149#c10
2032 if (dve.var.isCtorDeclaration())
2038 if (dve.var.storage_class & STC.return_ || tf.isreturn)
2040 if (dve.var.storage_class & STC.ref_ || tf.isref)
2041 dve.e1.accept(this);
2042 else if (dve.var.storage_class & STC.scope_ || tf.isScopeQual)
2043 escapeByValue(dve.e1, er, live);
2045 // If it's also a nested function that is 'return ref'
2046 FuncDeclaration fd = dve.var.isFuncDeclaration();
2047 if (fd && fd.isNested())
2053 // If it's a delegate, check it too
2054 if (e.e1.op == TOK.variable && t1.ty == Tdelegate)
2056 escapeByValue(e.e1, er, live);
2059 /* If it's a nested function that is 'return ref'
2061 if (auto ve = e.e1.isVarExp())
2063 FuncDeclaration fd = ve.var.isFuncDeclaration();
2064 if (fd && fd.isNested())
2076 scope EscapeRefVisitor v = new EscapeRefVisitor(er, live);
2081 /************************************
2082 * Aggregate the data collected by the escapeBy??() functions.
2084 struct EscapeByResults
2086 VarDeclarations byref; // array into which variables being returned by ref are inserted
2087 VarDeclarations byvalue; // array into which variables with values containing pointers are inserted
2088 FuncDeclarations byfunc; // nested functions that are turned into delegates
2089 Expressions byexp; // array into which temporaries being returned by ref are inserted
2091 /** Reset arrays so the storage can be used again
2102 /*************************
2103 * Find all variables accessed by this delegate that are
2104 * in functions enclosing it.
2107 * vars = array to append found variables to
2109 public void findAllOuterAccessedVariables(FuncDeclaration fd, VarDeclarations* vars)
2111 //printf("findAllOuterAccessedVariables(fd: %s)\n", fd.toChars());
2112 for (auto p = fd.parent; p; p = p.parent)
2114 auto fdp = p.isFuncDeclaration();
2118 foreach (v; fdp.closureVars)
2120 foreach (const fdv; v.nestedrefs)
2124 //printf("accessed: %s, type %s\n", v.toChars(), v.type.toChars());
2132 /***********************************
2133 * Turn off `STC.maybescope` for variable `v`.
2135 * This exists in order to find where `STC.maybescope` is getting turned off.
2141 public void notMaybeScope(string file = __FILE__, int line = __LINE__)(VarDeclaration v)
2143 printf("%.*s(%d): notMaybeScope('%s')\n", cast(int)file.length, file.ptr, line, v.toChars());
2144 v.storage_class &= ~STC.maybescope;
2149 public void notMaybeScope(VarDeclaration v)
2151 v.storage_class &= ~STC.maybescope;
2156 /**********************************************
2157 * Have some variables that are maybescopes that were
2158 * assigned values from other maybescope variables.
2159 * Now that semantic analysis of the function is
2160 * complete, we can finalize this by turning off
2161 * maybescope for array elements that cannot be scope.
2163 * $(TABLE2 Scope Table,
2164 * $(THEAD `va`, `v`, =>, `va` , `v` )
2165 * $(TROW maybe, maybe, =>, scope, scope)
2166 * $(TROW scope, scope, =>, scope, scope)
2167 * $(TROW scope, maybe, =>, scope, scope)
2168 * $(TROW maybe, scope, =>, scope, scope)
2169 * $(TROW - , - , =>, - , - )
2170 * $(TROW - , maybe, =>, - , - )
2171 * $(TROW - , scope, =>, error, error)
2172 * $(TROW maybe, - , =>, scope, - )
2173 * $(TROW scope, - , =>, scope, - )
2176 * array = array of variables that were assigned to from maybescope variables
2178 public void eliminateMaybeScopes(VarDeclaration[] array)
2181 if (log) printf("eliminateMaybeScopes()\n");
2188 if (log) printf(" va = %s\n", va.toChars());
2189 if (!(va.storage_class & (STC.maybescope | STC.scope_)))
2193 foreach (v; *va.maybes)
2195 if (log) printf(" v = %s\n", v.toChars());
2196 if (v.storage_class & STC.maybescope)
2198 // v cannot be scope since it is assigned to a non-scope va
2200 if (!v.isReference())
2201 v.storage_class &= ~(STC.return_ | STC.returninferred);
2211 /************************************************
2212 * Is type a reference to a mutable value?
2214 * This is used to determine if an argument that does not have a corresponding
2215 * Parameter, i.e. a variadic argument, is a pointer to mutable data.
2217 * t = type of the argument
2219 * true if it's a pointer (or reference) to mutable data
2221 bool isReferenceToMutable(Type t)
2225 if (!t.isMutable() ||
2232 if (t.nextOf().isTypeFunction())
2239 if (t.nextOf().isMutable())
2244 return true; // even if the class fields are not mutable
2247 // Have to look at each field
2248 foreach (VarDeclaration v; t.isTypeStruct().sym.fields)
2250 if (v.storage_class & STC.ref_)
2252 if (v.type.isMutable())
2255 else if (v.type.isReferenceToMutable())
2266 /****************************************
2267 * Is parameter a reference to a mutable value?
2269 * This is used if an argument has a corresponding Parameter.
2270 * The argument type is necessary if the Parameter is inout.
2272 * p = Parameter to check
2273 * t = type of corresponding argument
2275 * true if it's a pointer (or reference) to mutable data
2277 bool isReferenceToMutable(Parameter p, Type t)
2279 if (p.isReference())
2281 if (p.type.isConst() || p.type.isImmutable())
2283 if (p.type.isWild())
2285 return t.isMutable();
2287 return p.type.isMutable();
2289 return isReferenceToMutable(p.type);