Changeset 7b91c0e


Ignore:
Timestamp:
Jan 21, 2021, 2:24:01 PM (11 months ago)
Author:
Thierry Delisle <tdelisle@…>
Branches:
arm-eh, jacob/cs343-translation, master, new-ast-unique-expr
Children:
7d01186d
Parents:
5869cea (diff), 1adab3e (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

Files:
5 added
157 edited

Legend:

Unmodified
Added
Removed
  • doc/bibliography/pl.bib

    r5869cea r7b91c0e  
    688688    title       = {Asynchronous Exception Propagation in Blocked Tasks},
    689689    booktitle   = {4th International Workshop on Exception Handling (WEH.08)},
    690     organization= {16th International Symposium on the Foundations of Software Engineering (FSE 16)},
     690    optorganization= {16th International Symposium on the Foundations of Software Engineering (FSE 16)},
    691691    address     = {Atlanta, U.S.A},
    692692    month       = nov,
     
    72467246
    72477247@inproceedings{Edelson92,
    7248     keywords    = {persistence, pointers},
     7248    keywords    = {persistence, smart pointers},
    72497249    contributer = {pabuhr@plg},
    72507250    author      = {Daniel R. Edelson},
     
    72567256    year        = 1992,
    72577257    pages       = {1-19},
     7258}
     7259
     7260@incollection{smartpointers,
     7261    keywords    = {smart pointers},
     7262    contributer = {pabuhr@plg},
     7263    author      = {Andrei Alexandrescu},
     7264    title       = {Smart Pointers},
     7265    booktitle   = {Modern C++ Design: Generic Programming and Design Patterns Applied},
     7266    publisher   = {Addison-Wesley},
     7267    year        = 2001,
     7268    chapter     = 7,
     7269    optpages    = {?-?},
    72587270}
    72597271
     
    82458257}
    82468258
     8259@misc{vistorpattern,
     8260    keywords    = {visitor pattern},
     8261    contributer = {pabuhr@plg},
     8262    key         = {vistor pattern},
     8263    title       = {vistor pattern},
     8264    year        = 2020,
     8265    note        = {WikipediA},
     8266    howpublished= {\href{https://en.wikipedia.org/wiki/Visitor\_pattern}
     8267                  {https://\-en.wikipedia.org/\-wiki/\-Visitor\_pattern}},
     8268}
     8269
    82478270% W
    82488271
  • doc/theses/andrew_beach_MMath/Makefile

    r5869cea r7b91c0e  
    11### Makefile for Andrew Beach's Masters Thesis
    22
    3 DOC=thesis.pdf
     3DOC=uw-ethesis.pdf
    44BUILD=out
    55TEXSRC=$(wildcard *.tex)
     
    77STYSRC=$(wildcard *.sty)
    88CLSSRC=$(wildcard *.cls)
    9 TEXLIB= .:${BUILD}:
     9TEXLIB= .:../../LaTeXmacros:${BUILD}:
    1010BIBLIB= .:../../bibliography
    1111
     
    2929        ${LATEX} ${BASE}
    3030        ${BIBTEX} ${BUILD}/${BASE}
     31        ${LATEX} ${BASE}
    3132        ${GLOSSARY} ${BUILD}/${BASE}
    3233        ${LATEX} ${BASE}
  • doc/theses/andrew_beach_MMath/existing.tex

    r5869cea r7b91c0e  
    1 \chapter{\CFA{} Existing Features}
     1\chapter{\CFA Existing Features}
     2
     3\CFA (C-for-all)~\cite{Cforall} is an open-source project extending ISO C with modern safety and productivity features, while still ensuring backwards compatibility with C and its programmers.
     4\CFA is designed to have an orthogonal feature-set based closely on the C programming paradigm (non-object-oriented) and these features can be added incrementally to an existing C code-base allowing programmers to learn \CFA on an as-needed basis.
    25
    36\section{Overloading and extern}
    47Cforall has overloading, allowing multiple definitions of the same name to
    5 be defined.
     8be defined.~\cite{Moss18}
    69
    710This also adds name mangling so that the assembly symbols are unique for
     
    1114
    1215The syntax for disabling mangling is:
    13 \begin{lstlisting}
     16\begin{cfa}
    1417extern "C" {
    1518    ...
    1619}
    17 \end{lstlisting}
     20\end{cfa}
    1821
    1922To re-enable mangling once it is disabled the syntax is:
    20 \begin{lstlisting}
     23\begin{cfa}
    2124extern "Cforall" {
    2225    ...
    2326}
    24 \end{lstlisting}
     27\end{cfa}
    2528
    2629Both should occur at the declaration level and effect all the declarations
    27 in \texttt{...}. Neither care about the state of mangling when they begin
     30in @...@. Neither care about the state of mangling when they begin
    2831and will return to that state after the group is finished. So re-enabling
    2932is only used to nest areas of mangled and unmangled declarations.
     
    3134\section{References}
    3235\CFA adds references to C. These are auto-dereferencing pointers and use the
    33 same syntax as pointers except they use ampersand (\codeCFA{\&}) instead of
    34 the asterisk (\codeCFA{*}). They can also be constaint or mutable, if they
     36same syntax as pointers except they use ampersand (@&@) instead of
     37the asterisk (@*@). They can also be constaint or mutable, if they
    3538are mutable they may be assigned to by using the address-of operator
    36 (\codeCFA\&) which converts them into a pointer.
     39(@&@) which converts them into a pointer.
    3740
    3841\section{Constructors and Destructors}
     
    4144functions with special names. The special names are used to define them and
    4245may be used to call the functions expicately. The \CFA special names are
    43 constructed by taking the tokens in the operators and putting \texttt{?} where
    44 the arguments would go. So multiplication is \texttt{?*?} while dereference
    45 is \texttt{*?}. This also make it easy to tell the difference between
    46 pre-fix operations (such as \texttt{++?}) and post-fix operations
    47 (\texttt{?++}).
    48 
    49 The special name for contructors is \texttt{?\{\}}, which comes from the
     46constructed by taking the tokens in the operators and putting @?@ where
     47the arguments would go. So multiplication is @?*?@ while dereference
     48is @*?@. This also make it easy to tell the difference between
     49pre-fix operations (such as @++?@) and post-fix operations
     50(@?++@).
     51
     52The special name for contructors is @?{}@, which comes from the
    5053initialization syntax in C. The special name for destructors is
    51 \texttt{\^{}?\{\}}. % I don't like the \^{} symbol but $^\wedge$ isn't better.
     54@^{}@. % I don't like the \^{} symbol but $^\wedge$ isn't better.
    5255
    5356Any time a type T goes out of scope the destructor matching
    54 \codeCFA{void ^?\{\}(T \&);} is called. In theory this is also true of
    55 primitive types such as \codeCFA{int}, but in practice those are no-ops and
     57@void ^?{}(T &);@ is called. In theory this is also true of
     58primitive types such as @int@, but in practice those are no-ops and
    5659are usually omitted for optimization.
    5760
    5861\section{Polymorphism}
    5962\CFA uses polymorphism to create functions and types that are defined over
    60 different types. \CFA polymorphic declarations serve the same role as \CPP
     63different types. \CFA polymorphic declarations serve the same role as \CC
    6164templates or Java generics.
    6265
     
    6568except that you may use the names introduced by the forall clause in them.
    6669
    67 Forall clauses are written \codeCFA{forall( ... )} where \codeCFA{...} becomes
     70Forall clauses are written @forall( ... )@ where @...@ becomes
    6871the list of polymorphic variables (local type names) and assertions, which
    6972repersent required operations on those types.
    7073
    71 \begin{lstlisting}
     74\begin{cfa}
    7275forall(dtype T | { void do_once(T &); })
    7376void do_twice(T & value) {
     
    7578    do_once(value);
    7679}
    77 \end{lstlisting}
     80\end{cfa}
    7881
    7982A polymorphic function can be used in the same way normal functions are.
     
    8386the the call site.
    8487
    85 As an example, even if no function named \codeCFA{do_once} is not defined
    86 near the definition of \codeCFA{do_twice} the following code will work.
    87 \begin{lstlisting}
     88As an example, even if no function named @do_once@ is not defined
     89near the definition of @do_twice@ the following code will work.
     90\begin{cfa}
    8891int quadruple(int x) {
    8992    void do_once(int & y) {
     
    9396    return x;
    9497}
    95 \end{lstlisting}
     98\end{cfa}
    9699This is not the recommended way to implement a quadruple function but it
    97 does work. The complier will deduce that \codeCFA{do_twice}'s T is an
     100does work. The complier will deduce that @do_twice@'s T is an
    98101integer from the argument. It will then look for a definition matching the
    99 assertion which is the \codeCFA{do_once} defined within the function. That
    100 function will be passed in as a function pointer to \codeCFA{do_twice} and
     102assertion which is the @do_once@ defined within the function. That
     103function will be passed in as a function pointer to @do_twice@ and
    101104called within it.
    102105
     
    104107traits which collect assertions into convenent packages that can then be used
    105108in assertion lists instead of all of their components.
    106 \begin{lstlisting}
     109\begin{cfa}
    107110trait done_once(dtype T) {
    108111    void do_once(T &);
    109112}
    110 \end{lstlisting}
     113\end{cfa}
    111114
    112115After this the forall list in the previous example could instead be written
    113116with the trait instead of the assertion itself.
    114 \begin{lstlisting}
     117\begin{cfa}
    115118forall(dtype T | done_once(T))
    116 \end{lstlisting}
     119\end{cfa}
    117120
    118121Traits can have arbitrary number of assertions in them and are usually used to
     
    124127are now used in field declaractions instead of parameters and local variables.
    125128
    126 \begin{lstlisting}
     129\begin{cfa}
    127130forall(dtype T)
    128131struct node {
     
    130133    T * data;
    131134}
    132 \end{lstlisting}
    133 
    134 The \codeCFA{node(T)} is a use of a polymorphic structure. Polymorphic types
     135\end{cfa}
     136
     137The @node(T)@ is a use of a polymorphic structure. Polymorphic types
    135138must be provided their polymorphic parameters.
    136139
     
    140143\section{Concurrency}
    141144
    142 \CFA has a number of concurrency features, \codeCFA{thread}s,
    143 \codeCFA{monitor}s and \codeCFA{mutex} parameters, \codeCFA{coroutine}s and
    144 \codeCFA{generator}s. The two features that interact with the exception system
    145 are \codeCFA{thread}s and \codeCFA{coroutine}s; they and their supporting
     145\CFA has a number of concurrency features, @thread@s,
     146@monitor@s and @mutex@ parameters, @coroutine@s and
     147@generator@s. The two features that interact with the exception system
     148are @thread@s and @coroutine@s; they and their supporting
    146149constructs will be described here.
    147150
     
    154157library.
    155158
    156 In \CFA coroutines are created using the \codeCFA{coroutine} keyword which
    157 works just like \codeCFA{struct} except that the created structure will be
    158 modified by the compiler to satify the \codeCFA{is_coroutine} trait.
     159In \CFA coroutines are created using the @coroutine@ keyword which
     160works just like @struct@ except that the created structure will be
     161modified by the compiler to satify the @is_coroutine@ trait.
    159162
    160163These structures act as the interface between callers and the coroutine,
    161164the fields are used to pass information in and out. Here is a simple example
    162165where the single field is used to pass the next number in a sequence out.
    163 \begin{lstlisting}
     166\begin{cfa}
    164167coroutine CountUp {
    165168    unsigned int next;
    166169}
    167 \end{lstlisting}
     170\end{cfa}
    168171
    169172The routine part of the coroutine is a main function for the coroutine. It
     
    173176function it continue from that same suspend statement instead of at the top
    174177of the function.
    175 \begin{lstlisting}
     178\begin{cfa}
    176179void main(CountUp & this) {
    177180    unsigned int next = 0;
     
    182185    }
    183186}
    184 \end{lstlisting}
     187\end{cfa}
    185188
    186189Control is passed to the coroutine with the resume function. This includes the
     
    189192return value is for easy access to communication variables. For example the
    190193next value from a count-up can be generated and collected in a single
    191 expression: \codeCFA{resume(count).next}.
     194expression: @resume(count).next@.
    192195
    193196\subsection{Monitors and Mutex}
     
    198201parameters.
    199202
    200 Function parameters can have the \codeCFA{mutex} qualifiers on reference
    201 arguments, for example \codeCFA{void example(a_monitor & mutex arg);}. When the
     203Function parameters can have the @mutex@ qualifiers on reference
     204arguments, for example @void example(a_monitor & mutex arg);@. When the
    202205function is called it will acquire the lock on all of the mutex parameters.
    203206
     
    214217
    215218Threads are created like coroutines except the keyword is changed:
    216 \begin{lstlisting}
     219\begin{cfa}
    217220thread StringWorker {
    218221    const char * input;
     
    225228    this.result = result;
    226229}
    227 \end{lstlisting}
     230\end{cfa}
    228231The main function will start executing after the fork operation and continue
    229232executing until it is finished. If another thread joins with this one it will
     
    233236From the outside this is the creation and destruction of the thread object.
    234237Fork happens after the constructor is run and join happens before the
    235 destructor runs. Join also happens during the \codeCFA{join} function which
     238destructor runs. Join also happens during the @join@ function which
    236239can be used to join a thread earlier. If it is used the destructor does not
    237240join as that has already been completed.
  • doc/theses/andrew_beach_MMath/features.tex

    r5869cea r7b91c0e  
    5454returns a reference to the virtual table instance. Defining this function
    5555also establishes the virtual type and virtual table pair to the resolver
    56 and promises that \codeCFA{exceptT} is a virtual type and a child of the
     56and promises that @exceptT@ is a virtual type and a child of the
    5757base exception type.
    5858
    59 One odd thing about \codeCFA{get_exception_vtable} is that it should always
     59One odd thing about @get_exception_vtable@ is that it should always
    6060be a constant function, returning the same value regardless of its argument.
    6161A pointer or reference to the virtual table instance could be used instead,
     
    6666
    6767Also note the use of the word ``promise" in the trait description. \CFA
    68 cannot currently check to see if either \codeCFA{exceptT} or
    69 \codeCFA{virtualT} match the layout requirements. Currently this is
    70 considered part of \codeCFA{get_exception_vtable}'s correct implementation.
     68cannot currently check to see if either @exceptT@ or
     69@virtualT@ match the layout requirements. Currently this is
     70considered part of @get_exception_vtable@'s correct implementation.
    7171
    7272\begin{lstlisting}
     
    9292
    9393Finally there are three additional macros that can be used to refer to the
    94 these traits. They are \codeCFA{IS_EXCEPTION},
    95 \codeCFA{IS_TERMINATION_EXCEPTION} and \codeCFA{IS_RESUMPTION_EXCEPTION}.
     94these traits. They are @IS_EXCEPTION@,
     95@IS_TERMINATION_EXCEPTION@ and @IS_RESUMPTION_EXCEPTION@.
    9696Each takes the virtual type's name and, for polymorphic types only, the
    9797parenthesized list of polymorphic arguments. These do the name mangling to
     
    113113The expression must evaluate to a reference to a termination exception. A
    114114termination exception is any exception with a
    115 \codeCFA{void defaultTerminationHandler(T &);} (the default handler) defined
     115@void defaultTerminationHandler(T &);@ (the default handler) defined
    116116on it. The handler is taken from the call sight with \CFA's trait system and
    117117passed into the exception system along with the exception itself.
     
    169169
    170170You can also re-throw the most recent termination exception with
    171 \codeCFA{throw;}. % This is terrible and you should never do it.
     171@throw;@. % This is terrible and you should never do it.
    172172This can be done in a handler or any function that could be called from a
    173173handler.
     
    193193The result of EXPRESSION must be a resumption exception type. A resumption
    194194exception type is any type that satisfies the assertion
    195 \codeCFA{void defaultResumptionHandler(T &);} (the default handler). When the
     195@void defaultResumptionHandler(T &);@ (the default handler). When the
    196196statement is executed the expression is evaluated and the result is thrown.
    197197
     
    260260\paragraph{Re-Throwing}
    261261
    262 You may also re-throw resumptions with a \codeCFA{throwResume;} statement.
    263 This can only be done from inside of a \codeCFA{catchResume} block.
     262You may also re-throw resumptions with a @throwResume;@ statement.
     263This can only be done from inside of a @catchResume@ block.
    264264
    265265Outside of any side effects of any code already run in the handler this will
     
    269269\section{Finally Clauses}
    270270
    271 A \codeCFA{finally} clause may be placed at the end of a try statement after
     271A @finally@ clause may be placed at the end of a try statement after
    272272all the handler clauses. In the simply case, with no handlers, it looks like
    273273this:
     
    294294
    295295Because of this local control flow out of the finally block is forbidden.
    296 The compiler rejects uses of \codeCFA{break}, \codeCFA{continue},
    297 \codeCFA{fallthru} and \codeCFA{return} that would cause control to leave
     296The compiler rejects uses of @break@, @continue@,
     297@fallthru@ and @return@ that would cause control to leave
    298298the finally block. Other ways to leave the finally block - such as a long
    299299jump or termination - are much harder to check, at best requiring additional
     
    307307
    308308There is no special statement for starting a cancellation, instead you call
    309 the standard library function \codeCFA{cancel\_stack} which takes an exception.
     309the standard library function @cancel\_stack@ which takes an exception.
    310310Unlike in a throw this exception is not used in control flow but is just there
    311311to pass information about why the cancellation happened.
     
    323323
    324324\item Thread Stack:
    325 Thread stacks are those created \codeCFA{thread} or otherwise satisfy the
    326 \codeCFA{is\_thread} trait.
     325Thread stacks are those created @thread@ or otherwise satisfy the
     326@is\_thread@ trait.
    327327
    328328Threads only have two structural points of communication that must happen,
     
    333333and wait for another thread to join with it. The other thread, when it joins,
    334334checks for a cancellation. If so it will throw the resumption exception
    335 \codeCFA{ThreadCancelled}.
    336 
    337 There is a difference here in how explicate joins (with the \codeCFA{join}
     335@ThreadCancelled@.
     336
     337There is a difference here in how explicate joins (with the @join@
    338338function) and implicate joins (from a destructor call). Explicate joins will
    339 take the default handler (\codeCFA{defaultResumptionHandler}) from the context
     339take the default handler (@defaultResumptionHandler@) from the context
    340340and use like a regular through does if the exception is not caught. The
    341341implicate join does a program abort instead.
     
    349349
    350350\item Coroutine Stack:
    351 Coroutine stacks are those created with \codeCFA{coroutine} or otherwise
    352 satisfy the \codeCFA{is\_coroutine} trait.
     351Coroutine stacks are those created with @coroutine@ or otherwise
     352satisfy the @is\_coroutine@ trait.
    353353
    354354A coroutine knows of two other coroutines, its starter and its last resumer.
     
    356356
    357357After the stack is unwound control goes to the last resumer.
    358 Resume will resume throw a \codeCFA{CoroutineCancelled} exception, which is
     358Resume will resume throw a @CoroutineCancelled@ exception, which is
    359359polymorphic over the coroutine type and has a pointer to the coroutine being
    360360canceled and the canceling exception. The resume function also has an
    361 assertion that the \codeCFA{defaultResumptionHandler} for the exception. So it
     361assertion that the @defaultResumptionHandler@ for the exception. So it
    362362will use the default handler like a regular throw.
    363363
  • doc/theses/andrew_beach_MMath/future.tex

    r5869cea r7b91c0e  
    2020
    2121\section{Additional Throws}
    22 Several other kinds of throws, beyond the termination throw (\codeCFA{throw}),
    23 the resumption throw (\codeCFA{throwResume}) and the re-throws, were considered.
     22Several other kinds of throws, beyond the termination throw (@throw@),
     23the resumption throw (@throwResume@) and the re-throws, were considered.
    2424None were as useful as the core throws but they would likely be worth
    2525revising.
     
    114114is no reason not to allow it. It is however a small improvement; giving a bit
    115115of flexibility to the user in what style they want to use.
    116 \item Enabling local control flow (by \codeCFA{break}, \codeCFA{return} and
     116\item Enabling local control flow (by @break@, @return@ and
    117117similar statements) out of a termination handler. The current set-up makes
    118118this very difficult but the catch function that runs the handler after it has
  • doc/theses/andrew_beach_MMath/implement.tex

    r5869cea r7b91c0e  
    99
    1010All of this is accessed through a field inserted at the beginning of every
    11 virtual type. Currently it is called \codeC{virtual_table} but it is not
     11virtual type. Currently it is called @virtual_table@ but it is not
    1212ment to be accessed by the user. This field is a pointer to the type's
    1313virtual table instance. It is assigned once during the object's construction
     
    4040using that to calculate the mangled name of the parent's virtual table type.
    4141There are two special fields that are included like normal fields but have
    42 special initialization rules: the \codeC{size} field is the type's size and is
    43 initialized with a sizeof expression, the \codeC{align} field is the type's
     42special initialization rules: the @size@ field is the type's size and is
     43initialized with a sizeof expression, the @align@ field is the type's
    4444alignment and uses an alignof expression. The remaining fields are resolved
    4545to a name matching the field's name and type using the normal visibility
     
    5656The declarations include the virtual type definition and forward declarations
    5757of the virtual table instance, constructor, message function and
    58 \codeCFA{get_exception_vtable}. The definition includes the storage and
     58@get_exception_vtable@. The definition includes the storage and
    5959initialization of the virtual table instance and the bodies of the three
    6060functions.
     
    6565from the per-instance information. The virtual table type and most of the
    6666functions are polymorphic so they are all part of the core. The virtual table
    67 instance and the \codeCFA{get_exception_vtable} function.
    68 
    69 Coroutines and threads need instances of \codeCFA{CoroutineCancelled} and
    70 \codeCFA{ThreadCancelled} respectively to use all of their functionality.
    71 When a new data type is declared with \codeCFA{coroutine} or \codeCFA{thread}
     67instance and the @get_exception_vtable@ function.
     68
     69Coroutines and threads need instances of @CoroutineCancelled@ and
     70@ThreadCancelled@ respectively to use all of their functionality.
     71When a new data type is declared with @coroutine@ or @thread@
    7272the forward declaration for the instance is created as well. The definition
    7373of the virtual table is created at the definition of the main function.
     
    7979function.
    8080
    81 The function is \codeC{__cfa__virtual_cast} and it is implemented in the
     81The function is @__cfa__virtual_cast@ and it is implemented in the
    8282standard library. It takes a pointer to the target type's virtual table and
    8383the object pointer being cast. The function is very simple, getting the
     
    8787
    8888For the generated code a forward decaration of the virtual works as follows.
    89 There is a forward declaration of \codeC{__cfa__virtual_cast} in every cfa
     89There is a forward declaration of @__cfa__virtual_cast@ in every cfa
    9090file so it can just be used. The object argument is the expression being cast
    9191so that is just placed in the argument list.
     
    110110often across functions.
    111111
    112 At a very basic level this can be done with \codeC{setjmp} \& \codeC{longjmp}
     112At a very basic level this can be done with @setjmp@ \& @longjmp@
    113113which simply move the top of the stack, discarding everything on the stack
    114114above a certain point. However this ignores all the clean-up code that should
     
    118118both of these problems.
    119119
    120 Libunwind, provided in \texttt{unwind.h} on most platorms, is a C library
     120Libunwind, provided in @unwind.h@ on most platorms, is a C library
    121121that provides \CPP style stack unwinding. Its operation is divided into two
    122122phases. The search phase -- phase 1 -- is used to scan the stack and decide
     
    142142
    143143GCC will generate an LSDA and attach its personality function with the
    144 \texttt{-fexceptions} flag. However this only handles the cleanup attribute.
     144@-fexceptions@ flag. However this only handles the cleanup attribute.
    145145This attribute is used on a variable and specifies a function that should be
    146146run when the variable goes out of scope. The function is passed a pointer to
     
    165165messages for special cases (some of which should never be used by the
    166166personality function) and error codes but unless otherwise noted the
    167 personality function should always return \codeC{_URC_CONTINUE_UNWIND}.
    168 
    169 The \codeC{version} argument is the verson of the implementation that is
     167personality function should always return @_URC_CONTINUE_UNWIND@.
     168
     169The @version@ argument is the verson of the implementation that is
    170170calling the personality function. At this point it appears to always be 1 and
    171171it will likely stay that way until a new version of the API is updated.
    172172
    173 The \codeC{action} argument is set of flags that tell the personality
     173The @action@ argument is set of flags that tell the personality
    174174function when it is being called and what it must do on this invocation.
    175175The flags are as follows:
    176176\begin{itemize}
    177 \item\codeC{_UA_SEARCH_PHASE}: This flag is set whenever the personality
     177\item@_UA_SEARCH_PHASE@: This flag is set whenever the personality
    178178function is called during the search phase. The personality function should
    179179decide if unwinding will stop in this function or not. If it does then the
    180 personality function should return \codeC{_URC_HANDLER_FOUND}.
    181 \item\codeC{_UA_CLEANUP_PHASE}: This flag is set whenever the personality
     180personality function should return @_URC_HANDLER_FOUND@.
     181\item@_UA_CLEANUP_PHASE@: This flag is set whenever the personality
    182182function is called during the cleanup phase. If no other flags are set this
    183183means the entire frame will be unwound and all cleanup code should be run.
    184 \item\codeC{_UA_HANDLER_FRAME}: This flag is set during the cleanup phase
     184\item@_UA_HANDLER_FRAME@: This flag is set during the cleanup phase
    185185on the function frame that found the handler. The personality function must
    186186prepare to return to normal code execution and return
    187 \codeC{_URC_INSTALL_CONTEXT}.
    188 \item\codeC{_UA_FORCE_UNWIND}: This flag is set if the personality function
     187@_URC_INSTALL_CONTEXT@.
     188\item@_UA_FORCE_UNWIND@: This flag is set if the personality function
    189189is called through a forced unwind call. Forced unwind only performs the
    190190cleanup phase and uses a different means to decide when to stop. See its
     
    192192\end{itemize}
    193193
    194 The \codeC{exception_class} argument is a copy of the \codeC{exception}'s
    195 \codeC{exception_class} field.
    196 
    197 The \codeC{exception} argument is a pointer to the user provided storage
     194The @exception_class@ argument is a copy of the @exception@'s
     195@exception_class@ field.
     196
     197The @exception@ argument is a pointer to the user provided storage
    198198object. It has two public fields, the exception class which is actually just
    199199a number that identifies the exception handling mechanism that created it and
     
    201201exception needs to
    202202
    203 The \codeC{context} argument is a pointer to an opaque type. This is passed
     203The @context@ argument is a pointer to an opaque type. This is passed
    204204to the many helper functions that can be called inside the personality
    205205function.
     
    218218functions traversing the stack new-to-old until a function finds a handler or
    219219the end of the stack is reached. In the latter case raise exception will
    220 return with \codeC{_URC_END_OF_STACK}.
     220return with @_URC_END_OF_STACK@.
    221221
    222222Once a handler has been found raise exception continues onto the the cleanup
     
    227227
    228228If an error is encountered raise exception will return either
    229 \codeC{_URC_FATAL_PHASE1_ERROR} or \codeC{_URC_FATAL_PHASE2_ERROR} depending
     229@_URC_FATAL_PHASE1_ERROR@ or @_URC_FATAL_PHASE2_ERROR@ depending
    230230on when the error occured.
    231231
     
    259259been unwound.
    260260
    261 Each time it is called the stop function should return \codeC{_URC_NO_REASON}
     261Each time it is called the stop function should return @_URC_NO_REASON@
    262262or transfer control directly to other code outside of libunwind. The
    263263framework does not provide any assistance here.
    264264
    265265Its arguments are the same as the paired personality function.
    266 The actions \codeC{_UA_CLEANUP_PHASE} and \codeC{_UA_FORCE_UNWIND} are always
     266The actions @_UA_CLEANUP_PHASE@ and @_UA_FORCE_UNWIND@ are always
    267267set when it is called. By the official standard that is all but both GCC and
    268268Clang add an extra action on the last call at the end of the stack:
    269 \codeC{_UA_END_OF_STACK}.
     269@_UA_END_OF_STACK@.
    270270
    271271\section{Exception Context}
     
    280280Each stack has its own exception context. In a purely sequental program, using
    281281only core Cforall, there is only one stack and the context is global. However
    282 if the library \texttt{libcfathread} is linked then there can be multiple
     282if the library @libcfathread@ is linked then there can be multiple
    283283stacks so they will each need their own.
    284284
    285285To handle this code always gets the exception context from the function
    286 \codeC{this_exception_context}. The main exception handling code is in
    287 \texttt{libcfa} and that library also defines the function as a weak symbol
    288 so it acts as a default. Meanwhile in \texttt{libcfathread} the function is
     286@this_exception_context@. The main exception handling code is in
     287@libcfa@ and that library also defines the function as a weak symbol
     288so it acts as a default. Meanwhile in @libcfathread@ the function is
    289289defined as a strong symbol that replaces it when the libraries are linked
    290290together.
    291291
    292 The version of the function defined in \texttt{libcfa} is very simple. It
     292The version of the function defined in @libcfa@ is very simple. It
    293293returns a pointer to a global static variable. With only one stack this
    294294global instance is associated with the only stack.
    295295
    296 The version of the function defined in \texttt{libcfathread} has to handle
     296The version of the function defined in @libcfathread@ has to handle
    297297more as there are multiple stacks. The exception context is included as
    298298part of the per-stack data stored as part of coroutines. In the cold data
    299299section, stored at the base of each stack, is the exception context for that
    300 stack. The \codeC{this_exception_context} uses the concurrency library to get
     300stack. The @this_exception_context@ uses the concurrency library to get
    301301the current coroutine and through it the cold data section and the exception
    302302context.
     
    323323to store the exception. Macros with pointer arthritic and type cast are
    324324used to move between the components or go from the embedded
    325 \codeC{_Unwind_Exception} to the entire node.
     325@_Unwind_Exception@ to the entire node.
    326326
    327327All of these nodes are strung together in a linked list. One linked list per
     
    347347C which is what the \CFA compiler outputs so a work-around is used.
    348348
    349 This work around is a function called \codeC{__cfaehm_try_terminate} in the
     349This work around is a function called @__cfaehm_try_terminate@ in the
    350350standard library. The contents of a try block and the termination handlers
    351351are converted into functions. These are then passed to the try terminate
     
    385385
    386386These nested functions and all other functions besides
    387 \codeC{__cfaehm_try_terminate} in \CFA use the GCC personality function and
    388 the \texttt{-fexceptions} flag to generate the LSDA. This allows destructors
     387@__cfaehm_try_terminate@ in \CFA use the GCC personality function and
     388the @-fexceptions@ flag to generate the LSDA. This allows destructors
    389389to be implemented with the cleanup attribute.
    390390
     
    401401
    402402The handler function does both the matching and catching. It tries each
    403 the condition of \codeCFA{catchResume} in order, top-to-bottom and until it
     403the condition of @catchResume@ in order, top-to-bottom and until it
    404404finds a handler that matches. If no handler matches then the function returns
    405405false. Otherwise the matching handler is run, if it completes successfully
    406 the function returns true. Rethrows, through the \codeCFA{throwResume;}
     406the function returns true. Rethrows, through the @throwResume;@
    407407statement, cause the function to return true.
     408
     409% Recursive Resumption Stuff:
     410Blocking out part of the stack is accomplished by updating the front of the
     411list as the search continues. Before the handler at a node is called the head
     412of the list is updated to the next node of the current node. After the search
     413is complete, successful or not, the head of the list is reset.
     414
     415This means the current handler and every handler that has already been
     416checked are not on the list while a handler is run. If a resumption is thrown
     417during the handling of another resumption the active handlers and all the
     418other handler checked up to this point will not be checked again.
     419
     420This structure also supports new handler added while the resumption is being
     421handled. These are added to the front of the list, pointing back along the
     422stack -- the first one will point over all the checked handlers -- and the
     423ordering is maintained.
    408424
    409425\subsection{Libunwind Compatibility}
     
    438454
    439455Cancellation also uses libunwind to do its stack traversal and unwinding,
    440 however it uses a different primary function \codeC{_Unwind_ForcedUnwind}.
     456however it uses a different primary function @_Unwind_ForcedUnwind@.
    441457Details of its interface can be found in the unwind section.
    442458
  • doc/theses/andrew_beach_MMath/unwinding.tex

    r5869cea r7b91c0e  
    1010Even this is fairly simple if nothing needs to happen when the stack unwinds.
    1111Traditional C can unwind the stack by saving and restoring state (with
    12 \codeC{setjmp} \& \codeC{longjmp}). However many languages define actions that
     12@setjmp@ \& @longjmp@). However many languages define actions that
    1313have to be taken when something is removed from the stack, such as running
    14 a variable's destructor or a \codeCFA{try} statement's \codeCFA{finally}
     14a variable's destructor or a @try@ statement's @finally@
    1515clause. Handling this requires walking the stack going through each stack
    1616frame.
     
    2929
    3030\CFA uses two primary functions in libunwind to create most of its
    31 exceptional control-flow: \codeC{_Unwind_RaiseException} and
    32 \codeC{_Unwind_ForcedUnwind}.
     31exceptional control-flow: @_Unwind_RaiseException@ and
     32@_Unwind_ForcedUnwind@.
    3333Their operation is divided into two phases: search and clean-up. The search
    3434phase -- phase 1 -- is used to scan the stack but not unwinding it. The
     
    4444A personality function performs three tasks, although not all have to be
    4545present. The tasks performed are decided by the actions provided.
    46 \codeC{_Unwind_Action} is a bitmask of possible actions and an argument of
     46@_Unwind_Action@ is a bitmask of possible actions and an argument of
    4747this type is passed into the personality function.
    4848\begin{itemize}
    49 \item\codeC{_UA_SEARCH_PHASE} is passed in search phase and tells the
     49\item@_UA_SEARCH_PHASE@ is passed in search phase and tells the
    5050personality function to check for handlers. If there is a handler in this
    5151stack frame, as defined by the language, the personality function should
    52 return \codeC{_URC_HANDLER_FOUND}. Otherwise it should return
    53 \codeC{_URC_CONTINUE_UNWIND}.
    54 \item\codeC{_UA_CLEANUP_PHASE} is passed in during the clean-up phase and
     52return @_URC_HANDLER_FOUND@. Otherwise it should return
     53@_URC_CONTINUE_UNWIND@.
     54\item@_UA_CLEANUP_PHASE@ is passed in during the clean-up phase and
    5555means part or all of the stack frame is removed. The personality function
    5656should do whatever clean-up the language defines
    5757(such as running destructors/finalizers) and then generally returns
    58 \codeC{_URC_CONTINUE_UNWIND}.
    59 \item\codeC{_UA_HANDLER_FRAME} means the personality function must install
     58@_URC_CONTINUE_UNWIND@.
     59\item@_UA_HANDLER_FRAME@ means the personality function must install
    6060a handler. It is also passed in during the clean-up phase and is in addition
    6161to the clean-up action. libunwind provides several helpers for the personality
    6262function here. Once it is done, the personality function must return
    63 \codeC{_URC_INSTALL_CONTEXT}.
     63@_URC_INSTALL_CONTEXT@.
    6464\end{itemize}
    6565The personality function is given a number of other arguments. Some are for
    66 compatability and there is the \codeC{struct _Unwind_Context} pointer which
     66compatability and there is the @struct _Unwind_Context@ pointer which
    6767passed to many helpers to get information about the current stack frame.
    6868
     
    7272raise-exception but with some extras.
    7373The first it passes in an extra action to the personality function on each
    74 stack frame, \codeC{_UA_FORCE_UNWIND}, which means a handler cannot be
     74stack frame, @_UA_FORCE_UNWIND@, which means a handler cannot be
    7575installed.
    7676
     
    8383stack frames have been removed. By the standard API this is marked by setting
    8484the stack pointer inside the context passed to the stop function. However both
    85 GCC and Clang add an extra action for this case \codeC{_UA_END_OF_STACK}.
     85GCC and Clang add an extra action for this case @_UA_END_OF_STACK@.
    8686
    8787Each time function the stop function is called it can do one or two things.
    88 When it is not the end of the stack it can return \codeC{_URC_NO_REASON} to
     88When it is not the end of the stack it can return @_URC_NO_REASON@ to
    8989continue unwinding.
    9090% Is there a reason that NO_REASON is used instead of CONTINUE_UNWIND?
     
    113113
    114114The stop function is very simple. It checks the end of stack flag to see if
    115 it is finished unwinding. If so, it calls \codeC{exit} to end the process,
     115it is finished unwinding. If so, it calls @exit@ to end the process,
    116116otherwise it returns with no-reason to continue unwinding.
    117117% Yeah, this is going to have to change.
     
    128128location of the instruction pointer and stack layout, which varies with
    129129compiler and optimization levels. So for frames where there are only
    130 destructors, GCC's attribute cleanup with the \texttt{-fexception} flag is
     130destructors, GCC's attribute cleanup with the @-fexception@ flag is
    131131sufficient to handle unwinding.
    132132
    133133The only functions that require more than that are those that contain
    134 \codeCFA{try} statements. A \codeCFA{try} statement has a \codeCFA{try}
    135 clause, some number of \codeCFA{catch} clauses and \codeCFA{catchResume}
    136 clauses and may have a \codeCFA{finally} clause. Of these only \codeCFA{try}
    137 statements with \codeCFA{catch} clauses need to be transformed and only they
    138 and the \codeCFA{try} clause are involved.
     134@try@ statements. A @try@ statement has a @try@
     135clause, some number of @catch@ clauses and @catchResume@
     136clauses and may have a @finally@ clause. Of these only @try@
     137statements with @catch@ clauses need to be transformed and only they
     138and the @try@ clause are involved.
    139139
    140 The \codeCFA{try} statement is converted into a series of closures which can
     140The @try@ statement is converted into a series of closures which can
    141141access other parts of the function according to scoping rules but can be
    142 passed around. The \codeCFA{try} clause is converted into the try functions,
    143 almost entirely unchanged. The \codeCFA{catch} clauses are converted into two
     142passed around. The @try@ clause is converted into the try functions,
     143almost entirely unchanged. The @catch@ clauses are converted into two
    144144functions; the match function and the catch function.
    145145
     
    153153runs the handler's body.
    154154
    155 These three functions are passed to \codeC{try_terminate}. This is an
     155These three functions are passed to @try_terminate@. This is an
    156156% Maybe I shouldn't quote that, it isn't its actual name.
    157157internal hand-written function that has its own personality function and
     
    167167handler was found in this frame. If it was then the personality function
    168168installs the handler, which is setting the instruction pointer in
    169 \codeC{try_terminate} to an otherwise unused section that calls the catch
     169@try_terminate@ to an otherwise unused section that calls the catch
    170170function, passing it the current exception and handler index.
    171 \codeC{try_terminate} returns as soon as the catch function returns.
     171@try_terminate@ returns as soon as the catch function returns.
    172172
    173173At this point control has returned to normal control flow.
  • doc/theses/fangren_yu_COOP_F20/Report.tex

    r5869cea r7b91c0e  
    1717\usepackage[usenames]{color}
    1818\input{common}                                          % common CFA document macros
    19 \usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
     19\usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
    2020\usepackage{breakurl}
    2121\urlstyle{sf}
     
    7676\renewcommand{\subsectionmark}[1]{\markboth{\thesubsection\quad #1}{\thesubsection\quad #1}}
    7777\pagenumbering{roman}
    78 \linenumbers                                            % comment out to turn off line numbering
     78%\linenumbers                                            % comment out to turn off line numbering
    7979
    8080\maketitle
    8181\pdfbookmark[1]{Contents}{section}
    82 \tableofcontents
    83 
    84 \clearpage
     82
    8583\thispagestyle{plain}
    8684\pagenumbering{arabic}
    8785
    8886\begin{abstract}
    89 
    90 \CFA is an evolutionary extension to the C programming language, featuring a parametric type system, and is currently under active development. The reference compiler for \CFA language, @cfa-cc@, has some of its major components dated back to early 2000s, and is based on inefficient data structures and algorithms. Some improvements targeting the expression resolution algorithm, suggested by a recent prototype experiment on a simplified model, are implemented in @cfa-cc@ to support the full \CFA language. These optimizations speed up the compiler significantly by a factor of 20 across the existing \CFA codebase, bringing the compilation time of a mid-sized \CFA source file down to 10-second level. A few cases derived from realistic code examples that causes trouble to the compiler are analyzed in detail, with proposed solutions. This step of \CFA project development is critical to its eventual goal to be used alongside C for large software systems.
    91 
     87\CFA is an evolutionary, non-object-oriented extension of the C programming language, featuring a parametric type-system, and is currently under active development. The reference compiler for the \CFA language, @cfa-cc@, has some of its major components dated back to the early 2000s, which are based on inefficient data structures and algorithms. This report introduces improvements targeting the expression resolution algorithm, suggested by a recent prototype experiment on a simplified model, which are implemented in @cfa-cc@ to support the full \CFA language. These optimizations speed up the compiler by a factor of 20 across the existing \CFA codebase, bringing the compilation time of a mid-sized \CFA source file down to the 10-second level. A few problem cases derived from realistic code examples are analyzed in detail, with proposed solutions. This work is a critical step in the \CFA project development to achieve its eventual goal of being used alongside C for large software systems.
    9288\end{abstract}
    9389
     90\clearpage
     91\section*{Acknowledgements}
     92\begin{sloppypar}
     93I would like to thank everyone in the \CFA team for their contribution towards this project. Programming language design and development is a tough subject and requires a lot of teamwork. Without the collaborative efforts from the team, this project could not have been a success. Specifically, I would like to thank Andrew Beach for introducing me to the \CFA codebase, Thierry Delisle for maintaining the test and build automation framework, Michael Brooks for providing example programs of various experimental language and type system features, and most importantly, Professor Martin Karsten for recommending me to the \CFA team, and my supervisor, Professor Peter Buhr for encouraging me to explore deeply into intricate compiler algorithms. Finally, I gratefully acknowledge the help from Aaron Moss, former graduate from the team and the author of the precedent thesis work, to participate in the \CFA team's virtual conferences and email correspondence, and provide many critical arguments and suggestions. 2020 had been an unusually challenging year for everyone and we managed to keep a steady pace.
     94\end{sloppypar}
     95
     96\clearpage
     97\tableofcontents
     98
     99\clearpage
    94100\section{Introduction}
    95101
    96 \CFA language, developed by the Programming Language Group at University of Waterloo, has a long history, with the first proof-of-concept compiler built in 2003 by Richard Bilson~\cite{Bilson03}. Many new features are added to the language over time, but the core of \CFA, parametric functions introduced by the @forall@ clause (hence the name of the language), with the type system supporting parametric overloading, remains mostly unchanged.
    97 
    98 The current \CFA reference compiler @cfa-cc@ still includes many parts taken directly from the original Bilson's implementation, and serves as a starting point for the enhancement work to the type system. Unfortunately, it does not provide the efficiency required for the language to be used practically: a \CFA source file of approximately 1000 lines of code can take a few minutes to compile. The cause of the problem is that the old compiler used inefficient data structures and algorithms for expression resolution, which involved a lot of copying and redundant work.
    99 
    100 This paper presents a series of optimizations to the performance-critical parts of the resolver, with a major rework of the data structure used by the compiler, using a functional programming approach to reduce memory complexity. Subsequent improvements are mostly suggested by running the compiler builds with a performance profiler against the \CFA standard library source code and a test suite to find the most underperforming components in the compiler algorithm.
    101 
    102 The \CFA team endorses a pragmatic philosophy in work that mostly focuses on practical implications of language design and implementation, rather than the theoretical limits. In particular, the compiler is designed to work on production \CFA code efficiently and keep type safety, while sometimes making compromises to expressiveness in extreme corner cases. However, when these corner cases do appear in actual usage, they need to be thoroughly investigated. Analysis presented in this paper, therefore, are conducted on a case-by-case basis. Some of them eventually point to certain weaknesses in the language design and solutions are proposed based on experimental results.
    103 
    104 \section{Completed work}
     102\CFA language, developed by the Programming Language Group at the University of Waterloo, has a long history, with the initial language design in 1992 by Glen Ditchfield~\cite{Ditchfield92} and the first proof-of-concept compiler built in 2003 by Richard Bilson~\cite{Bilson03}. Many new features have been added to the language over time, but the core of \CFA's type-system --- parametric functions introduced by the @forall@ clause (hence the name of the language) providing parametric overloading --- remains mostly unchanged.
     103
     104The current \CFA reference compiler, @cfa-cc@, is designed using the visitor pattern~\cite{vistorpattern} over an abstract syntax tree (AST), where multiple passes over the AST modify it for subsequent passes. @cfa-cc@ still includes many parts taken directly from the original Bilson implementation, which served as the starting point for this enhancement work to the type system. Unfortunately, the prior implementation did not provide the efficiency required for the language to be practical: a \CFA source file of approximately 1000 lines of code can take a multiple minutes to compile. The cause of the problem is that the old compiler used inefficient data structures and algorithms for expression resolution, which involved significant copying and redundant work.
     105
     106This report presents a series of optimizations to the performance-critical parts of the resolver, with a major rework of the compiler data-structures using a functional-programming approach to reduce memory complexity. The improvements were suggested by running the compiler builds with a performance profiler against the \CFA standard-library source-code and a test suite to find the most underperforming components in the compiler algorithm.
     107
     108The \CFA team endorses a pragmatic philosophy that focuses on practical implications of language design and implementation rather than theoretical limits. In particular, the compiler is designed to be expressive with respect to code reuse while maintaining type safety, but compromise theoretical soundness in extreme corner cases. However, when these corner cases do appear in actual usage, they need to be thoroughly investigated. A case-by-case analysis is presented for several of these corner cases, some of which point to certain weaknesses in the language design with solutions proposed based on experimental results.
     109
     110\section{AST restructuring}
    105111
    106112\subsection{Memory model with sharing}
    107113
    108 A major rework of the abstract syntax tree (AST) data structure in the compiler is completed as the first step of the project. The majority of work were documented in the reference manual of the compiler~\cite{cfa-cc}. To summarize:
    109 \begin{itemize}
    110 \item
    111 AST nodes (and therefore subtrees) can be shared without copying when reused.
    112 \item
    113 Modifications apply the functional programming principle, making copies for local changes without affecting the original data shared by other owners. In-place mutations are permitted as a special case when sharing does not happen. The logic is implemented by reference counting.
    114 \item
    115 Memory allocation and freeing are performed automatically using smart pointers.
    116 \end{itemize}
    117 The resolver algorithm designed for overload resolution naturally introduces a significant amount of reused intermediate representations, especially in the following two places:
    118 \begin{itemize}
    119 \item
    120 Function overload candidates are computed by combining the argument candidates bottom-up, with many of them being a common term. For example, if $n$ overloads of a function @f@ all take an integer for the first parameter but different types for the second (@f( int, int )@, @f( int, double )@, etc.) the first term is reused $n$ times for each of the generated candidate expressions. This effect is particularly bad for deep expression trees.
    121 \item
    122 In the unification algorithm and candidate elimination step, actual types are obtained by substituting the type parameters by their bindings. Let $n$ be the complexity (\ie number of nodes in representation) of the original type, $m$ be the complexity of bound type for parameters, and $k$ be the number of occurrences of type parameters in the original type. If everything needs to be deep-copied, the substitution step takes $O(n+mk)$ time and memory, while using shared nodes it is reduced to $O(n)$ time and $O(k)$ memory.
    123 \end{itemize}
    124 One of the worst examples for the old compiler is a long chain of I/O operations
    125 \begin{cfa}
    126 sout | 1 | 2 | 3 | 4 | ...
    127 \end{cfa}
    128 The pipe operator is overloaded by \CFA I/O library for every primitive type in C language, as well as I/O manipulators defined by the library. In total there are around 50 overloads for the output stream operation. On resolving the $n$-th pipe operator in the sequence, the first term, which is the result of sub-expression containing $n-1$ pipe operators, is reused to resolve every overload. Therefore at least $O(n^2)$ copies of expression nodes are made during resolution, not even counting type unification cost; combined with two large factors from number of overloads of pipe operators, and that the ``output stream type'' in \CFA is a trait with 27 assertions (which adds to complexity of the pipe operator's type) this makes compiling a long output sequence extremely slow. In new AST representation only $O(n)$ copies are required and type of pipe operator is not copied at all.
    129 
    130 Reduction in space complexity is especially important, as preliminary profiling result on the old compiler build shows that over half of time spent in expression resolution are on memory allocations.
    131  
     114A major rework of the AST data-structure in the compiler was completed as the first step of the project. The majority of this work is documented in my prior report documenting the compiler reference-manual~\cite{cfa-cc}. To summarize:
     115\begin{itemize}
     116\item
     117AST nodes (and therefore subtrees) can be shared without copying.
     118\item
     119Modifications are performed using functional-programming principles, making copies for local changes without affecting the original data shared by other owners. In-place mutations are permitted as a special case when there is no sharing. The logic is implemented by reference counting.
     120\item
     121Memory allocation and freeing are performed automatically using smart pointers~\cite{smartpointers}.
     122\end{itemize}
     123
     124The resolver algorithm, designed for overload resolution, uses a significant amount of reused, and hence copying, for the intermediate representations, especially in the following two places:
     125\begin{itemize}
     126\item
     127Function overload candidates are computed by combining the argument candidates bottom-up, with many being a common term. For example, if $n$ overloads of a function @f@ all take an integer for the first parameter but different types for the second, \eg @f( int, int )@, @f( int, double )@, etc., the first term is copied $n$ times for each of the generated candidate expressions. This copying is particularly bad for deep expression trees.
     128\item
     129In the unification algorithm and candidate elimination step, actual types are obtained by substituting the type parameters by their bindings. Let $n$ be the complexity (\ie number of nodes in representation) of the original type, $m$ be the complexity of the bound type for parameters, and $k$ be the number of occurrences of type parameters in the original type. If every substitution needs to be deep-copied, these copy step takes $O(n+mk)$ time and memory, while using shared nodes it is reduced to $O(n)$ time and $O(k)$ memory.
     130\end{itemize}
     131One of the worst examples for the old compiler is a long chain of I/O operations:
     132\begin{cfa}
     133sout | 1 | 2 | 3 | 4 | ...;   // print integer constants
     134\end{cfa}
     135The pipe operator is overloaded by the \CFA I/O library for every primitive type in the C language, as well as I/O manipulators defined by the library. In total, there are around 50 overloads for the output stream operation. On resolving the $n$-th pipe operator in the sequence, the first term, which is the result of sub-expression containing $n-1$ pipe operators, is reused to resolve every overload. Therefore at least $O(n^2)$ copies of expression nodes are made during resolution, not even counting type unification cost; combined with the two large factors from number of overloads of pipe operators, and that the ``output stream type'' in \CFA is a trait with 27 assertions (which adds to complexity of the pipe operator's type) this makes compiling a long output sequence extremely slow. In the new AST representation, only $O(n)$ copies are required and the type of the pipe operator is not copied at all.
     136Reduction in space complexity is especially important, as preliminary profiling results on the old compiler build showed over half of the time spent in expression resolution is on memory allocations.
     137
     138Since the compiler codebase is large and the new memory model mostly benefits expression resolution, some of the old data structures are still kept, and a conversion pass happens before and after the general resolve phase. Rewriting every compiler module will take longer, and whether the new model is correct was unknown when this project started, therefore only the resolver is currently implemented with the new data structure.
     139
    132140
    133141\subsection{Merged resolver calls}
    134142
    135 The pre-resolve phase of compilation, inadequately called ``validate'' in the compiler source code, does more than just simple syntax validation, as it also normalizes input program. Some of them, however, requires type information on expressions and therefore needs to call the resolver before the general resolve phase. There are three notable places where the resolver is invoked:
    136 \begin{itemize}
    137 \item
    138 Attempt to generate default constructor, copy constructor and destructor for user-defined @struct@ types
    139 \item
    140 Resolve @with@ statements (the same as in Python, which introduces fields of a structure directly in scope)
     143The pre-resolve phase of compilation, inappropriately called ``validate'' in the compiler source code, has a number of passes that do more than simple syntax and semantic validation; some passes also normalizes the input program. A few of these passes require type information for expressions, and therefore, need to call the resolver before the general resolve phase. There are three notable places where the resolver is invoked:
     144\begin{itemize}
     145\item
     146Generate default constructor, copy constructor and destructor for user-defined @struct@ types.
     147\item
     148Resolve @with@ statements (the same as in Pascal~\cite{pascal}), which introduces fields of a structure directly into a scope.
    141149\item
    142150Resolve @typeof@ expressions (cf. @decltype@ in \CC); note that this step may depend on symbols introduced by @with@ statements.
    143151\end{itemize}
    144 Since the compiler codebase is large and the new memory model mostly only benefits expression resolution, the old data structure is still kept, and a conversion pass happens before and after resolve phase. Rewriting every compiler module will take a long time, and whether the new model is correct is still unknown when started, therefore only the resolver is implemented with the new data structure.
    145 
    146 Since the constructor calls were one of the most expensive to resolve (reason will be shown in the next section), pre-resolve phase were taking more time after resolver moves to the more efficient new implementation. To better facilitate the new resolver, every step that requires type information are reintegrated as part of resolver.
    147 
    148 A by-product of this work is that the reversed dependence of @with@ statement and @typeof@ can now be handled. Previously, the compiler is unable to handle cases such as
     152
     153Since the constructor calls are one of the most expensive to resolve (reason given in~\VRef{s:SpecialFunctionLookup}), this pre-resolve phase was taking a large amount of time even after the resolver was changed to the more efficient new implementation. The problem is that multiple resolutions repeat a significant amount of work. Therefore, to better facilitate the new resolver, every step that requires type information should be integrated as part of the general resolver phase.
     154
     155A by-product of this work is that reversed dependence between @with@ statement and @typeof@ can now be handled. Previously, the compiler was unable to handle cases such as:
    149156\begin{cfa}
    150157struct S { int x; };
    151158S foo();
    152159typeof( foo() ) s; // type is S
    153 with (s) { 
     160with (s) {
    154161        x; // refers to s.x
    155162}
    156163\end{cfa}
    157 since type of @s@ is still unresolved when handling @with@ expressions. Instead, the new (and correct) approach is to evaluate @typeof@ expressions when the declaration is first seen, and it suffices because of the declaration-before-use rule.
     164since the type of @s@ is unresolved when handling @with@ expressions because the @with@ pass follows the @typeof@ pass (interchanging passes only interchanges the problem). Instead, the new (and correct) approach is to evaluate @typeof@ expressions when the declaration is first seen during resolution, and it suffices because of the declaration-before-use rule.
    158165
    159166
    160167\subsection{Special function lookup}
    161 
    162 Reducing the number of functions looked up for overload resolution is an effective way to gain performance when there are many overloads but most of them are trivially wrong. In practice, most functions have few (if any) overloads but there are notable exceptions. Most importantly, constructor @?{}@, destructor @^?{}@, and assignment @?=?@ are generated for every user-defined type, and in a large source file there can be hundreds of them. Furthermore, many calls to them are generated for initializing variables and passing arguments. This fact makes them the most overloaded and most called functions.
    163 
    164 In an object-oriented programming language, object has methods declared with their types, so a call such as @obj.f()@ only needs to perform lookup in the method table corresponding to type of @obj@. \CFA on the other hand, does not have methods, and all types are open (\ie new operations can be defined on them), so a similar approach will not work in general. However, the ``big 3'' operators have a unique property enforced by the language rules, such that the first parameter must have a reference type. Since \CFA does not have class inheritance, reference type must always match exactly. Therefore, argument-dependent lookup can be implemented for these operators, by using a dedicated symbol table.
    165 
    166 The lookup key used for the special functions is the mangled type name of the first parameter, which acts as the @this@ parameter in an object-oriented language. To handle generic types, the type parameters are stripped off, and only the base type is matched. Note that a constructor (destructor, assignment operator) taking arbitrary @this@ argument, for example @forall( dtype T ) void ?{}( T & );@ is not allowed, and it guarantees that if the @this@ type is known, all possible overloads can be found by searching with the given type. In case that the @this@ argument itself is overloaded, it is resolved first and all possible result types are used for lookup.
    167 
    168 Note that for the generated expressions, the particular variable for @this@ argument is fully known, without overloads, so the majority of constructor call resolutions only need to check for one given object type. Explicit constructor calls and assignment statements sometimes may require lookup for multiple types. In the extremely rare case that type of @this@ argument is yet unbound, everything will have to be checked, just like without the argument-dependent lookup algorithm; fortunately, this case almost never happens in practice. An example is found in the library function @new@:
     168\label{s:SpecialFunctionLookup}
     169
     170Reducing the number of function looked ups for overload resolution is an effective way to gain performance when there are many overloads but most of them are trivially wrong. In practice, most functions have few (if any) overloads but there are notable exceptions. Most importantly, constructor @?{}@, destructor @^?{}@, and assignment @?=?@ are generated for every user-defined type (@struct@ and @union@ in C), and in a large source file there can be hundreds of them. Furthermore, many calls are generated for initializing variables, passing arguments and copying values. This fact makes them the most overloaded and most called functions.
     171
     172In an object-oriented programming language, the object-method types are scoped within a class, so a call such as @obj.f()@ only needs to perform lookup in the method table corresponding to the type of @obj@. \CFA on the other hand, does not have methods, and all types are open, \ie new operations can be defined on them without inheritance; at best a \CFA type can be constrained by a translation unit. However, the ``big 3'' operators have a unique property enforced by the language rules: the first parameter must be a reference to its associated type, which acts as the @this@ parameter in an object-oriented language. Since \CFA does not have class inheritance, the reference type must always match exactly. Therefore, argument-dependent lookup can be implemented for these operators by using a dedicated, fast symbol-table.
     173
     174The lookup key for the special functions is the mangled type name of the first parameter. To handle generic types, the type parameters are stripped off, and only the base type is matched. Note a constructor (destructor, assignment operator) may not take an arbitrary @this@ argument, \eg @forall( dtype T ) void ?{}( T & )@, thus guaranteeing that if the @this@ type is known, all possible overloads can be found by searching with this given type. In the case where the @this@ argument itself is overloaded, it is resolved first and all possible result types are used for lookup.
     175
     176Note that for a generated expression, the particular variable for the @this@ argument is fully known, without overloads, so the majority of constructor-call resolutions only need to check for one given object type. Explicit constructor calls and assignment statements sometimes require lookup for multiple types. In the extremely rare case that the @this@-argument type is unbound, all necessary types are guaranteed to be checked, as for the previous lookup without the argument-dependent lookup; fortunately, this complex case almost never happens in practice. An example is found in the library function @new@:
    169177\begin{cfa}
    170178forall( dtype T | sized( T ), ttype TT | { void ?{}( T &, TT ); } )
    171179T * new( TT p ) { return &(*malloc()){ p }; }
    172180\end{cfa}
    173 as @malloc@ may return a pointer to any type, depending on context. 
    174 
    175 Interestingly, this particular line of code actually caused another complicated issue, where the unusually massive work of checking every constructor in presence makes the case even worse. Section~\ref{s:TtypeResolutionInfiniteRecursion} presents a detailed analysis for the problem.
    176 
    177 The ``callable'' operator @?()@ (cf. @operator()@ in \CC) could also be included in the special operator list, as it is usually only on user-defined types, and the restriction that first argument must be a reference seems reasonable in this case.
     181as @malloc@ may return a pointer to any type, depending on context.
     182
     183Interestingly, this particular declaration actually causes another complicated issue, making the complex checking of every constructor even worse. \VRef[Section]{s:TtypeResolutionInfiniteRecursion} presents a detailed analysis of this problem.
     184
     185The ``callable'' operator @?()@ (cf. @operator()@ in \CC) can also be included in this special operator list, as it is usually only on user-defined types, and the restriction that the first argument must be a reference seems reasonable in this case.
    178186
    179187
    180188\subsection{Improvement of function type representation}
    181189
    182 Since substituting type parameters with their bound types is one fundamental operation in many parts of resolver algorithm (particularly unification and environment binding), making as few copies of type nodes as possible helps reducing memory complexity. Even with the new memory management model, allocation is still a significant factor of resolver performance. Conceptually, operations on type nodes of AST should be performed in functional programming style, treating the data structure as immutable and only copy when necessary. The in-place mutation is a mere optimization that does not change logic of operations.
    183 The model was broken on function types by an inappropriate design. Function types require some special treatment due to the existence of assertions. In particular, it must be able to distinguish two different kinds of type parameter usage:
     190Since substituting type parameters with their bound types is one fundamental operation in many parts of resolver algorithm (particularly unification and environment binding), making as few copies of type nodes as possible helps reducing memory complexity. Even with the new memory management model, allocation is still a significant factor of resolver performance. Conceptually, operations on type nodes of the AST should be performed in functional-programming style, treating the data structure as immutable and only copying when necessary. The in-place mutation is a mere optimization that does not change the logic for operations.
     191
     192However, the model was broken for function types by an inappropriate design. Function types require special treatment due to the existence of assertions that constrain the types it supports. Specifically, it must be possible to distinguish two different kinds of type parameter usage:
    184193\begin{cfa}
    185194forall( dtype T ) void foo( T * t ) {
    186         forall( dtype U ) void bar( T * t, U * u ) { ... }
    187 }
    188 \end{cfa}
    189 Here, only @U@ is a free parameter in declaration of @bar@, as it appears in the function's own forall clause; while @T@ is not free.
    190 
    191 Moreover, the resolution algorithm also has to distinguish type bindings of multiple calls to the same function, for example with
     195        forall( dtype U ) void bar( @T@ * t, @U@ * u ) { ... }
     196}
     197\end{cfa}
     198Here, only @U@ is a free parameter in the nested declaration of function @bar@, as @T@ must be bound at the call site when resolving @bar@.
     199
     200Moreover, the resolution algorithm also has to distinguish type bindings of multiple calls to the same function, \eg:
    192201\begin{cfa}
    193202forall( dtype T ) int foo( T x );
    194 foo( foo( 1.0 ) );
    195 \end{cfa}
    196 The inner call has binding (T: double) while the outer call has binding (T: int). Therefore a unique representation of free parameters in each expression is required. This was previously done by creating a copy of the parameter declarations inside function type, and fixing references afterwards. However, fixing references is an inherently deep operation that does not work well with functional programming model, as it must be evaluated eagerly on the entire syntax tree representing the function type.
    197 
    198 The revised approach generates a unique ID value for each function call expression instance and represents an occurrence of free parameter type with a pair of generated ID and the original parameter declaration, so that references do not need to be fixed, and a shallow copy of function type is possible.
    199 
    200 Note that after the change, all declaration nodes in syntax tree representation maps one-to-one with the actual declarations in the program, and therefore are guaranteed to be unique. Such property can potentially enable more optimizations, and some related ideas are presented after Section~\ref{s:SharedSub-ExpressionCaseUniqueExpressions}.
     203int i = foo( foo( 1.0 ) );
     204\end{cfa}
     205The inner call has binding (T: double) while the outer call has binding (T: int). Therefore a unique representation for the free parameters is required in each expression. This type binding was previously done by creating a copy of the parameter declarations inside the function type and fixing references afterwards. However, fixing references is an inherently deep operation that does not work well with the functional-programming style, as it forces eager evaluation on the entire syntax tree representing the function type.
     206
     207The revised approach generates a unique ID value for each function call expression instance and represents an occurrence of a free-parameter type with a pair of generated ID and original parameter declaration, so references are unique and a shallow copy of the function type is possible.
     208
     209Note that after the change, all declaration nodes in the syntax-tree representation now map one-to-one with the actual declarations in the program, and therefore are guaranteed to be unique. This property can potentially enable more optimizations, and some related ideas are presented at the end of \VRef{s:SharedSub-ExpressionCaseUniqueExpressions}.
    201210
    202211
    203212\subsection{Improvement of pruning steps}
    204213
    205 A minor improvement for candidate elimination is to skip the step on the function overloads themselves and only perform on results of function application. As function calls are usually by name, the name resolution rule dictates that every function candidate necessarily has a different type; indirect function calls are rare, and when they do appear, they usually will not have many possible interpretations, and those rarely matches exactly in argument type. Since function types have a much more complex representation than data types (with multiple parameters and assertions), checking equality on them also takes longer.
    206 
    207 A brief test of this approach shows that the number of function overloads considered in expression resolution increases by a negligible amount of less than 1 percent, while type comparisons in candidate elimination are cut by more than half. Improvement is consistent over all \CFA source files in the test suite.
     214A minor improvement for candidate elimination is to skip the step on the function overloads and only check the results of function application. As function calls are usually by name (versus pointers to functions), the name resolution rule dictates that every function candidate necessarily has a different type; indirect function calls are rare, and when they do appear, there are even fewer cases with multiple interpretations, and these rarely match exactly in argument type. Since function types have a much more complex representation (with multiple parameters and assertions) than data types, checking equality on them also takes longer.
     215
     216A brief test of this approach shows that the number of function overloads considered in expression resolution increases by an amount of less than 1 percent, while type comparisons in candidate elimination are reduced by more than half. This improvement is consistent over all \CFA source files in the test suite.
    208217
    209218
     
    211220\label{s:SharedSub-ExpressionCaseUniqueExpressions}
    212221
    213 Unique expression denotes an expression that must be evaluated only once, to prevent unwanted side effects. It is currently only a compiler artifact, generated on tuple member expression of the form
     222Unique expression denotes an expression evaluated only once to prevent unwanted side effects. It is currently only a compiler artifact, generated for tuple-member expression of the form:
    214223\begin{cfa}
    215224struct S { int a; int b; };
     
    217226s.[a, b]; // tuple member expression, type is [int, int]
    218227\end{cfa}
    219 If the aggregate expression contains function calls, it cannot be evaluated multiple times:
     228If the aggregate expression is function call, it cannot be evaluated multiple times:
    220229\begin{cfa}
    221230S makeS();
    222 makeS().[a, b]; // this should only make one S
     231makeS().[a, b]; // this should only generate a unique S
    223232\end{cfa}
    224233Before code generation, the above expression is internally represented as
     
    237246\end{cfa}
    238247at code generation, where @_unique_var@ and @_unique_var_evaluated@ are generated variables whose scope covers all appearances of the same expression.
    239 
    240 Note that although the unique expression is only used for tuple expansion now, it is a generally useful construction, and can be seen in other languages, such as Scala's @lazy val@~\cite{Scala}; therefore it could be worthwhile to introduce the unique expression to a broader context in \CFA and even make it directly available to programmers.
    241 
    242 In the compiler's visitor pattern, however, this creates a problem where multiple paths to a logically unique expression exist, so it may be modified more than once and become ill-formed; some specific intervention is required to ensure that unique expressions are only visited once. Furthermore, a unique expression appearing in more than one places will be copied on mutation so its representation is no longer unique. Some hacks are required to keep it in sync, and the methods are different when mutating the unique expression instance itself or its underlying expression.
    243 
    244 Example when mutating the underlying expression (visit-once guard)
     248The conditional check ensures a single call to @makeS()@ even though there are logically multiple calls because of the tuple field expansion.
     249
     250Note that although the unique expression is only used for tuple expansion now, it is a generally useful construction, and is seen in other programming languages, such as Scala's @lazy val@~\cite{Scala}; therefore it may be worthwhile to introduce the unique expression to a broader context in \CFA and even make it directly available to programmers.
     251
     252In the compiler's visitor pattern, however, this creates a problem where multiple paths to a logically unique expression exist, so it may be modified more than once and become ill-formed; some specific intervention is required to ensure unique expressions are only visited once. Furthermore, a unique expression appearing in more than one places is copied on mutation so its representation is no longer unique.
     253
     254Currently, special cases are required to keep everything synchronized, and the methods are different when mutating the unique expression instance itself or its underlying expression:
     255\begin{itemize}
     256\item
     257When mutating the underlying expression (visit-once guard)
    245258\begin{cfa}
    246259void InsertImplicitCalls::previsit( const ast::UniqueExpr * unqExpr ) {
    247         if ( visitedIds.count( unqExpr->id ) ) visit_children = false;
     260        @if ( visitedIds.count( unqExpr->id ) ) visit_children = false;@
    248261        else visitedIds.insert( unqExpr->id );
    249262}
    250263\end{cfa}
    251 Example when mutating the unique instance itself, which actually creates copies
     264\item
     265When mutating the unique instance itself, which actually creates copies
    252266\begin{cfa}
    253267auto mutExpr = mutate( unqExpr ); // internally calls copy when shared
    254 if ( ! unqMap.count( unqExpr->id ) ) {
     268@if ( ! unqMap.count( unqExpr->id ) ) {@
    255269        ...
    256270} else {
     
    259273}
    260274\end{cfa}
    261 Such workaround seems difficult to be fit into a common visitor template. This suggests the memory model may need different kinds of nodes to accurately represent the syntax tree.
    262 
    263 Together with the fact that declaration nodes are always unique, it is possible that AST nodes can be classified by three different types:
    264 \begin{itemize}
    265 \item
    266 \textbf{Strictly unique} with only one owner (declarations);
    267 \item
    268 \textbf{Logically unique} with (possibly) many owners but should not be copied (unique expression example presented here);
    269 \item
    270 \textbf{Shared} by functional programming model, which assume immutable data structure and are copied on mutation.
     275\end{itemize}
     276Such workarounds are difficult to fit into the common visitor pattern, which suggests the memory model may need different kinds of nodes to accurately represent this feature in the AST.
     277
     278Given that declaration nodes are unique, it is possible for AST nodes to be divided into three different types:
     279\begin{itemize}
     280\item
     281\textbf{Singleton} with only one owner (declarations);
     282\item
     283\textbf{No-copy} with multiple owners but cannot be copied (unique expression example presented here);
     284\item
     285\textbf{Copy} by functional-programming style, which assumes immutable data structures that are copied on mutation.
    271286\end{itemize}
    272287The boilerplate code can potentially handle these three cases differently.
     
    275290\section{Analysis of resolver algorithm complexity}
    276291
    277 The focus of this chapter is to identify and analyze some realistic cases that cause resolver algorithm to have an exponential run time. As previous work has shown [3], the overload resolution problem in \CFA has worst-case exponential complexity; however, only few specific patterns can trigger the exponential complexity in practice. Implementing heuristic-based optimization for those selected cases is helpful to alleviate the problem.
     292The focus of this section is to identify and analyze some realistic cases that cause the resolver algorithm to have an exponential runtime. As previous work has shown~\cite[\S~4.2.1]{Moss19}, the overload resolution problem in \CFA has worst-case exponential complexity; however, only few specific patterns can trigger the exponential complexity in practice. Implementing heuristic-based optimization for those selected cases is helpful to alleviate the problem.
    278293
    279294
     
    281296\label{s:UnboundReturnType}
    282297
    283 The interaction of return type overloading and polymorphic functions creates this problem of function calls with unbound return type, and is further complicated by the presence of assertions.
     298The interaction of return-type overloading and polymorphic functions creates function calls with unbounded return-type, and is further complicated by the presence of assertions.
    284299The prime example of a function with unbound return type is the type-safe version of C @malloc@:
    285300\begin{cfa}
    286 // size deduced from type, so no need to provide the size argument
    287 forall( dtype T | sized( T ) ) T * malloc( void );
    288 \end{cfa}
    289 Unbound return type can be problematic in resolver algorithm complexity because a single match of function call with unbound return type may create multiple candidates. In the worst case, consider a function declared to return any @otype@:
     301forall( dtype T | sized( T ) )
     302T * malloc( void ) { return (T *)malloc( sizeof(T) ); } // call C malloc
     303int * i = malloc();  // type deduced from left-hand size $\Rightarrow$ no size argument or return cast
     304\end{cfa}
     305An unbound return-type is problematic in resolver complexity because a single match of a function call with an unbound return type may create multiple candidates. In the worst case, consider a function declared that returns any @otype@ (defined \VPageref{otype}):
    290306\begin{cfa}
    291307forall( otype T ) T anyObj( void );
    292308\end{cfa}
    293 As the resolver attempts to satisfy the otype constraint on @T@, a single call to @anyObj()@ without the result type known creates at least as many candidates as the number of complete types currently in scope; with generic types it becomes even worse, for example, assuming a declaration of generic pair is available at that point:
     309As the resolver attempts to satisfy the otype constraint on @T@, a call to @anyObj()@ in an expression, without the result type known, creates at least as many candidates as the number of complete types currently in scope; with generic types it becomes even worse, \eg assuming a declaration of a generic @pair@ is available at that point:
    294310\begin{cfa}
    295311forall( otype T, otype U ) struct pair { T first; U second; };
    296312\end{cfa}
    297 Then an @anyObj()@ call can result in arbitrarily complex types, such as @pair( pair( int,int ), pair( int,int ) )@, and the depth can grow indefinitely until the specified parameter depth limit, thus creating exponentially many candidates. However, the expected types allowed by parent expressions are practically very few, so most of those interpretations are invalid; if the result type is never bound up to top level, by the semantic rules it is ambiguous if there are more than one valid bindings, and resolution can fail fast. It is therefore reasonable to delay resolving assertions on an unbound parameter in return type; however, with the current cost model, such behavior may further cause irregularities in candidate selection, such that the presence of assertions can change the preferred candidate, even when order of expression costs are supposed to stay the same. Detailed analysis of this issue will be presented later, in the correctness part.
     313Then an @anyObj()@ call can result in arbitrarily complex types, such as @pair( pair( int, int ), pair( int, int ) )@, and the depth can grow indefinitely until a specified parameter-depth limit, thus creating exponentially many candidates. However, the expected types allowed by parent expressions are practically very few, so most of those interpretations are invalid; if the result type is never bound up to the top level, by the semantic rules it is ambiguous if there is more than one valid binding and resolution fails quickly. It is therefore reasonable to delay resolving assertions on an unbound parameter in a return type; however, with the current cost model, such behavior may further cause irregularities in candidate selection, such that the presence of assertions can change the preferred candidate, even when order of expression costs are supposed to stay the same. A detailed analysis of this issue is presented in \VRef{s:AnalysisTypeSystemCorrectness}.
    298314
    299315
     
    301317\label{s:TtypeResolutionInfiniteRecursion}
    302318
    303 @ttype@ (``tuple type'') is a relatively new addition to the language that attempts to provide type-safe variadic argument semantics. Unlike regular @dtype@ parameters, @ttype@ is only valid in function parameter list, and may only appear once as the type of last parameter. At the call site, a @ttype@ parameter is bound to the tuple type of all remaining function call arguments.
     319@ttype@ (``tuple type'') is a relatively new addition to the language that attempts to provide type-safe variadic argument semantics. Unlike regular @dtype@ parameters, @ttype@ is only valid in a function parameter-list, and may only appear once as the last parameter type. At the call site, a @ttype@ parameter is bound to the tuple type of all remaining function-call arguments.
    304320
    305321There are two kinds of idiomatic @ttype@ usage: one is to provide flexible argument forwarding, similar to the variadic template in \CC (\lstinline[language=C++]|template<typename... args>|), as shown below in the implementation of @unique_ptr@
     
    309325        T * data;
    310326};
    311 forall( dtype T | sized( T ), ttype Args | { void ?{}( T &, Args ); })
    312 void ?{}( unique_ptr( T ) & this, Args args ) {
    313         this.data = new( args );
    314 }
    315 \end{cfa}
    316 the other is to implement structural recursion in the first-rest manner:
    317 \begin{cfa}
    318 forall( otype T, ttype Params | { void process( T ); void func( Params ); })
     327forall( dtype T | sized( T ), @ttype Args@ | { void ?{}( T &, Args ); })
     328void ?{}( unique_ptr( T ) & this, Args @args@ ) {
     329        this.data = new( @args@ );  // forward constructor arguments to dynamic allocator
     330}
     331\end{cfa}
     332The other usage is to implement structural recursion in the first-rest pattern:
     333\begin{cfa}
     334forall( otype T, @ttype Params@ | { void process( T ); void func( Params ); })
    319335void func( T arg1, Params p ) {
    320336        process( arg1 );
    321         func( p );
    322 }
    323 \end{cfa}
    324 For the second use case, it is important that the number of parameters in the recursive call go down, since the call site must deduce all assertion candidates, and that is only possible if by just looking at argument types (and not their values), the recursion is known to be completed in a finite number of steps.
    325 
    326 In recent experiments, however, some flaw in the type binding rules can lead to the first kind of @ttype@ use case produce an invalid candidate that the resolver enters an infinite loop.
    327 
    328 This bug was discovered in an attempt to raise assertion recursive depth limit and one of the library program takes exponentially longer time to compile. The cause of the problem is identified to be the following set of functions.
    329 File @memory.cfa@ contains
    330 \begin{cfa}
    331 #include "memory.hfa"
    332 #include "stdlib.hfa"
    333 \end{cfa}
    334 where file @memory.hfa@ contains the @unique_ptr@ declaration above, and two other similar functions with @ttype@ parameter:
    335 \begin{cfa}
    336 forall( dtype T | sized( T ), ttype Args | { void ?{}( T &, Args ); }) {
     337        func( @p@ );  // recursive call until base case of one argument
     338}
     339\end{cfa}
     340For the second use case, it is imperative the number of parameters in the recursive call goes down, since the call site must deduce all assertion candidates, and that is only possible if by observation of the argument types (and not their values), the recursion is known to be completed in a finite number of steps.
     341
     342In recent experiments, however, a flaw in the type-binding rules can lead to the first kind of @ttype@ use case producing an invalid candidate and the resolver enters an infinite loop.
     343This bug was discovered in an attempt to raise the assertion recursive-depth limit and one of the library programs took exponentially longer to compile. The cause of the problem is the following set of functions:
     344\begin{cfa}
     345// unique_ptr  declaration from above
     346
     347forall( dtype T | sized( T ), ttype Args | { void ?{}( T &, Args ); } ) { // distribute forall clause
    337348        void ?{}( counter_data( T ) & this, Args args );
    338349        void ?{}( counter_ptr( T ) & this, Args args );
    339350        void ?{}( unique_ptr( T ) & this, Args args );
    340351}
    341 \end{cfa}
    342 File @stdlib.hfa@ contains
    343 \begin{cfa}
     352
    344353forall( dtype T | sized( T ), ttype TT | { void ?{}( T &, TT ); } )
    345 T * new( TT p ) { return &(*malloc()){ p }; }
    346 \end{cfa}
    347 
    348 In the expression @(*malloc()){p}@, the type of object being constructed is yet unknown, since the return type information is not immediately provided. That caused every constructor to be searched, and while normally a bound @ttype@ cannot be unified with any free parameter, it is possible with another free @ttype@. Therefore in addition to the correct option provided by assertion, 3 wrong options are examined, each of which again requires the same assertion, for an unknown base type T and @ttype@ arguments, and that becomes an infinite loop, until the specified recursion limit and resolution is forced to fail. Moreover, during the recursion steps, number of candidates grows exponentially, since there are always 3 options at each step.
    349 
    350 Unfortunately, @ttype@ to @ttype@ binding is necessary, to allow calling the function provided by assertion indirectly.
    351 \begin{cfa}
    352 forall( dtype T | sized( T ), ttype Args | { void ?{}( T &, Args ); })
    353 void ?{}( unique_ptr( T ) & this, Args args ) { this.data = (T * )new( args ); }
    354 \end{cfa}
    355 Here the constructor assertion is used for the @new( args )@ call.
     354T * new( TT p ) { return @&(*malloc()){ p };@ }
     355\end{cfa}
     356In the expression @(*malloc()){p}@, the type of the object being constructed is unknown, since the return-type information is not immediately available. That causes every constructor to be searched, and while normally a bound @ttype@ cannot be unified with any free parameter, it is possible with another free @ttype@. Therefore, in addition to the correct option provided by the assertion, 3 wrong options are examined, each of which again requires the same assertion, for an unknown base-type @T@ and @ttype@ argument, which becomes an infinite loop until the specified recursion limit and resolution is fails. Moreover, during the recursion steps, the number of candidates grows exponentially, since there are always 3 options at each step.
     357
     358Unfortunately, @ttype@ to @ttype@ binding is necessary, to allow indirectly calling a function provided in an assertion.
     359\begin{cfa}
     360forall( dtype T | sized( T ), ttype Args | { @void ?{}( T &, Args );@ })
     361void ?{}( unique_ptr( T ) & this, Args args ) { this.data = (T *)@new( args )@; } // constructor call
     362\end{cfa}
     363Here the constructor assertion is used by the @new( args )@ call to indirectly call the constructor on the allocated storage.
    356364Therefore, it is hard, perhaps impossible, to solve this problem by tweaking the type binding rules. An assertion caching algorithm can help improve this case by detecting cycles in recursion.
    357365
    358 Meanwhile, without the caching algorithm implemented, some changes in the \CFA source code are enough to eliminate this problem, at least in the current codebase. Note that the issue only happens with an overloaded variadic function, which rarely appears in practice, since the idiomatic use cases are for argument forwarding and self-recursion. The only overloaded @ttype@ function so far discovered in all of \CFA standard library code is the constructor, and by utilizing the argument-dependent lookup process described in Section~\ref{s:UnboundReturnType}, adding a cast before constructor call gets rid of the issue.
    359 \begin{cfa}
    360 T * new( TT p ) { return &(*(T * )malloc()){ p }; }
     366Meanwhile, without a caching algorithm implemented, some changes in the \CFA source code are enough to eliminate this problem, at least in the current codebase. Note that the issue only happens with an overloaded variadic function, which rarely appears in practice, since the idiomatic use cases are for argument forwarding and self-recursion. The only overloaded @ttype@ function so far discovered in all of \CFA standard library is the constructor, and by utilizing the argument-dependent lookup process described in \VRef{s:UnboundReturnType}, adding a cast before the constructor call removes the issue.
     367\begin{cfa}
     368T * new( TT p ) { return &(*@(T * )@malloc()){ p }; }
    361369\end{cfa}
    362370
     
    364372\subsection{Reused assertions in nested generic type}
    365373
    366 The following test of deeply nested dynamic generic type reveals that locally caching reused assertions is necessary, rather than just a resolver optimization, because recomputing assertions can result in bloated generated code size:
     374The following test of deeply nested, dynamic generic type reveals that locally caching reused assertions is necessary, rather than just a resolver optimization, because recomputing assertions can result in bloated generated code size:
    367375\begin{cfa}
    368376struct nil {};
     
    372380int main() {
    373381        #if   N==0
    374         nil x;   
     382        nil @x@;
    375383        #elif N==1
    376         cons( size_t, nil ) x;
     384        cons( size_t, nil ) @x@;
    377385        #elif N==2
    378         cons( size_t, cons( size_t, nil ) ) x;
     386        cons( size_t, cons( size_t, nil ) ) @x@;
    379387        #elif N==3
    380         cons( size_t, cons( size_t, cons( size_t, nil ) ) ) x;
     388        cons( size_t, cons( size_t, cons( size_t, nil ) ) ) @x@;
    381389        // similarly for N=4,5,6
    382390        #endif
    383391}
    384392\end{cfa}
    385 At the declaration of @x@, it is implicitly initialized by generated constructor call, whose signature is given by
     393At the declaration of @x@, it is implicitly initialized by generated constructor call, with signature:
    386394\begin{cfa}
    387395forall( otype L, otype R ) void ?{}( cons( L, R ) & );
    388396\end{cfa}
    389 Note that the @otype@ constraint contains 4 assertions:
     397where the @otype@ constraint contains the 4 assertions:\label{otype}
    390398\begin{cfa}
    391399void ?{}( L & ); // default constructor
     
    394402L & ?=?( L &, L & ); // assignment
    395403\end{cfa}
    396 Now since the right hand side of outermost cons is again a cons, recursive assertions are required. When the compiler cannot cache and reuse already resolved assertions, it becomes a problem, as each of those 4 pending assertions again asks for 4 more assertions one level below. Without any caching, number of resolved assertions grows exponentially, while that is obviously unnecessary since there are only $n+1$ different types involved. Even worse, this causes exponentially many wrapper functions generated later at the codegen step, and results in huge compiled binary.
    397 
    398 \begin{table}[h]
     404
     405\begin{table}[htb]
     406\centering
    399407\caption{Compilation results of nested cons test}
     408\label{t:NestedConsTest}
    400409\begin{tabular}{|r|r|r|}
    401410\hline
     
    413422\end{table}
    414423
    415 As the local functions are implemented by emitting executable code on the stack~\cite{gcc-nested-func}, it eventually means that compiled code also has exponential run time. This problem has evident practical implications, as nested collection types are frequently used in real production code.
    416 
     424Now since the right hand side of outermost cons is again a cons, recursive assertions are required. \VRef[Table]{t:NestedConsTest} shows when the compiler does not cache and reuse already resolved assertions, it becomes a problem, as each of these 4 pending assertions again asks for 4 more assertions one level below. Without caching, the number of resolved assertions grows exponentially, which is unnecessary since there are only $n+1$ different types involved. Even worse, this problem causes exponentially many wrapper functions to be generated at the backend, resulting in a huge binary. As the local functions are implemented by emitting executable code on the stack~\cite{gcc-nested-func}, it means that compiled code also has exponential run time. This problem has practical implications, as nested collection types are frequently used in real production code.
    417425
    418426\section{Analysis of type system correctness}
     427\label{s:AnalysisTypeSystemCorrectness}
    419428
    420429In Moss' thesis~\cite[\S~4.1.2,~p.~45]{Moss19}, the author presents the following example:
     
    433442From the set of candidates whose parameter and argument types have been unified and whose assertions have been satisfied, those whose sub-expression interpretations have the smallest total cost of conversion are selected ... The total cost of conversion for each of these candidates is then calculated based on the implicit conversions and polymorphism involved in adapting the types of the sub-expression interpretations to the formal parameter types.
    434443\end{quote}
    435 With this model, the algorithm picks @g1@ in resolving the @f( g( 42 ) )@ call, which seems to be undesirable.
    436 
    437 There are further evidence that shows the Bilson model is fundamentally incorrect, following the discussion of unbound return type in Section~\ref{s:UnboundReturnType}. By the conversion cost specification, a binding from a polymorphic type parameter to a concrete type incurs a polymorphic cost of 1. It remains unspecified \emph{when} the type parameters should become bound. When the parameterized types appear in the function parameters, they can be deduced from the argument type, and there is no ambiguity. In the unbound return case, however, the binding may happen at any stage in expression resolution, therefore it is impossible to define a unique local conversion cost. Note that type binding happens exactly once per parameter in resolving the entire expression, so the global binding cost is unambiguously 1.
    438 
    439 As per the current compiler implementation, it does have a notable inconsistency in handling such case. For any unbound parameter that does \emph{not} come with an associated assertion, it remains unbound to the parent expression; for those that does however, they are immediately bound in the assertion resolution step, and concrete result types are used in the parent expressions.
    440 
     444With this model, the algorithm picks @g1@ in resolving the @f( g( 42 ) )@ call, which is undesirable.
     445
     446There is further evidence that shows the Bilson model is fundamentally incorrect, following the discussion of unbound return type in \VRef{s:UnboundReturnType}. By the conversion-cost specification, a binding from a polymorphic type-parameter to a concrete type incurs a polymorphic cost of 1. It remains unspecified \emph{when} the type parameters should become bound. When the parameterized types appear in function parameters, they can be deduced from the argument type, and there is no ambiguity. In the unbound return case, however, the binding may happen at any stage in expression resolution, therefore it is impossible to define a unique local conversion cost. Note that type binding happens exactly once per parameter in resolving the entire expression, so the global binding cost is unambiguously 1.
     447
     448In the current compiler implementation, there is a notable inconsistency in handling this case. For any unbound parameter that does \emph{not} come with an associated assertion, it remains unbound to the parent expression; for those that do, however, they are immediately bound in the assertion resolution step, and concrete result types are used in the parent expressions.
    441449Consider the following example:
    442450\begin{cfa}
     
    444452void h( int * );
    445453\end{cfa}
    446 The expression @h( f() )@ eventually has a total cost of 1 from binding (T: int), but in the eager resolution model, the cost of 1 may occur either at call to @f@ or at call to @h@, and with the assertion resolution triggering a binding, the local cost of @f()@ is (0 poly, 0 spec) with no assertions, but (1 poly, -1 spec) with an assertion:
    447 \begin{cfa}
    448 forall( dtype T | { void g( T * ); } ) T * f( void );
     454The expression @h( f() )@ eventually has a total cost of 1 from binding (T: int), but in the eager-resolution model, the cost of 1 may occur either at the call to @f@ or at call to @h@, and with the assertion resolution triggering a binding, the local cost of @f()@ is (0 poly, 0 spec) with no assertions, but (1 poly, -1 spec) with an assertion:
     455\begin{cfa}
     456forall( dtype T | @{ void g( T * ); }@ ) T * f( void );
    449457void g( int * );
    450458void h( int * );
    451459\end{cfa}
    452 and that contradicts the principle that adding assertions should make expression cost lower. Furthermore, the time at which type binding and assertion resolution happens is an implementation detail of the compiler, but not a part of language definition. That means two compliant \CFA compilers, one performing immediate assertion resolution at each step, and one delaying assertion resolution on unbound types, can produce different expression costs and therefore different candidate selection, making the language rule itself partially undefined and therefore unsound. By the above reasoning, the updated cost model using global sum of costs should be accepted as the standard. It also allows the compiler to freely choose when to resolve assertions, as the sum of total costs is independent of that choice; more optimizations regarding assertion resolution can also be implemented.
     460and that contradicts the principle that adding assertions should make expression cost lower. Furthermore, the time at which type binding and assertion resolution happens is an implementation detail of the compiler, not part of the language definition. That means two compliant \CFA compilers, one performing immediate assertion resolution at each step, and one delaying assertion resolution on unbound types, can produce different expression costs and therefore different candidate selection, making the language rule itself partially undefined, and therefore, unsound. By the above reasoning, the updated cost model using global sum of costs should be accepted as the standard. It also allows the compiler to freely choose when to resolve assertions, as the sum of total costs is independent of that choice; more optimizations regarding assertion resolution can also be implemented.
    453461
    454462
    455463\section{Timing results}
    456464
    457 For the timing results presented here, the \CFA compiler is built with gcc 9.3.0, and tested on a server machine running Ubuntu 20.04, 64GB RAM and 32-core 2.2 GHz CPU, results reported by the time command, and using only 8 cores in parallel such that the time is close to the case with 100\% CPU utilization on a single thread.
    458 
    459 On the most recent build, the \CFA standard library (~1.3 MB of source code) compiles in 4 minutes 47 seconds total processor time (single thread equivalent), with the slowest file taking 13 seconds. The test suite (178 test cases, ~2.2MB of source code) completes within 25 minutes total processor time,\footnote{Including a few runtime tests; total time spent in compilation is approximately 21 minutes.} with the slowest file taking 23 seconds. In contrast, the library build on old compiler takes 85 minutes total, 5 minutes for the slowest file. Full test suite takes too long with old compiler build and is therefore not run, but the slowest test cases take approximately 5 minutes. Overall, the most recent build compared to old build in April 2020, before the project started, is consistently faster by a factor of 20.
    460 
    461 Additionally, 6 selected \CFA source files with distinct features from library and test suite are used to test compiler performance after each of the optimizations are implemented. Test files are from the most recent build and run through C preprocessor to eliminate the factor of header file changes. The selected tests are:
    462 \begin{itemize}
    463 \item
    464 @lib/fstream@ (112 KB)\footnote{File sizes are after preprocessing, with no line information (\lstinline|gcc -E -P|).}: implementation of I/O library
     465For the timing results presented here, the \CFA compiler is built with gcc 9.3.0, and tested on a server machine running Ubuntu 20.04, 64GB RAM and 32-core 2.2 GHz CPU.
     466Timing is reported by the @time@ command and an experiment is run using 8 cores, where each core is at 100\% CPU utilization.
     467
     468On the most recent build, the \CFA standard library ($\approx$1.3 MB of source code) compiles in 4 minutes 47 seconds total processor time (single thread equivalent), with the slowest file taking 13 seconds. The test suite (178 test cases, $\approx$2.2MB of source code) completes within 25 minutes total processor time,
     469% PAB: I do not understand this footnote.
     470%\footnote{Including a few runtime tests; total time spent in compilation is approximately 21 minutes.}
     471with the slowest file taking 23 seconds. In contrast, the library build with the old compiler takes 85 minutes total, 5 minutes for the slowest file. The full test-suite takes too long with old compiler build and is therefore not run, but the slowest test cases take approximately 5 minutes. Overall, the most recent build compared to an old build is consistently faster by a factor of 20.
     472
     473Additionally, 6 selected \CFA source files with distinct features from the library and test suite are used to illustrate the compiler performance change after each of the implemented optimizations. Test files are from the most recent build and run through the C preprocessor to expand header file, perform macro expansions, but no line number information (@gcc -E -P@).
     474\VRef[Table]{t:SelectedFileByCompilerBuild} shows the selected tests:
     475\begin{itemize}
     476\item
     477@lib/fstream@ (112 KB)
    465478\item
    466479@lib/mutex@ (166 KB): implementation of concurrency primitive
     
    470483@lib/stdlib@ (64 KB): type-safe wrapper to @void *@-based C standard library functions
    471484\item
    472 @test/ISO2@ (55 KB): application of I/O library
     485@test/io2@ (55 KB): application of I/O library
    473486\item
    474487@test/thread@ (188 KB): application of threading library
    475488\end{itemize}
    476 
    477 The \CFA compiler builds are picked from git commit history that passed the test suite, and implement the optimizations incrementally:
    478 \begin{itemize}
    479 \item
    480 \#0 is the first working build of new AST data structure
     489versus \CFA compiler builds picked from the git commit history that implement the optimizations incrementally:
     490\begin{itemize}
     491\item
     492old resolver
     493\item
     494\#0 is the first working build of the new AST data structure
    481495\item
    482496\#1 implements special symbol table and argument-dependent lookup
    483497\item
    484 \#2 implements late assertion satisfaction
    485 \item
    486 \#3 implements revised function type representation
    487 \item
    488 \#4 skips pruning on expressions with function type (most recent build)
    489 \end{itemize}
    490 The old resolver with no memory sharing and none of the optimizations above is also tested.
    491 \begin{table}
     498\#2 implements late assertion-satisfaction
     499\item
     500\#3 implements revised function-type representation
     501\item
     502\#4 skips pruning on expressions for function types (most recent build)
     503\end{itemize}
     504Reading left to right for a test shows the benefit of each optimization on the cost of compilation.
     505
     506\begin{table}[htb]
     507\centering
    492508\caption{Compile time of selected files by compiler build, in seconds}
     509\label{t:SelectedFileByCompilerBuild}
    493510\begin{tabular}{|l|r|r|r|r|r|r|}
    494511\hline
     
    513530\end{table}
    514531
    515 
    516532\section{Conclusion}
    517533
    518 Over the course of 8 months of active research and development in \CFA type system and compiler algorithm, performance of the reference \CFA compiler, cfa-cc, has been greatly improved, allowing mid-sized \CFA programs to be compiled and built reasonably fast. As there are also ongoing efforts in the team on building a standard library, evaluating the runtime performance, and attempting to incorporate \CFA with existing software written in C, this project is especially meaningful for practical purposes.
    519 
    520 Analysis conducted in the project were based significantly on heuristics and practical evidence, as the theoretical bounds and average cases for the expression resolution problem differ. This approach was difficult at start to follow, with an unacceptably slow compiler, since running the program through debugger and validation tools (\eg @gdb@, @valgrind@) adds another order of magnitude to run time, which was already in minutes. However, near the end of the project, many significant improvements have already been made and new optimizations can be tested immediately. The positive feedback in development cycle benefits the \CFA team as a whole, more than just for the compiler optimizations.
    521 
    522 Some potential issues of the language that may happen frequently in practice have been identified. Due to the time constraint and complex nature of these problems, a handful of them remain unsolved, but some constructive proposals are made. Notably, introducing a local assertion cache in the resolver is a common solution for a few remaining problems, so that should be the focus of work soon.
    523 
    524 The \CFA team are planning on a public alpha release of the language as the compiler performance becomes promising, and other parts of the system, such as a standard library, are also being enhanced. Ideally, the remaining problems should be resolved before release, and the solutions will also be integral to drafting a formal specification.
     534Over the course of 8 months of active research and development of the \CFA type system and compiler algorithms, performance of the reference \CFA compiler, cfa-cc, has been greatly improved. Now, mid-sized \CFA programs are compiled reasonably fast. Currently, there are ongoing efforts by the \CFA team to augment the standard library and evaluate its runtime performance, and incorporate \CFA with existing software written in C; therefore this project is especially meaningful for these practical purposes.
     535
     536Accomplishing this work was difficult. Analysis conducted in the project is based significantly on heuristics and practical evidence, as the theoretical bounds and average cases for the expression resolution problem differ. As well, the slowness of the initial compiler made attempts to understand why and where problems exist extremely difficult because both debugging and validation tools (\eg @gdb@, @valgrind@, @pref@) further slowed down compilation time. However, by the end of the project, I had found and fixed several significant problems and new optimizations are easier to introduce and test. The reduction in the development cycle benefits the \CFA team as a whole.
     537
     538Some potential issues of the language, which happen frequently in practice, have been identified. Due to the time constraint and complex nature of these problems, a handful of them remain unsolved, but some constructive proposals are made. Notably, introducing a local assertion cache in the resolver is a reasonable solution for a few remaining problems, so that should be the focus of future work.
     539
     540The \CFA team are planning on a public alpha release of the language as the compiler performance, given my recent improvements, is now useable. Other parts of the system, such as the standard library, have made significant gains due to the speed up in the development cycle. Ideally, the remaining problems should be resolved before release, and the solutions will also be integral to drafting a formal specification.
    525541
    526542\addcontentsline{toc}{section}{\refname}
  • doc/theses/fangren_yu_COOP_S20/Report.tex

    r5869cea r7b91c0e  
    1717\usepackage[usenames]{color}
    1818\input{common}                                          % common CFA document macros
    19 \usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
     19\usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
    2020\usepackage{breakurl}
    2121\urlstyle{sf}
  • driver/cfa.cc

    r5869cea r7b91c0e  
    1010// Created On       : Tue Aug 20 13:44:49 2002
    1111// Last Modified By : Peter A. Buhr
    12 // Last Modified On : Tue Nov 17 14:27:28 2020
    13 // Update Count     : 440
     12// Last Modified On : Sat Jan 16 07:30:19 2021
     13// Update Count     : 442
    1414//
    1515
     
    499499                args[nargs++] = "-no-integrated-cpp";
    500500                args[nargs++] = "-Wno-deprecated";
     501                args[nargs++] = "-Wno-strict-aliasing";                 // casting from one type to another
    501502                #ifdef HAVE_CAST_FUNCTION_TYPE
    502503                args[nargs++] = "-Wno-cast-function-type";
  • libcfa/prelude/builtins.c

    r5869cea r7b91c0e  
    1818// type that wraps a pointer and a destructor-like function - used in generating implicit destructor calls for struct members in user-defined functions
    1919// Note: needs to occur early, because it is used to generate destructor calls during code generation
    20 forall(dtype T)
     20forall(T &)
    2121struct __Destructor {
    2222        T * object;
     
    2525
    2626// defined destructor in the case that non-generated code wants to use __Destructor
    27 forall(dtype T)
     27forall(T &)
    2828static inline void ^?{}(__Destructor(T) & x) {
    2929        if (x.object && x.dtor) {
     
    3434// easy interface into __Destructor's destructor for easy codegen purposes
    3535extern "C" {
    36         forall(dtype T)
     36        forall(T &)
    3737        static inline void __destroy_Destructor(__Destructor(T) * dtor) {
    3838                ^(*dtor){};
     
    5151void abort( const char fmt[], ... ) __attribute__ (( format(printf, 1, 2), __nothrow__, __leaf__, __noreturn__ ));
    5252
    53 forall(dtype T)
     53forall(T &)
    5454static inline T & identity(T & i) {
    5555        return i;
     
    6464static inline void ^?{}($generator &) {}
    6565
    66 trait is_generator(dtype T) {
     66trait is_generator(T &) {
    6767      void main(T & this);
    6868      $generator * get_generator(T & this);
    6969};
    7070
    71 forall(dtype T | is_generator(T))
     71forall(T & | is_generator(T))
    7272static inline T & resume(T & gen) {
    7373        main(gen);
     
    7878
    7979static inline {
    80         forall( dtype DT | { DT & ?+=?( DT &, one_t ); } )
     80        forall( DT & | { DT & ?+=?( DT &, one_t ); } )
    8181        DT & ++?( DT & x ) { return x += 1; }
    8282
    83         forall( dtype DT | sized(DT) | { void ?{}( DT &, DT ); void ^?{}( DT & ); DT & ?+=?( DT &, one_t ); } )
     83        forall( DT & | sized(DT) | { void ?{}( DT &, DT ); void ^?{}( DT & ); DT & ?+=?( DT &, one_t ); } )
    8484        DT & ?++( DT & x ) { DT tmp = x; x += 1; return tmp; }
    8585
    86         forall( dtype DT | { DT & ?-=?( DT &, one_t ); } )
     86        forall( DT & | { DT & ?-=?( DT &, one_t ); } )
    8787        DT & --?( DT & x ) { return x -= 1; }
    8888
    89         forall( dtype DT | sized(DT) | { void ?{}( DT &, DT ); void ^?{}( DT & ); DT & ?-=?( DT &, one_t ); } )
     89        forall( DT & | sized(DT) | { void ?{}( DT &, DT ); void ^?{}( DT & ); DT & ?-=?( DT &, one_t ); } )
    9090        DT & ?--( DT & x ) { DT tmp = x; x -= 1; return tmp; }
    9191
    92         forall( dtype DT | { int ?!=?( const DT &, zero_t ); } )
     92        forall( DT & | { int ?!=?( const DT &, zero_t ); } )
    9393        int !?( const DT & x ) { return !( x != 0 ); }
    9494} // distribution
    9595
    9696// universal typed pointer constant
    97 static inline forall( dtype DT ) DT * intptr( uintptr_t addr ) { return (DT *)addr; }
     97static inline forall( DT & ) DT * intptr( uintptr_t addr ) { return (DT *)addr; }
    9898static inline forall( ftype FT ) FT * intptr( uintptr_t addr ) { return (FT *)addr; }
    9999
     
    156156#define __CFA_EXP_OVERFLOW__()
    157157
    158 static inline forall( otype OT | { void ?{}( OT & this, one_t ); OT ?*?( OT, OT ); } ) {
     158static inline forall( OT | { void ?{}( OT & this, one_t ); OT ?*?( OT, OT ); } ) {
    159159        OT ?\?( OT ep, unsigned int y ) { __CFA_EXP__(); }
    160160        OT ?\?( OT ep, unsigned long int y ) { __CFA_EXP__(); }
  • libcfa/prelude/prelude-gen.cc

    r5869cea r7b91c0e  
    159159int main() {
    160160        cout << "# 2 \"prelude.cfa\"  // needed for error messages from this file" << endl;
    161         cout << "trait sized(dtype T) {};" << endl;
     161        cout << "trait sized(T &) {};" << endl;
    162162
    163163        cout << "//////////////////////////" << endl;
     
    264264                for (auto cvq : qualifiersPair) {
    265265                        for (auto is_vol : { "        ", "volatile" }) {
    266                                 cout << "forall(dtype DT) void  ?{}(" << cvq.first << type << " * " << is_vol << " &, " << cvq.second << "DT *);" << endl;
     266                                cout << "forall(DT &) void  ?{}(" << cvq.first << type << " * " << is_vol << " &, " << cvq.second << "DT *);" << endl;
    267267                        }
    268268                }
     
    279279        for (auto cvq : qualifiersSingle) {
    280280                for (auto is_vol : { "        ", "volatile" }) {
    281                         cout << "forall(dtype DT) void  ?{}(" << cvq << "  DT" << " * " << is_vol << " &);" << endl;
     281                        cout << "forall(DT &) void  ?{}(" << cvq << "  DT" << " * " << is_vol << " &);" << endl;
    282282                }
    283283                for (auto is_vol : { "        ", "volatile" }) {
    284                         cout << "forall(dtype DT) void ^?{}(" << cvq << "  DT" << " * " << is_vol << " &);" << endl;
     284                        cout << "forall(DT &) void ^?{}(" << cvq << "  DT" << " * " << is_vol << " &);" << endl;
    285285                }
    286286        }
     
    290290                for (auto is_vol : { "        ", "volatile" }) {
    291291                        for (auto cvq : qualifiersSingle) {
    292                                 cout << "forall(dtype DT) void ?{}( " << cvq << type << " * " << is_vol << " &, zero_t);" << endl;
     292                                cout << "forall(DT &) void ?{}( " << cvq << type << " * " << is_vol << " &, zero_t);" << endl;
    293293                        }
    294294                }
     
    317317        for (auto op : pointerOperators) {
    318318                auto forall = [&op]() {
    319                         cout << "forall(dtype DT" << op.sized << ") ";
     319                        cout << "forall(DT &" << op.sized << ") ";
    320320                };
    321321                for (auto type : { "DT"/*, "void"*/ } ) {
     
    408408        for (auto is_vol : { "        ", "volatile" }) {
    409409                for (auto cvq : qualifiersPair) {
    410                                 cout << "forall(dtype DT) " << cvq.first << "void * ?=?( " << cvq.first << "void * " << is_vol << " &, " << cvq.second << "DT *);" << endl;
     410                                cout << "forall(DT &) " << cvq.first << "void * ?=?( " << cvq.first << "void * " << is_vol << " &, " << cvq.second << "DT *);" << endl;
    411411                }
    412412                for (auto cvq : qualifiersSingle) {
    413                         cout << "forall(dtype DT) " << cvq <<   "  DT * ?=?( " << cvq << "  DT * " << is_vol << " &, zero_t);" << endl;
     413                        cout << "forall(DT &) " << cvq <<   "  DT * ?=?( " << cvq << "  DT * " << is_vol << " &, zero_t);" << endl;
    414414                }
    415415        }
  • libcfa/prelude/prelude.old.cf

    r5869cea r7b91c0e  
    2323// ------------------------------------------------------------
    2424
    25 trait sized(dtype T) {};
     25trait sized(T &) {};
    2626
    2727// ------------------------------------------------------------
     
    6868long double _Complex    ?--( long double _Complex & ),          ?--( volatile long double _Complex & );
    6969
    70 forall( dtype T | sized(T) ) T *                         ?++(                T *& );
    71 forall( dtype T | sized(T) ) const T *           ?++( const          T *& );
    72 forall( dtype T | sized(T) ) volatile T *                ?++(       volatile T *& );
    73 forall( dtype T | sized(T) ) const volatile T *  ?++( const volatile T *& );
    74 forall( dtype T | sized(T) ) T *                         ?--(                T *& );
    75 forall( dtype T | sized(T) ) const T *           ?--( const          T *& );
    76 forall( dtype T | sized(T) ) volatile T *                ?--(       volatile T *& );
    77 forall( dtype T | sized(T) ) const volatile T *  ?--( const volatile T *& );
    78 
    79 forall( dtype T | sized(T) ) T &                 ?[?](                T *,          ptrdiff_t );
    80 forall( dtype T | sized(T) ) const T &   ?[?]( const          T *,          ptrdiff_t );
    81 forall( dtype T | sized(T) ) volatile T &        ?[?](       volatile T *,          ptrdiff_t );
    82 forall( dtype T | sized(T) ) const volatile T & ?[?]( const volatile T *,           ptrdiff_t );
    83 forall( dtype T | sized(T) ) T &                 ?[?](          ptrdiff_t,                T * );
    84 forall( dtype T | sized(T) ) const T &   ?[?](          ptrdiff_t, const          T * );
    85 forall( dtype T | sized(T) ) volatile T &        ?[?](          ptrdiff_t,       volatile T * );
    86 forall( dtype T | sized(T) ) const volatile T & ?[?](           ptrdiff_t, const volatile T * );
     70forall( T & | sized(T) ) T *                     ?++(                T *& );
     71forall( T & | sized(T) ) const T *               ?++( const          T *& );
     72forall( T & | sized(T) ) volatile T *            ?++(       volatile T *& );
     73forall( T & | sized(T) ) const volatile T *      ?++( const volatile T *& );
     74forall( T & | sized(T) ) T *                     ?--(                T *& );
     75forall( T & | sized(T) ) const T *               ?--( const          T *& );
     76forall( T & | sized(T) ) volatile T *            ?--(       volatile T *& );
     77forall( T & | sized(T) ) const volatile T *      ?--( const volatile T *& );
     78
     79forall( T & | sized(T) ) T &             ?[?](                T *,          ptrdiff_t );
     80forall( T & | sized(T) ) const T &       ?[?]( const          T *,          ptrdiff_t );
     81forall( T & | sized(T) ) volatile T &    ?[?](       volatile T *,          ptrdiff_t );
     82forall( T & | sized(T) ) const volatile T & ?[?]( const volatile T *,       ptrdiff_t );
     83forall( T & | sized(T) ) T &             ?[?](          ptrdiff_t,                T * );
     84forall( T & | sized(T) ) const T &       ?[?](          ptrdiff_t, const          T * );
     85forall( T & | sized(T) ) volatile T &    ?[?](          ptrdiff_t,       volatile T * );
     86forall( T & | sized(T) ) const volatile T & ?[?](               ptrdiff_t, const volatile T * );
    8787
    8888// ------------------------------------------------------------
     
    107107long double _Complex    ++?( long double _Complex & ),          --?( long double _Complex & );
    108108
    109 forall( dtype T | sized(T) ) T *                         ++?(                T *& );
    110 forall( dtype T | sized(T) ) const T *           ++?( const          T *& );
    111 forall( dtype T | sized(T) ) volatile T *                ++?(       volatile T *& );
    112 forall( dtype T | sized(T) ) const volatile T *  ++?( const volatile T *& );
    113 forall( dtype T | sized(T) ) T *                         --?(                T *& );
    114 forall( dtype T | sized(T) ) const T *           --?( const          T *& );
    115 forall( dtype T | sized(T) ) volatile T *                --?(       volatile T *& );
    116 forall( dtype T | sized(T) ) const volatile T *  --?( const volatile T *& );
    117 
    118 forall( dtype T | sized(T) ) T &                 *?(                 T * );
    119 forall( dtype T | sized(T) ) const T &           *?( const           T * );
    120 forall( dtype T | sized(T) ) volatile T &        *?(       volatile  T * );
    121 forall( dtype T | sized(T) ) const volatile T & *?( const volatile  T * );
     109forall( T & | sized(T) ) T *                     ++?(                T *& );
     110forall( T & | sized(T) ) const T *               ++?( const          T *& );
     111forall( T & | sized(T) ) volatile T *            ++?(       volatile T *& );
     112forall( T & | sized(T) ) const volatile T *      ++?( const volatile T *& );
     113forall( T & | sized(T) ) T *                     --?(                T *& );
     114forall( T & | sized(T) ) const T *               --?( const          T *& );
     115forall( T & | sized(T) ) volatile T *            --?(       volatile T *& );
     116forall( T & | sized(T) ) const volatile T *      --?( const volatile T *& );
     117
     118forall( T & | sized(T) ) T &             *?(                 T * );
     119forall( T & | sized(T) ) const T &               *?( const           T * );
     120forall( T & | sized(T) ) volatile T &    *?(       volatile  T * );
     121forall( T & | sized(T) ) const volatile T & *?( const volatile  T * );
    122122forall( ftype FT ) FT &          *?( FT * );
    123123
     
    142142                !?( float _Complex ),           !?( double _Complex ),          !?( long double _Complex );
    143143
    144 forall( dtype DT ) int !?(                DT * );
    145 forall( dtype DT ) int !?( const          DT * );
    146 forall( dtype DT ) int !?(       volatile DT * );
    147 forall( dtype DT ) int !?( const volatile DT * );
     144forall( DT & ) int !?(                DT * );
     145forall( DT & ) int !?( const          DT * );
     146forall( DT & ) int !?(       volatile DT * );
     147forall( DT & ) int !?( const volatile DT * );
    148148forall( ftype FT ) int !?( FT * );
    149149
     
    191191long double _Complex    ?+?( long double _Complex, long double _Complex ),      ?-?( long double _Complex, long double _Complex );
    192192
    193 forall( dtype T | sized(T) ) T *                ?+?(                T *,          ptrdiff_t );
    194 forall( dtype T | sized(T) ) T *                ?+?(          ptrdiff_t,                T * );
    195 forall( dtype T | sized(T) ) const T *          ?+?( const          T *,          ptrdiff_t );
    196 forall( dtype T | sized(T) ) const T *          ?+?(          ptrdiff_t, const          T * );
    197 forall( dtype T | sized(T) ) volatile T *       ?+?(       volatile T *,          ptrdiff_t );
    198 forall( dtype T | sized(T) ) volatile T *       ?+?(          ptrdiff_t,       volatile T * );
    199 forall( dtype T | sized(T) ) const volatile T * ?+?( const volatile T *,          ptrdiff_t );
    200 forall( dtype T | sized(T) ) const volatile T * ?+?(          ptrdiff_t, const volatile T * );
    201 forall( dtype T | sized(T) ) T *                ?-?(                T *,          ptrdiff_t );
    202 forall( dtype T | sized(T) ) const T *          ?-?( const          T *,          ptrdiff_t );
    203 forall( dtype T | sized(T) ) volatile T *       ?-?(       volatile T *,          ptrdiff_t );
    204 forall( dtype T | sized(T) ) const volatile T * ?-?( const volatile T *,          ptrdiff_t );
    205 forall( dtype T | sized(T) ) ptrdiff_t          ?-?( const volatile T *, const volatile T * );
     193forall( T & | sized(T) ) T *            ?+?(                T *,          ptrdiff_t );
     194forall( T & | sized(T) ) T *            ?+?(          ptrdiff_t,                T * );
     195forall( T & | sized(T) ) const T *              ?+?( const          T *,          ptrdiff_t );
     196forall( T & | sized(T) ) const T *              ?+?(          ptrdiff_t, const          T * );
     197forall( T & | sized(T) ) volatile T *   ?+?(       volatile T *,          ptrdiff_t );
     198forall( T & | sized(T) ) volatile T *   ?+?(          ptrdiff_t,       volatile T * );
     199forall( T & | sized(T) ) const volatile T *     ?+?( const volatile T *,          ptrdiff_t );
     200forall( T & | sized(T) ) const volatile T *     ?+?(          ptrdiff_t, const volatile T * );
     201forall( T & | sized(T) ) T *            ?-?(                T *,          ptrdiff_t );
     202forall( T & | sized(T) ) const T *              ?-?( const          T *,          ptrdiff_t );
     203forall( T & | sized(T) ) volatile T *   ?-?(       volatile T *,          ptrdiff_t );
     204forall( T & | sized(T) ) const volatile T *     ?-?( const volatile T *,          ptrdiff_t );
     205forall( T & | sized(T) ) ptrdiff_t              ?-?( const volatile T *, const volatile T * );
    206206
    207207// ------------------------------------------------------------
     
    255255           ?>?( long double, long double ),                             ?>=?( long double, long double );
    256256
    257 forall( dtype DT ) signed int ?<?(                 DT *,                DT * );
    258 forall( dtype DT ) signed int ?<?(  const          DT *, const          DT * );
    259 forall( dtype DT ) signed int ?<?(        volatile DT *,       volatile DT * );
    260 forall( dtype DT ) signed int ?<?(  const volatile DT *, const volatile DT * );
    261 
    262 forall( dtype DT ) signed int ?>?(                 DT *,                DT * );
    263 forall( dtype DT ) signed int ?>?(  const          DT *, const          DT * );
    264 forall( dtype DT ) signed int ?>?(        volatile DT *,       volatile DT * );
    265 forall( dtype DT ) signed int ?>?(  const volatile DT *, const volatile DT * );
    266 
    267 forall( dtype DT ) signed int ?<=?(                 DT *,                DT * );
    268 forall( dtype DT ) signed int ?<=?(  const          DT *, const          DT * );
    269 forall( dtype DT ) signed int ?<=?(        volatile DT *,       volatile DT * );
    270 forall( dtype DT ) signed int ?<=?( const volatile DT *, const volatile DT * );
    271 
    272 forall( dtype DT ) signed int ?>=?(                 DT *,                DT * );
    273 forall( dtype DT ) signed int ?>=?(  const          DT *, const          DT * );
    274 forall( dtype DT ) signed int ?>=?(        volatile DT *,       volatile DT * );
    275 forall( dtype DT ) signed int ?>=?( const volatile DT *, const volatile DT * );
     257forall( DT & ) signed int ?<?(                 DT *,                DT * );
     258forall( DT & ) signed int ?<?(  const          DT *, const          DT * );
     259forall( DT & ) signed int ?<?(        volatile DT *,       volatile DT * );
     260forall( DT & ) signed int ?<?(  const volatile DT *, const volatile DT * );
     261
     262forall( DT & ) signed int ?>?(                 DT *,                DT * );
     263forall( DT & ) signed int ?>?(  const          DT *, const          DT * );
     264forall( DT & ) signed int ?>?(        volatile DT *,       volatile DT * );
     265forall( DT & ) signed int ?>?(  const volatile DT *, const volatile DT * );
     266
     267forall( DT & ) signed int ?<=?(                 DT *,                DT * );
     268forall( DT & ) signed int ?<=?(  const          DT *, const          DT * );
     269forall( DT & ) signed int ?<=?(        volatile DT *,       volatile DT * );
     270forall( DT & ) signed int ?<=?( const volatile DT *, const volatile DT * );
     271
     272forall( DT & ) signed int ?>=?(                 DT *,                DT * );
     273forall( DT & ) signed int ?>=?(  const          DT *, const          DT * );
     274forall( DT & ) signed int ?>=?(        volatile DT *,       volatile DT * );
     275forall( DT & ) signed int ?>=?( const volatile DT *, const volatile DT * );
    276276
    277277// ------------------------------------------------------------
     
    302302signed int ?==?( one_t, one_t ),                                                        ?!=?( one_t, one_t );
    303303
    304 forall( dtype DT ) signed int ?==?(                DT *,                DT * );
    305 forall( dtype DT ) signed int ?==?( const          DT *, const          DT * );
    306 forall( dtype DT ) signed int ?==?(       volatile DT *,       volatile DT * );
    307 forall( dtype DT ) signed int ?==?( const volatile DT *, const volatile DT * );
     304forall( DT & ) signed int ?==?(            DT *,                DT * );
     305forall( DT & ) signed int ?==?( const      DT *, const          DT * );
     306forall( DT & ) signed int ?==?(       volatile DT *,       volatile DT * );
     307forall( DT & ) signed int ?==?( const volatile DT *, const volatile DT * );
    308308forall( ftype FT ) signed int ?==?( FT *, FT * );
    309 forall( dtype DT ) signed int ?!=?(                DT *,                DT * );
    310 forall( dtype DT ) signed int ?!=?( const          DT *, const          DT * );
    311 forall( dtype DT ) signed int ?!=?(       volatile DT *,       volatile DT * );
    312 forall( dtype DT ) signed int ?!=?( const volatile DT *, const volatile DT * );
     309forall( DT & ) signed int ?!=?(            DT *,                DT * );
     310forall( DT & ) signed int ?!=?( const      DT *, const          DT * );
     311forall( DT & ) signed int ?!=?(       volatile DT *,       volatile DT * );
     312forall( DT & ) signed int ?!=?( const volatile DT *, const volatile DT * );
    313313forall( ftype FT ) signed int ?!=?( FT *, FT * );
    314314
     
    376376
    377377forall( ftype FT ) FT *                 ?=?( FT *&, FT * );
    378 forall( ftype FT ) FT *                 ?=?( FT * volatile &, FT * );
    379 
    380 forall( dtype DT ) DT *                 ?=?(                 DT *          &,                   DT * );
    381 forall( dtype DT ) DT *                 ?=?(                 DT * volatile &,                   DT * );
    382 forall( dtype DT ) const DT *           ?=?( const           DT *          &,                   DT * );
    383 forall( dtype DT ) const DT *           ?=?( const           DT * volatile &,                   DT * );
    384 forall( dtype DT ) const DT *           ?=?( const           DT *          &, const             DT * );
    385 forall( dtype DT ) const DT *           ?=?( const           DT * volatile &, const             DT * );
    386 forall( dtype DT ) volatile DT *        ?=?(       volatile  DT *          &,                   DT * );
    387 forall( dtype DT ) volatile DT *        ?=?(       volatile  DT * volatile &,                   DT * );
    388 forall( dtype DT ) volatile DT *        ?=?(       volatile  DT *          &,       volatile    DT * );
    389 forall( dtype DT ) volatile DT *        ?=?(       volatile  DT * volatile &,       volatile    DT * );
    390 
    391 forall( dtype DT ) const volatile DT *  ?=?( const volatile  DT *          &,                   DT * );
    392 forall( dtype DT ) const volatile DT *  ?=?( const volatile  DT * volatile &,                   DT * );
    393 forall( dtype DT ) const volatile DT *  ?=?( const volatile  DT *          &, const             DT * );
    394 forall( dtype DT ) const volatile DT *  ?=?( const volatile  DT * volatile &, const             DT * );
    395 forall( dtype DT ) const volatile DT *  ?=?( const volatile  DT *          &,       volatile    DT * );
    396 forall( dtype DT ) const volatile DT *  ?=?( const volatile  DT * volatile &,       volatile    DT * );
    397 forall( dtype DT ) const volatile DT *  ?=?( const volatile  DT *          &, const volatile    DT * );
    398 forall( dtype DT ) const volatile DT *  ?=?( const volatile  DT * volatile &, const volatile    DT * );
    399 
    400 forall( dtype DT ) void *                ?=?(                void *          &,                 DT * );
    401 forall( dtype DT ) void *                ?=?(                void * volatile &,                 DT * );
    402 forall( dtype DT ) const void *          ?=?( const          void *          &,                 DT * );
    403 forall( dtype DT ) const void *          ?=?( const          void * volatile &,                 DT * );
    404 forall( dtype DT ) const void *          ?=?( const          void *          &, const           DT * );
    405 forall( dtype DT ) const void *          ?=?( const          void * volatile &, const           DT * );
    406 forall( dtype DT ) volatile void *       ?=?(       volatile void *          &,                 DT * );
    407 forall( dtype DT ) volatile void *       ?=?(       volatile void * volatile &,                 DT * );
    408 forall( dtype DT ) volatile void *       ?=?(       volatile void *          &,       volatile  DT * );
    409 forall( dtype DT ) volatile void *       ?=?(       volatile void * volatile &,       volatile  DT * );
    410 forall( dtype DT ) const volatile void * ?=?( const volatile void *          &,                 DT * );
    411 forall( dtype DT ) const volatile void * ?=?( const volatile void * volatile &,                 DT * );
    412 forall( dtype DT ) const volatile void * ?=?( const volatile void *          &, const           DT * );
    413 forall( dtype DT ) const volatile void * ?=?( const volatile void * volatile &, const           DT * );
    414 forall( dtype DT ) const volatile void * ?=?( const volatile void *          &,       volatile  DT * );
    415 forall( dtype DT ) const volatile void * ?=?( const volatile void * volatile &,       volatile  DT * );
    416 forall( dtype DT ) const volatile void * ?=?( const volatile void *          &, const volatile  DT * );
    417 forall( dtype DT ) const volatile void * ?=?( const volatile void * volatile &, const volatile  DT * );
     378forall( ftyep FT ) FT *                 ?=?( FT * volatile &, FT * );
     379
     380forall( DT & ) DT *                     ?=?(                 DT *          &,                   DT * );
     381forall( DT & ) DT *                     ?=?(                 DT * volatile &,                   DT * );
     382forall( DT & ) const DT *               ?=?( const           DT *          &,                   DT * );
     383forall( DT & ) const DT *               ?=?( const           DT * volatile &,                   DT * );
     384forall( DT & ) const DT *               ?=?( const           DT *          &, const             DT * );
     385forall( DT & ) const DT *               ?=?( const           DT * volatile &, const             DT * );
     386forall( DT & ) volatile DT *    ?=?(       volatile  DT *          &,                   DT * );
     387forall( DT & ) volatile DT *    ?=?(       volatile  DT * volatile &,                   DT * );
     388forall( DT & ) volatile DT *    ?=?(       volatile  DT *          &,       volatile    DT * );
     389forall( DT & ) volatile DT *    ?=?(       volatile  DT * volatile &,       volatile    DT * );
     390
     391forall( DT & ) const volatile DT *      ?=?( const volatile  DT *          &,                   DT * );
     392forall( DT & ) const volatile DT *  ?=?( const volatile  DT * volatile &,                       DT * );
     393forall( DT & ) const volatile DT *  ?=?( const volatile  DT *      &, const             DT * );
     394forall( DT & ) const volatile DT *  ?=?( const volatile  DT * volatile &, const         DT * );
     395forall( DT & ) const volatile DT *  ?=?( const volatile  DT *      &,       volatile    DT * );
     396forall( DT & ) const volatile DT *  ?=?( const volatile  DT * volatile &,           volatile    DT * );
     397forall( DT & ) const volatile DT *  ?=?( const volatile  DT *      &, const volatile    DT * );
     398forall( DT & ) const volatile DT *  ?=?( const volatile  DT * volatile &, const volatile        DT * );
     399
     400forall( DT & ) void *            ?=?(                void *          &,                 DT * );
     401forall( DT & ) void *            ?=?(                void * volatile &,                 DT * );
     402forall( DT & ) const void *              ?=?( const          void *          &,                 DT * );
     403forall( DT & ) const void *              ?=?( const          void * volatile &,                 DT * );
     404forall( DT & ) const void *              ?=?( const          void *          &, const           DT * );
     405forall( DT & ) const void *              ?=?( const          void * volatile &, const           DT * );
     406forall( DT & ) volatile void *   ?=?(       volatile void *          &,                 DT * );
     407forall( DT & ) volatile void *   ?=?(       volatile void * volatile &,                 DT * );
     408forall( DT & ) volatile void *   ?=?(       volatile void *          &,       volatile  DT * );
     409forall( DT & ) volatile void *   ?=?(       volatile void * volatile &,       volatile  DT * );
     410forall( DT & ) const volatile void * ?=?( const volatile void *      &,                 DT * );
     411forall( DT & ) const volatile void * ?=?( const volatile void * volatile &,                     DT * );
     412forall( DT & ) const volatile void * ?=?( const volatile void *      &, const           DT * );
     413forall( DT & ) const volatile void * ?=?( const volatile void * volatile &, const               DT * );
     414forall( DT & ) const volatile void * ?=?( const volatile void *      &,       volatile  DT * );
     415forall( DT & ) const volatile void * ?=?( const volatile void * volatile &,           volatile  DT * );
     416forall( DT & ) const volatile void * ?=?( const volatile void *      &, const volatile  DT * );
     417forall( DT & ) const volatile void * ?=?( const volatile void * volatile &, const volatile      DT * );
    418418
    419419//forall( dtype DT ) DT *                       ?=?(                DT *          &, zero_t );
    420420//forall( dtype DT ) DT *                       ?=?(                DT * volatile &, zero_t );
    421 forall( dtype DT ) const DT *           ?=?( const          DT *          &, zero_t );
    422 forall( dtype DT ) const DT *           ?=?( const          DT * volatile &, zero_t );
     421forall( DT & ) const DT *               ?=?( const          DT *          &, zero_t );
     422forall( DT & ) const DT *               ?=?( const          DT * volatile &, zero_t );
    423423//forall( dtype DT ) volatile DT *      ?=?( volatile       DT *          &, zero_t );
    424424//forall( dtype DT ) volatile DT *      ?=?( volatile       DT * volatile &, zero_t );
    425 forall( dtype DT ) const volatile DT *  ?=?( const volatile DT *          &, zero_t );
    426 forall( dtype DT ) const volatile DT *  ?=?( const volatile DT * volatile &, zero_t );
     425forall( DT & ) const volatile DT *      ?=?( const volatile DT *          &, zero_t );
     426forall( DT & ) const volatile DT *      ?=?( const volatile DT * volatile &, zero_t );
    427427
    428428forall( ftype FT ) FT *                 ?=?( FT *          &, zero_t );
    429429forall( ftype FT ) FT *                 ?=?( FT * volatile &, zero_t );
    430430
    431 forall( dtype T | sized(T) ) T *                ?+=?(                T *          &, ptrdiff_t );
    432 forall( dtype T | sized(T) ) T *                ?+=?(                T * volatile &, ptrdiff_t );
    433 forall( dtype T | sized(T) ) const T *          ?+=?( const          T *          &, ptrdiff_t );
    434 forall( dtype T | sized(T) ) const T *          ?+=?( const          T * volatile &, ptrdiff_t );
    435 forall( dtype T | sized(T) ) volatile T *       ?+=?(       volatile T *          &, ptrdiff_t );
    436 forall( dtype T | sized(T) ) volatile T *       ?+=?(       volatile T * volatile &, ptrdiff_t );
    437 forall( dtype T | sized(T) ) const volatile T * ?+=?( const volatile T *          &, ptrdiff_t );
    438 forall( dtype T | sized(T) ) const volatile T * ?+=?( const volatile T * volatile &, ptrdiff_t );
    439 forall( dtype T | sized(T) ) T *                ?-=?(                T *          &, ptrdiff_t );
    440 forall( dtype T | sized(T) ) T *                ?-=?(                T * volatile &, ptrdiff_t );
    441 forall( dtype T | sized(T) ) const T *          ?-=?( const          T *          &, ptrdiff_t );
    442 forall( dtype T | sized(T) ) const T *          ?-=?( const          T * volatile &, ptrdiff_t );
    443 forall( dtype T | sized(T) ) volatile T *       ?-=?(       volatile T *          &, ptrdiff_t );
    444 forall( dtype T | sized(T) ) volatile T *       ?-=?(       volatile T * volatile &, ptrdiff_t );
    445 forall( dtype T | sized(T) ) const volatile T * ?-=?( const volatile T *          &, ptrdiff_t );
    446 forall( dtype T | sized(T) ) const volatile T * ?-=?( const volatile T * volatile &, ptrdiff_t );
     431forall( T & | sized(T) ) T *            ?+=?(                T *          &, ptrdiff_t );
     432forall( T & | sized(T) ) T *            ?+=?(                T * volatile &, ptrdiff_t );
     433forall( T & | sized(T) ) const T *              ?+=?( const          T *          &, ptrdiff_t );
     434forall( T & | sized(T) ) const T *              ?+=?( const          T * volatile &, ptrdiff_t );
     435forall( T & | sized(T) ) volatile T *   ?+=?(       volatile T *          &, ptrdiff_t );
     436forall( T & | sized(T) ) volatile T *   ?+=?(       volatile T * volatile &, ptrdiff_t );
     437forall( T & | sized(T) ) const volatile T *     ?+=?( const volatile T *          &, ptrdiff_t );
     438forall( T & | sized(T) ) const volatile T *     ?+=?( const volatile T * volatile &, ptrdiff_t );
     439forall( T & | sized(T) ) T *            ?-=?(                T *          &, ptrdiff_t );
     440forall( T & | sized(T) ) T *            ?-=?(                T * volatile &, ptrdiff_t );
     441forall( T & | sized(T) ) const T *              ?-=?( const          T *          &, ptrdiff_t );
     442forall( T & | sized(T) ) const T *              ?-=?( const          T * volatile &, ptrdiff_t );
     443forall( T & | sized(T) ) volatile T *   ?-=?(       volatile T *          &, ptrdiff_t );
     444forall( T & | sized(T) ) volatile T *   ?-=?(       volatile T * volatile &, ptrdiff_t );
     445forall( T & | sized(T) ) const volatile T *     ?-=?( const volatile T *          &, ptrdiff_t );
     446forall( T & | sized(T) ) const volatile T *     ?-=?( const volatile T * volatile &, ptrdiff_t );
    447447
    448448_Bool                   ?=?( _Bool &, _Bool ),                                  ?=?( volatile _Bool &, _Bool );
     
    723723forall( ftype FT ) void ?{}( FT * volatile &, FT * );
    724724
    725 forall( dtype DT ) void ?{}(                 DT *          &,                   DT * );
    726 forall( dtype DT ) void ?{}( const           DT *          &,                   DT * );
    727 forall( dtype DT ) void ?{}( const           DT *          &, const             DT * );
    728 forall( dtype DT ) void ?{}(       volatile  DT *          &,                   DT * );
    729 forall( dtype DT ) void ?{}(       volatile  DT *          &,       volatile    DT * );
    730 forall( dtype DT ) void ?{}( const volatile  DT *          &,                   DT * );
    731 forall( dtype DT ) void ?{}( const volatile  DT *          &, const             DT * );
    732 forall( dtype DT ) void ?{}( const volatile  DT *          &,       volatile    DT * );
    733 forall( dtype DT ) void ?{}( const volatile  DT *          &, const volatile    DT * );
    734 
    735 forall( dtype DT ) void ?{}(                 void *          &,                 DT * );
    736 forall( dtype DT ) void ?{}( const           void *          &,                 DT * );
    737 forall( dtype DT ) void ?{}( const           void *          &, const           DT * );
    738 forall( dtype DT ) void ?{}(        volatile void *          &,                 DT * );
    739 forall( dtype DT ) void ?{}(        volatile void *          &,       volatile  DT * );
    740 forall( dtype DT ) void ?{}( const volatile void *           &,                 DT * );
    741 forall( dtype DT ) void ?{}( const volatile void *           &, const           DT * );
    742 forall( dtype DT ) void ?{}( const volatile void *           &,       volatile  DT * );
    743 forall( dtype DT ) void ?{}( const volatile void *           &, const volatile  DT * );
     725forall( DT & ) void ?{}(                     DT *          &,                   DT * );
     726forall( DT & ) void ?{}( const       DT *          &,                   DT * );
     727forall( DT & ) void ?{}( const       DT *          &, const             DT * );
     728forall( DT & ) void ?{}(           volatile  DT *          &,                   DT * );
     729forall( DT & ) void ?{}(           volatile  DT *          &,       volatile    DT * );
     730forall( DT & ) void ?{}( const volatile  DT *      &,                   DT * );
     731forall( DT & ) void ?{}( const volatile  DT *      &, const             DT * );
     732forall( DT & ) void ?{}( const volatile  DT *      &,       volatile    DT * );
     733forall( DT & ) void ?{}( const volatile  DT *      &, const volatile    DT * );
     734
     735forall( DT & ) void ?{}(                     void *          &,                 DT * );
     736forall( DT & ) void ?{}( const       void *          &,                 DT * );
     737forall( DT & ) void ?{}( const       void *          &, const           DT * );
     738forall( DT & ) void ?{}(            volatile void *          &,                 DT * );
     739forall( DT & ) void ?{}(            volatile void *          &,       volatile  DT * );
     740forall( DT & ) void ?{}( const volatile void *       &,                 DT * );
     741forall( DT & ) void ?{}( const volatile void *       &, const           DT * );
     742forall( DT & ) void ?{}( const volatile void *       &,       volatile  DT * );
     743forall( DT & ) void ?{}( const volatile void *       &, const volatile  DT * );
    744744
    745745//forall( dtype DT ) void ?{}(              DT *          &, zero_t );
    746746//forall( dtype DT ) void ?{}(              DT * volatile &, zero_t );
    747 forall( dtype DT ) void ?{}( const          DT *          &, zero_t );
     747forall( DT & ) void ?{}( const      DT *          &, zero_t );
    748748//forall( dtype DT ) void ?{}( volatile     DT *          &, zero_t );
    749749//forall( dtype DT ) void ?{}( volatile     DT * volatile &, zero_t );
    750 forall( dtype DT ) void ?{}( const volatile DT *          &, zero_t );
     750forall( DT & ) void ?{}( const volatile DT *      &, zero_t );
    751751
    752752forall( ftype FT ) void ?{}( FT *          &, zero_t );
     
    755755forall( ftype FT ) void ?{}( FT *          & );
    756756
    757 forall( dtype DT ) void ?{}(                 DT *          &);
    758 forall( dtype DT ) void ?{}( const           DT *          &);
    759 forall( dtype DT ) void ?{}(       volatile  DT *          &);
    760 forall( dtype DT ) void ?{}( const volatile  DT *          &);
     757forall( DT & ) void     ?{}(                 DT *          &);
     758forall( DT & ) void     ?{}( const           DT *          &);
     759forall( DT & ) void     ?{}(       volatile  DT *          &);
     760forall( DT & ) void ?{}( const volatile  DT *      &);
    761761
    762762void    ?{}(                void *          &);
     
    768768forall( ftype FT ) void ^?{}( FT *         & );
    769769
    770 forall( dtype DT ) void ^?{}(                DT *          &);
    771 forall( dtype DT ) void ^?{}( const          DT *          &);
    772 forall( dtype DT ) void ^?{}(      volatile  DT *          &);
    773 forall( dtype DT ) void ^?{}( const volatile  DT *         &);
     770forall( DT & ) void     ^?{}(                DT *          &);
     771forall( DT & ) void     ^?{}( const          DT *          &);
     772forall( DT & ) void     ^?{}(      volatile  DT *          &);
     773forall( DT & ) void ^?{}( const volatile  DT *     &);
    774774
    775775void ^?{}(                  void *          &);
  • libcfa/prelude/sync-builtins.cf

    r5869cea r7b91c0e  
    206206_Bool __sync_bool_compare_and_swap(volatile unsigned __int128 *, unsigned __int128, unsigned __int128,...);
    207207#endif
    208 forall(dtype T) _Bool __sync_bool_compare_and_swap(T * volatile *, T *, T*, ...);
     208forall(T &) _Bool __sync_bool_compare_and_swap(T * volatile *, T *, T*, ...);
    209209
    210210char __sync_val_compare_and_swap(volatile char *, char, char,...);
     
    223223unsigned __int128 __sync_val_compare_and_swap(volatile unsigned __int128 *, unsigned __int128, unsigned __int128,...);
    224224#endif
    225 forall(dtype T) T * __sync_val_compare_and_swap(T * volatile *, T *, T*,...);
     225forall(T &) T * __sync_val_compare_and_swap(T * volatile *, T *, T*,...);
    226226
    227227char __sync_lock_test_and_set(volatile char *, char,...);
     
    326326void __atomic_exchange(volatile unsigned __int128 *, volatile unsigned __int128 *, volatile unsigned __int128 *, int);
    327327#endif
    328 forall(dtype T) T * __atomic_exchange_n(T * volatile *, T *, int);
    329 forall(dtype T) void __atomic_exchange(T * volatile *, T * volatile *, T * volatile *, int);
     328forall(T &) T * __atomic_exchange_n(T * volatile *, T *, int);
     329forall(T &) void __atomic_exchange(T * volatile *, T * volatile *, T * volatile *, int);
    330330
    331331_Bool __atomic_load_n(const volatile _Bool *, int);
     
    359359void __atomic_load(const volatile unsigned __int128 *, volatile unsigned __int128 *, int);
    360360#endif
    361 forall(dtype T) T * __atomic_load_n(T * const volatile *, int);
    362 forall(dtype T) void __atomic_load(T * const volatile *, T **, int);
     361forall(T &) T * __atomic_load_n(T * const volatile *, int);
     362forall(T &) void __atomic_load(T * const volatile *, T **, int);
    363363
    364364_Bool __atomic_compare_exchange_n(volatile char *, char *, char, _Bool, int, int);
     
    390390_Bool __atomic_compare_exchange   (volatile unsigned __int128 *, unsigned __int128 *, unsigned __int128 *, _Bool, int, int);
    391391#endif
    392 forall(dtype T) _Bool __atomic_compare_exchange_n (T * volatile *, T **, T*, _Bool, int, int);
    393 forall(dtype T) _Bool __atomic_compare_exchange   (T * volatile *, T **, T**, _Bool, int, int);
     392forall(T &) _Bool __atomic_compare_exchange_n (T * volatile *, T **, T*, _Bool, int, int);
     393forall(T &) _Bool __atomic_compare_exchange   (T * volatile *, T **, T**, _Bool, int, int);
    394394
    395395void __atomic_store_n(volatile _Bool *, _Bool, int);
     
    423423void __atomic_store(volatile unsigned __int128 *, unsigned __int128 *, int);
    424424#endif
    425 forall(dtype T) void __atomic_store_n(T * volatile *, T *, int);
    426 forall(dtype T) void __atomic_store(T * volatile *, T **, int);
     425forall(T &) void __atomic_store_n(T * volatile *, T *, int);
     426forall(T &) void __atomic_store(T * volatile *, T **, int);
    427427
    428428char __atomic_add_fetch  (volatile char *, char, int);
  • libcfa/src/bitmanip.hfa

    r5869cea r7b91c0e  
    100100        unsigned long long int floor2( unsigned long long int n, unsigned long long int align ) { verify( is_pow2( align ) ); return n & -align; }
    101101
    102         // forall( otype T | { T ?&?( T, T ); T -?( T ); } )
     102        // forall( T | { T ?&?( T, T ); T -?( T ); } )
    103103        // T floor2( T n, T align ) { verify( is_pow2( align ) ); return n & -align; }
    104104
     
    115115        unsigned long long int ceiling2( unsigned long long int n, unsigned long long int align ) { verify( is_pow2( align ) ); return -floor2( -n, align ); }
    116116
    117         // forall( otype T | { T floor2( T, T ); T -?( T ); } )
     117        // forall( T | { T floor2( T, T ); T -?( T ); } )
    118118        // T ceiling2( T n, T align ) { verify( is_pow2( align ) ); return -floor2( -n, align ); }
    119119} // distribution
  • libcfa/src/bits/algorithm.hfa

    r5869cea r7b91c0e  
    1717
    1818#ifdef SAFE_SORT
    19 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort2( T * arr );
    20 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort3( T * arr );
    21 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort4( T * arr );
    22 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort5( T * arr );
    23 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort6( T * arr );
    24 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sortN( T * arr, size_t dim );
     19forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort2( T * arr );
     20forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort3( T * arr );
     21forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort4( T * arr );
     22forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort5( T * arr );
     23forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sort6( T * arr );
     24forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } ) static inline void __libcfa_small_sortN( T * arr, size_t dim );
    2525
    26 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } )
     26forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } )
    2727static inline void __libcfa_small_sort( T * arr, size_t dim ) {
    2828        switch( dim ) {
     
    4141#define SWAP(x,y) { T a = min(arr[x], arr[y]); T b = max(arr[x], arr[y]); arr[x] = a; arr[y] = b;}
    4242
    43 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } )
     43forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } )
    4444static inline void __libcfa_small_sort2( T * arr ) {
    4545        SWAP(0, 1);
    4646}
    4747
    48 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } )
     48forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } )
    4949static inline void __libcfa_small_sort3( T * arr ) {
    5050        SWAP(1, 2);
     
    5353}
    5454
    55 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } )
     55forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } )
    5656static inline void __libcfa_small_sort4( T * arr ) {
    5757        SWAP(0, 1);
     
    6262}
    6363
    64 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } )
     64forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } )
    6565static inline void __libcfa_small_sort5( T * arr ) {
    6666        SWAP(0, 1);
     
    7575}
    7676
    77 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } )
     77forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } )
    7878static inline void __libcfa_small_sort6( T * arr ) {
    7979        SWAP(1, 2);
     
    9191}
    9292
    93 forall( otype T | {  int ?<?( T, T ); int ?>?( T, T ); } )
     93forall( T | {  int ?<?( T, T ); int ?>?( T, T ); } )
    9494static inline void __libcfa_small_sortN( T * arr, size_t dim ) {
    9595        int i, j;
     
    112112static inline void __libcfa_small_sortN( void* * arr, size_t dim );
    113113
    114 forall( dtype T )
     114forall( T & )
    115115static inline void __libcfa_small_sort( T* * arr, size_t dim ) {
    116116        switch( dim ) {
  • libcfa/src/bits/collection.hfa

    r5869cea r7b91c0e  
    3131
    3232        // // wrappers to make Collection have T
    33         // forall( dtype T ) {
     33        // forall( T & ) {
    3434        //      T *& Next( T * n ) {
    3535        //              return (T *)Next( (Colable *)n );
     
    3838} // distribution
    3939
    40 forall( dtype T | { T *& Next ( T * ); } ) {
     40static inline forall( T & | { T *& Next ( T * ); } ) {
    4141        bool listed( T * n ) {
    4242                return Next( n ) != 0p;
     
    7676        } // post: elts = null
    7777
    78         forall( dtype T ) {
     78        forall( T & ) {
    7979                T * Curr( ColIter & ci ) with( ci ) {
    8080                        return (T *)curr;
  • libcfa/src/bits/containers.hfa

    r5869cea r7b91c0e  
    2323
    2424#ifdef __cforall
    25         forall(dtype T)
     25        forall(T &)
    2626#else
    2727        #define T void
     
    4040
    4141#ifdef __cforall
    42         // forall(otype T | sized(T))
     42        // forall(T | sized(T))
    4343        // static inline void ?{}(__small_array(T) & this) {}
    4444
    45         forall(dtype T | sized(T))
     45        forall(T & | sized(T))
    4646        static inline T & ?[?]( __small_array(T) & this, __lock_size_t idx ) {
    4747                return ((typeof(this.data))this.data)[idx];
    4848        }
    4949
    50         forall(dtype T | sized(T))
     50        forall(T & | sized(T))
    5151        static inline T & ?[?]( const __small_array(T) & this, __lock_size_t idx ) {
    5252                return ((typeof(this.data))this.data)[idx];
    5353        }
    5454
    55         forall(dtype T)
     55        forall(T &)
    5656        static inline T * begin( const __small_array(T) & this ) {
    5757                return ((typeof(this.data))this.data);
    5858        }
    5959
    60         forall(dtype T | sized(T))
     60        forall(T & | sized(T))
    6161        static inline T * end( const __small_array(T) & this ) {
    6262                return ((typeof(this.data))this.data) + this.size;
     
    6969
    7070#ifdef __cforall
    71         trait is_node(dtype T) {
     71        trait is_node(T &) {
    7272                T *& get_next( T & );
    7373        };
     
    7878//-----------------------------------------------------------------------------
    7979#ifdef __cforall
    80         forall(dtype TYPE)
     80        forall(TYPE &)
    8181        #define T TYPE
    8282#else
     
    9595
    9696#ifdef __cforall
    97         forall(dtype T)
     97        forall(T &)
    9898        static inline void ?{}( __stack(T) & this ) {
    9999                (this.top){ 0p };
    100100        }
    101101
    102         static inline forall( dtype T | is_node(T) ) {
     102        static inline forall( T & | is_node(T) ) {
    103103                void push( __stack(T) & this, T * val ) {
    104104                        verify( !get_next( *val ) );
     
    126126//-----------------------------------------------------------------------------
    127127#ifdef __cforall
    128         forall(dtype TYPE)
     128        forall(TYPE &)
    129129        #define T TYPE
    130130#else
     
    144144
    145145#ifdef __cforall
    146         static inline forall( dtype T | is_node(T) ) {
     146        static inline forall( T & | is_node(T) ) {
    147147                void ?{}( __queue(T) & this ) with( this ) {
    148148                        (this.head){ 1p };
     
    215215//-----------------------------------------------------------------------------
    216216#ifdef __cforall
    217         forall(dtype TYPE)
     217        forall(TYPE &)
    218218        #define T TYPE
    219219        #define __getter_t * [T * & next, T * & prev] ( T & )
     
    237237
    238238#ifdef __cforall
    239         forall(dtype T )
     239        forall(T & )
    240240        static inline [void] ?{}( __dllist(T) & this, * [T * & next, T * & prev] ( T & ) __get ) {
    241241                (this.head){ 0p };
     
    245245        #define next 0
    246246        #define prev 1
    247         static inline forall(dtype T) {
     247        static inline forall(T &) {
    248248                void push_front( __dllist(T) & this, T & node ) with( this ) {
    249249                        verify(__get);
  • libcfa/src/bits/defs.hfa

    r5869cea r7b91c0e  
    55// file "LICENCE" distributed with Cforall.
    66//
    7 // defs.hfa --
     7// defs.hfa -- Commen macros, functions and typedefs
     8// Most files depend on them and they are always useful to have.
     9//
     10//  *** Must not contain code specific to libcfathread ***
    811//
    912// Author           : Thierry Delisle
     
    6265        #endif
    6366}
     67
     68// pause to prevent excess processor bus usage
     69#if defined( __i386 ) || defined( __x86_64 )
     70        #define Pause() __asm__ __volatile__ ( "pause" : : : )
     71#elif defined( __ARM_ARCH )
     72        #define Pause() __asm__ __volatile__ ( "YIELD" : : : )
     73#else
     74        #error unsupported architecture
     75#endif
  • libcfa/src/bits/locks.hfa

    r5869cea r7b91c0e  
    55// file "LICENCE" distributed with Cforall.
    66//
    7 // bits/locks.hfa -- Fast internal locks.
     7// bits/locks.hfa -- Basic spinlocks that are reused in the system.
     8// Used for locks that aren't specific to cforall threads and can be used anywhere
     9//
     10//  *** Must not contain code specific to libcfathread ***
    811//
    912// Author           : Thierry Delisle
     
    1922#include "bits/defs.hfa"
    2023#include <assert.h>
    21 
    22 #ifdef __cforall
    23         extern "C" {
    24                 #include <pthread.h>
    25         }
    26 #endif
    27 
    28 // pause to prevent excess processor bus usage
    29 #if defined( __i386 ) || defined( __x86_64 )
    30         #define Pause() __asm__ __volatile__ ( "pause" : : : )
    31 #elif defined( __ARM_ARCH )
    32         #define Pause() __asm__ __volatile__ ( "YIELD" : : : )
    33 #else
    34         #error unsupported architecture
    35 #endif
    3624
    3725struct __spinlock_t {
     
    10492                enable_interrupts_noPoll();
    10593        }
    106 
    107 
    108         #ifdef __CFA_WITH_VERIFY__
    109                 extern bool __cfaabi_dbg_in_kernel();
    110         #endif
    111 
    112         extern "C" {
    113                 char * strerror(int);
    114         }
    115         #define CHECKED(x) { int err = x; if( err != 0 ) abort("KERNEL ERROR: Operation \"" #x "\" return error %d - %s\n", err, strerror(err)); }
    116 
    117         struct __bin_sem_t {
    118                 pthread_mutex_t         lock;
    119                 pthread_cond_t          cond;
    120                 int                     val;
    121         };
    122 
    123         static inline void ?{}(__bin_sem_t & this) with( this ) {
    124                 // Create the mutex with error checking
    125                 pthread_mutexattr_t mattr;
    126                 pthread_mutexattr_init( &mattr );
    127                 pthread_mutexattr_settype( &mattr, PTHREAD_MUTEX_ERRORCHECK_NP);
    128                 pthread_mutex_init(&lock, &mattr);
    129 
    130                 pthread_cond_init (&cond, (const pthread_condattr_t *)0p);  // workaround trac#208: cast should not be required
    131                 val = 0;
    132         }
    133 
    134         static inline void ^?{}(__bin_sem_t & this) with( this ) {
    135                 CHECKED( pthread_mutex_destroy(&lock) );
    136                 CHECKED( pthread_cond_destroy (&cond) );
    137         }
    138 
    139         static inline void wait(__bin_sem_t & this) with( this ) {
    140                 verify(__cfaabi_dbg_in_kernel());
    141                 CHECKED( pthread_mutex_lock(&lock) );
    142                         while(val < 1) {
    143                                 pthread_cond_wait(&cond, &lock);
    144                         }
    145                         val -= 1;
    146                 CHECKED( pthread_mutex_unlock(&lock) );
    147         }
    148 
    149         static inline bool post(__bin_sem_t & this) with( this ) {
    150                 bool needs_signal = false;
    151 
    152                 CHECKED( pthread_mutex_lock(&lock) );
    153                         if(val < 1) {
    154                                 val += 1;
    155                                 pthread_cond_signal(&cond);
    156                                 needs_signal = true;
    157                         }
    158                 CHECKED( pthread_mutex_unlock(&lock) );
    159 
    160                 return needs_signal;
    161         }
    162 
    163         #undef CHECKED
    164 
    165         struct $thread;
    166         extern void park( void );
    167         extern void unpark( struct $thread * this );
    168         static inline struct $thread * active_thread ();
    169 
    170         // Semaphore which only supports a single thread
    171         struct single_sem {
    172                 struct $thread * volatile ptr;
    173         };
    174 
    175         static inline {
    176                 void  ?{}(single_sem & this) {
    177                         this.ptr = 0p;
    178                 }
    179 
    180                 void ^?{}(single_sem &) {}
    181 
    182                 bool wait(single_sem & this) {
    183                         for() {
    184                                 struct $thread * expected = this.ptr;
    185                                 if(expected == 1p) {
    186                                         if(__atomic_compare_exchange_n(&this.ptr, &expected, 0p, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    187                                                 return false;
    188                                         }
    189                                 }
    190                                 else {
    191                                         /* paranoid */ verify( expected == 0p );
    192                                         if(__atomic_compare_exchange_n(&this.ptr, &expected, active_thread(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    193                                                 park();
    194                                                 return true;
    195                                         }
    196                                 }
    197 
    198                         }
    199                 }
    200 
    201                 bool post(single_sem & this) {
    202                         for() {
    203                                 struct $thread * expected = this.ptr;
    204                                 if(expected == 1p) return false;
    205                                 if(expected == 0p) {
    206                                         if(__atomic_compare_exchange_n(&this.ptr, &expected, 1p, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    207                                                 return false;
    208                                         }
    209                                 }
    210                                 else {
    211                                         if(__atomic_compare_exchange_n(&this.ptr, &expected, 0p, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    212                                                 unpark( expected );
    213                                                 return true;
    214                                         }
    215                                 }
    216                         }
    217                 }
    218         }
    219 
    220         // Synchronozation primitive which only supports a single thread and one post
    221         // Similar to a binary semaphore with a 'one shot' semantic
    222         // is expected to be discarded after each party call their side
    223         struct oneshot {
    224                 // Internal state :
    225                 //     0p     : is initial state (wait will block)
    226                 //     1p     : fulfilled (wait won't block)
    227                 // any thread : a thread is currently waiting
    228                 struct $thread * volatile ptr;
    229         };
    230 
    231         static inline {
    232                 void  ?{}(oneshot & this) {
    233                         this.ptr = 0p;
    234                 }
    235 
    236                 void ^?{}(oneshot &) {}
    237 
    238                 // Wait for the post, return immidiately if it already happened.
    239                 // return true if the thread was parked
    240                 bool wait(oneshot & this) {
    241                         for() {
    242                                 struct $thread * expected = this.ptr;
    243                                 if(expected == 1p) return false;
    244                                 /* paranoid */ verify( expected == 0p );
    245                                 if(__atomic_compare_exchange_n(&this.ptr, &expected, active_thread(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    246                                         park();
    247                                         /* paranoid */ verify( this.ptr == 1p );
    248                                         return true;
    249                                 }
    250                         }
    251                 }
    252 
    253                 // Mark as fulfilled, wake thread if needed
    254                 // return true if a thread was unparked
    255                 bool post(oneshot & this) {
    256                         struct $thread * got = __atomic_exchange_n( &this.ptr, 1p, __ATOMIC_SEQ_CST);
    257                         if( got == 0p ) return false;
    258                         unpark( got );
    259                         return true;
    260                 }
    261         }
    262 
    263         // base types for future to build upon
    264         // It is based on the 'oneshot' type to allow multiple futures
    265         // to block on the same instance, permitting users to block a single
    266         // thread on "any of" [a given set of] futures.
    267         // does not support multiple threads waiting on the same future
    268         struct future_t {
    269                 // Internal state :
    270                 //     0p      : is initial state (wait will block)
    271                 //     1p      : fulfilled (wait won't block)
    272                 //     2p      : in progress ()
    273                 //     3p      : abandoned, server should delete
    274                 // any oneshot : a context has been setup to wait, a thread could wait on it
    275                 struct oneshot * volatile ptr;
    276         };
    277 
    278         static inline {
    279                 void  ?{}(future_t & this) {
    280                         this.ptr = 0p;
    281                 }
    282 
    283                 void ^?{}(future_t &) {}
    284 
    285                 void reset(future_t & this) {
    286                         // needs to be in 0p or 1p
    287                         __atomic_exchange_n( &this.ptr, 0p, __ATOMIC_SEQ_CST);
    288                 }
    289 
    290                 // check if the future is available
    291                 bool available( future_t & this ) {
    292                         return this.ptr == 1p;
    293                 }
    294 
    295                 // Prepare the future to be waited on
    296                 // intented to be use by wait, wait_any, waitfor, etc. rather than used directly
    297                 bool setup( future_t & this, oneshot & wait_ctx ) {
    298                         /* paranoid */ verify( wait_ctx.ptr == 0p );
    299                         // The future needs to set the wait context
    300                         for() {
    301                                 struct oneshot * expected = this.ptr;
    302                                 // Is the future already fulfilled?
    303                                 if(expected == 1p) return false; // Yes, just return false (didn't block)
    304 
    305                                 // The future is not fulfilled, try to setup the wait context
    306                                 /* paranoid */ verify( expected == 0p );
    307                                 if(__atomic_compare_exchange_n(&this.ptr, &expected, &wait_ctx, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    308                                         return true;
    309                                 }
    310                         }
    311                 }
    312 
    313                 // Stop waiting on a future
    314                 // When multiple futures are waited for together in "any of" pattern
    315                 // futures that weren't fulfilled before the thread woke up
    316                 // should retract the wait ctx
    317                 // intented to be use by wait, wait_any, waitfor, etc. rather than used directly
    318                 void retract( future_t & this, oneshot & wait_ctx ) {
    319                         // Remove the wait context
    320                         struct oneshot * got = __atomic_exchange_n( &this.ptr, 0p, __ATOMIC_SEQ_CST);
    321 
    322                         // got == 0p: future was never actually setup, just return
    323                         if( got == 0p ) return;
    324 
    325                         // got == wait_ctx: since fulfil does an atomic_swap,
    326                         // if we got back the original then no one else saw context
    327                         // It is safe to delete (which could happen after the return)
    328                         if( got == &wait_ctx ) return;
    329 
    330                         // got == 1p: the future is ready and the context was fully consumed
    331                         // the server won't use the pointer again
    332                         // It is safe to delete (which could happen after the return)
    333                         if( got == 1p ) return;
    334 
    335                         // got == 2p: the future is ready but the context hasn't fully been consumed
    336                         // spin until it is safe to move on
    337                         if( got == 2p ) {
    338                                 while( this.ptr != 1p ) Pause();
    339                                 return;
    340                         }
    341 
    342                         // got == any thing else, something wen't wrong here, abort
    343                         abort("Future in unexpected state");
    344                 }
    345 
    346                 // Mark the future as abandoned, meaning it will be deleted by the server
    347                 bool abandon( future_t & this ) {
    348                         /* paranoid */ verify( this.ptr != 3p );
    349 
    350                         // Mark the future as abandonned
    351                         struct oneshot * got = __atomic_exchange_n( &this.ptr, 3p, __ATOMIC_SEQ_CST);
    352 
    353                         // If the future isn't already fulfilled, let the server delete it
    354                         if( got == 0p ) return false;
    355 
    356                         // got == 2p: the future is ready but the context hasn't fully been consumed
    357                         // spin until it is safe to move on
    358                         if( got == 2p ) {
    359                                 while( this.ptr != 1p ) Pause();
    360                                 got = 1p;
    361                         }
    362 
    363                         // The future is completed delete it now
    364                         /* paranoid */ verify( this.ptr != 1p );
    365                         free( &this );
    366                         return true;
    367                 }
    368 
    369                 // from the server side, mark the future as fulfilled
    370                 // delete it if needed
    371                 bool fulfil( future_t & this ) {
    372                         for() {
    373                                 struct oneshot * expected = this.ptr;
    374                                 // was this abandoned?
    375                                 #if defined(__GNUC__) && __GNUC__ >= 7
    376                                         #pragma GCC diagnostic push
    377                                         #pragma GCC diagnostic ignored "-Wfree-nonheap-object"
    378                                 #endif
    379                                         if( expected == 3p ) { free( &this ); return false; }
    380                                 #if defined(__GNUC__) && __GNUC__ >= 7
    381                                         #pragma GCC diagnostic pop
    382                                 #endif
    383 
    384                                 /* paranoid */ verify( expected != 1p ); // Future is already fulfilled, should not happen
    385                                 /* paranoid */ verify( expected != 2p ); // Future is bein fulfilled by someone else, this is even less supported then the previous case.
    386 
    387                                 // If there is a wait context, we need to consume it and mark it as consumed after
    388                                 // If there is no context then we can skip the in progress phase
    389                                 struct oneshot * want = expected == 0p ? 1p : 2p;
    390                                 if(__atomic_compare_exchange_n(&this.ptr, &expected, want, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
    391                                         if( expected == 0p ) { /* paranoid */ verify( this.ptr == 1p); return false; }
    392                                         bool ret = post( *expected );
    393                                         __atomic_store_n( &this.ptr, 1p, __ATOMIC_SEQ_CST);
    394                                         return ret;
    395                                 }
    396                         }
    397 
    398                 }
    399 
    400                 // Wait for the future to be fulfilled
    401                 bool wait( future_t & this ) {
    402                         oneshot temp;
    403                         if( !setup(this, temp) ) return false;
    404 
    405                         // Wait context is setup, just wait on it
    406                         bool ret = wait( temp );
    407 
    408                         // Wait for the future to tru
    409                         while( this.ptr == 2p ) Pause();
    410                         // Make sure the state makes sense
    411                         // Should be fulfilled, could be in progress but it's out of date if so
    412                         // since if that is the case, the oneshot was fulfilled (unparking this thread)
    413                         // and the oneshot should not be needed any more
    414                         __attribute__((unused)) struct oneshot * was = this.ptr;
    415                         /* paranoid */ verifyf( was == 1p, "Expected this.ptr to be 1p, was %p\n", was );
    416 
    417                         // Mark the future as fulfilled, to be consistent
    418                         // with potential calls to avail
    419                         // this.ptr = 1p;
    420                         return ret;
    421                 }
    422         }
    42394#endif
  • libcfa/src/bits/queue.hfa

    r5869cea r7b91c0e  
    99// instead of being null.
    1010
    11 forall( dtype T | { T *& Next ( T * ); } ) {
     11forall( T & | { T *& Next ( T * ); } ) {
    1212        struct Queue {
    1313                inline Collection;                                                              // Plan 9 inheritance
     
    151151} // distribution
    152152
    153 forall( dtype T | { T *& Next ( T * ); } ) {
     153forall( T & | { T *& Next ( T * ); } ) {
    154154        struct QueueIter {
    155155                inline ColIter;                                                                 // Plan 9 inheritance
  • libcfa/src/bits/sequence.hfa

    r5869cea r7b91c0e  
    2929
    3030        // // wrappers to make Collection have T
    31         // forall( dtype T ) {
     31        // forall( T & ) {
    3232        //      T *& Back( T * n ) {
    3333        //              return (T *)Back( (Seqable *)n );
     
    4343// and the back field of the last node points at the first node (circular).
    4444
    45 forall( dtype T | { T *& Back ( T * ); T *& Next ( T * ); } ) {
     45forall( T & | { T *& Back ( T * ); T *& Next ( T * ); } ) {
    4646        struct Sequence {
    4747                inline Collection;                                                              // Plan 9 inheritance
     
    231231} // distribution
    232232
    233 forall( dtype T | { T *& Back ( T * ); T *& Next ( T * ); } ) {
     233forall( T & | { T *& Back ( T * ); T *& Next ( T * ); } ) {
    234234        // SeqIter(T) is used to iterate over a Sequence(T) in head-to-tail order.
    235235        struct SeqIter {
  • libcfa/src/bits/stack.hfa

    r5869cea r7b91c0e  
    99// instead of being null.
    1010
    11 forall( dtype T | { T *& Next ( T * ); } ) {
     11forall( T & | { T *& Next ( T * ); } ) {
    1212        struct Stack {
    1313                inline Collection;                                                              // Plan 9 inheritance
     
    6767// order returned by drop().
    6868
    69 forall( dtype T | { T *& Next ( T * ); } ) {
     69forall( T & | { T *& Next ( T * ); } ) {
    7070        struct StackIter {
    7171                inline ColIter;                                                                 // Plan 9 inheritance
  • libcfa/src/common.cfa

    r5869cea r7b91c0e  
    2323[ long int, long int ] div( long int num, long int denom ) { ldiv_t qr = ldiv( num, denom ); return [ qr.quot, qr.rem ]; }
    2424[ long long int, long long int ] div( long long int num, long long int denom ) { lldiv_t qr = lldiv( num, denom ); return [ qr.quot, qr.rem ]; }
    25 forall( otype T | { T ?/?( T, T ); T ?%?( T, T ); } )
     25forall( T | { T ?/?( T, T ); T ?%?( T, T ); } )
    2626[ T, T ] div( T num, T denom ) { return [ num / denom, num % denom ]; }
    2727
  • libcfa/src/common.hfa

    r5869cea r7b91c0e  
    2121[ long int, long int ] div( long int num, long int denom );
    2222[ long long int, long long int ] div( long long int num, long long int denom );
    23 forall( otype T | { T ?/?( T, T ); T ?%?( T, T ); } )
     23forall( T | { T ?/?( T, T ); T ?%?( T, T ); } )
    2424[ T, T ] div( T num, T demon );
    2525
     
    6161} // distribution
    6262
    63 forall( otype T | { void ?{}( T &, zero_t ); int ?<?( T, T ); T -?( T ); } )
     63forall( T | { void ?{}( T &, zero_t ); int ?<?( T, T ); T -?( T ); } )
    6464T abs( T );
    6565
     
    7070        intptr_t min( intptr_t t1, intptr_t t2 ) { return t1 < t2 ? t1 : t2; } // optimization
    7171        uintptr_t min( uintptr_t t1, uintptr_t t2 ) { return t1 < t2 ? t1 : t2; } // optimization
    72         forall( otype T | { int ?<?( T, T ); } )
     72        forall( T | { int ?<?( T, T ); } )
    7373        T min( T t1, T t2 ) { return t1 < t2 ? t1 : t2; }
    7474
     
    7676        intptr_t max( intptr_t t1, intptr_t t2 ) { return t1 > t2 ? t1 : t2; } // optimization
    7777        uintptr_t max( uintptr_t t1, uintptr_t t2 ) { return t1 > t2 ? t1 : t2; } // optimization
    78         forall( otype T | { int ?>?( T, T ); } )
     78        forall( T | { int ?>?( T, T ); } )
    7979        T max( T t1, T t2 ) { return t1 > t2 ? t1 : t2; }
    8080
    81         forall( otype T | { T min( T, T ); T max( T, T ); } )
     81        forall( T | { T min( T, T ); T max( T, T ); } )
    8282        T clamp( T value, T min_val, T max_val ) { return max( min_val, min( value, max_val ) ); }
    8383
    84         forall( otype T )
     84        forall( T )
    8585        void swap( T & v1, T & v2 ) { T temp = v1; v1 = v2; v2 = temp; }
    8686} // distribution
  • libcfa/src/concurrency/coroutine.cfa

    r5869cea r7b91c0e  
    4646
    4747//-----------------------------------------------------------------------------
    48 FORALL_DATA_INSTANCE(CoroutineCancelled, (dtype coroutine_t), (coroutine_t))
    49 
    50 forall(dtype T)
     48FORALL_DATA_INSTANCE(CoroutineCancelled, (coroutine_t &), (coroutine_t))
     49
     50forall(T &)
    5151void mark_exception(CoroutineCancelled(T) *) {}
    5252
    53 forall(dtype T)
     53forall(T &)
    5454void copy(CoroutineCancelled(T) * dst, CoroutineCancelled(T) * src) {
    5555        dst->virtual_table = src->virtual_table;
     
    5858}
    5959
    60 forall(dtype T)
     60forall(T &)
    6161const char * msg(CoroutineCancelled(T) *) {
    6262        return "CoroutineCancelled(...)";
     
    6464
    6565// This code should not be inlined. It is the error path on resume.
    66 forall(dtype T | is_coroutine(T))
     66forall(T & | is_coroutine(T))
    6767void __cfaehm_cancelled_coroutine( T & cor, $coroutine * desc ) {
    6868        verify( desc->cancellation );
     
    148148// Part of the Public API
    149149// Not inline since only ever called once per coroutine
    150 forall(dtype T | is_coroutine(T))
     150forall(T & | is_coroutine(T))
    151151void prime(T& cor) {
    152152        $coroutine* this = get_coroutine(cor);
  • libcfa/src/concurrency/coroutine.hfa

    r5869cea r7b91c0e  
    2222//-----------------------------------------------------------------------------
    2323// Exception thrown from resume when a coroutine stack is cancelled.
    24 FORALL_DATA_EXCEPTION(CoroutineCancelled, (dtype coroutine_t), (coroutine_t)) (
     24FORALL_DATA_EXCEPTION(CoroutineCancelled, (coroutine_t &), (coroutine_t)) (
    2525        coroutine_t * the_coroutine;
    2626        exception_t * the_exception;
    2727);
    2828
    29 forall(dtype T)
     29forall(T &)
    3030void copy(CoroutineCancelled(T) * dst, CoroutineCancelled(T) * src);
    3131
    32 forall(dtype T)
     32forall(T &)
    3333const char * msg(CoroutineCancelled(T) *);
    3434
     
    3737// Anything that implements this trait can be resumed.
    3838// Anything that is resumed is a coroutine.
    39 trait is_coroutine(dtype T | IS_RESUMPTION_EXCEPTION(CoroutineCancelled, (T))) {
     39trait is_coroutine(T & | IS_RESUMPTION_EXCEPTION(CoroutineCancelled, (T))) {
    4040        void main(T & this);
    4141        $coroutine * get_coroutine(T & this);
     
    6060//-----------------------------------------------------------------------------
    6161// Public coroutine API
    62 forall(dtype T | is_coroutine(T))
     62forall(T & | is_coroutine(T))
    6363void prime(T & cor);
    6464
     
    7272        void __cfactx_invoke_coroutine(void (*main)(void *), void * this);
    7373
    74         forall(dtype T)
     74        forall(T &)
    7575        void __cfactx_start(void (*main)(T &), struct $coroutine * cor, T & this, void (*invoke)(void (*main)(void *), void *));
    7676
     
    129129}
    130130
    131 forall(dtype T | is_coroutine(T))
     131forall(T & | is_coroutine(T))
    132132void __cfaehm_cancelled_coroutine( T & cor, $coroutine * desc );
    133133
    134134// Resume implementation inlined for performance
    135 forall(dtype T | is_coroutine(T))
     135forall(T & | is_coroutine(T))
    136136static inline T & resume(T & cor) {
    137137        // optimization : read TLS once and reuse it
  • libcfa/src/concurrency/future.hfa

    r5869cea r7b91c0e  
    1919#include "monitor.hfa"
    2020
    21 forall( otype T ) {
     21forall( T ) {
    2222        struct future {
    2323                inline future_t;
     
    5858}
    5959
    60 forall( otype T ) {
     60forall( T ) {
    6161        monitor multi_future {
    6262                inline future_t;
  • libcfa/src/concurrency/io/types.hfa

    r5869cea r7b91c0e  
    55// file "LICENCE" distributed with Cforall.
    66//
    7 // io/types.hfa --
     7// io/types.hfa -- PRIVATE
     8// Types used by the I/O subsystem
    89//
    910// Author           : Thierry Delisle
     
    2122
    2223#include "bits/locks.hfa"
     24#include "kernel/fwd.hfa"
    2325
    2426#if defined(CFA_HAVE_LINUX_IO_URING_H)
  • libcfa/src/concurrency/kernel.cfa

    r5869cea r7b91c0e  
    224224        }
    225225
    226         V( this->terminated );
     226        post( this->terminated );
    227227
    228228        if(this == mainProcessor) {
     
    624624// Unexpected Terminating logic
    625625//=============================================================================================
    626 
    627 extern "C" {
    628         extern void __cfaabi_real_abort(void);
    629 }
    630 static volatile bool kernel_abort_called = false;
    631 
    632 void * kernel_abort(void) __attribute__ ((__nothrow__)) {
    633         // abort cannot be recursively entered by the same or different processors because all signal handlers return when
    634         // the globalAbort flag is true.
    635         bool first = !__atomic_test_and_set( &kernel_abort_called, __ATOMIC_SEQ_CST);
    636 
    637         // first task to abort ?
    638         if ( !first ) {
    639                 // We aren't the first to abort.
    640                 // I give up, just let C handle it
    641                 __cfaabi_real_abort();
    642         }
    643 
    644         // disable interrupts, it no longer makes sense to try to interrupt this processor
    645         disable_interrupts();
    646 
    647         return __cfaabi_tls.this_thread;
    648 }
    649 
    650 void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
    651         $thread * thrd = ( $thread * ) kernel_data;
     626void __kernel_abort_msg( char * abort_text, int abort_text_size ) {
     627        $thread * thrd = __cfaabi_tls.this_thread;
    652628
    653629        if(thrd) {
     
    669645}
    670646
    671 int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
    672         return get_coroutine(kernelTLS().this_thread) == get_coroutine(mainThread) ? 4 : 2;
     647int __kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
     648        return get_coroutine(__cfaabi_tls.this_thread) == get_coroutine(mainThread) ? 4 : 2;
    673649}
    674650
     
    688664// Kernel Utilities
    689665//=============================================================================================
    690 //-----------------------------------------------------------------------------
    691 // Locks
    692 void  ?{}( semaphore & this, int count = 1 ) {
    693         (this.lock){};
    694         this.count = count;
    695         (this.waiting){};
    696 }
    697 void ^?{}(semaphore & this) {}
    698 
    699 bool P(semaphore & this) with( this ){
    700         lock( lock __cfaabi_dbg_ctx2 );
    701         count -= 1;
    702         if ( count < 0 ) {
    703                 // queue current task
    704                 append( waiting, active_thread() );
    705 
    706                 // atomically release spin lock and block
    707                 unlock( lock );
    708                 park();
    709                 return true;
    710         }
    711         else {
    712             unlock( lock );
    713             return false;
    714         }
    715 }
    716 
    717 bool V(semaphore & this) with( this ) {
    718         $thread * thrd = 0p;
    719         lock( lock __cfaabi_dbg_ctx2 );
    720         count += 1;
    721         if ( count <= 0 ) {
    722                 // remove task at head of waiting list
    723                 thrd = pop_head( waiting );
    724         }
    725 
    726         unlock( lock );
    727 
    728         // make new owner
    729         unpark( thrd );
    730 
    731         return thrd != 0p;
    732 }
    733 
    734 bool V(semaphore & this, unsigned diff) with( this ) {
    735         $thread * thrd = 0p;
    736         lock( lock __cfaabi_dbg_ctx2 );
    737         int release = max(-count, (int)diff);
    738         count += diff;
    739         for(release) {
    740                 unpark( pop_head( waiting ) );
    741         }
    742 
    743         unlock( lock );
    744 
    745         return thrd != 0p;
    746 }
    747 
    748666//-----------------------------------------------------------------------------
    749667// Debug
  • libcfa/src/concurrency/kernel.hfa

    r5869cea r7b91c0e  
    55// file "LICENCE" distributed with Cforall.
    66//
    7 // kernel --
     7// kernel -- Header containing the core of the kernel API
    88//
    99// Author           : Thierry Delisle
     
    2424extern "C" {
    2525        #include <bits/pthreadtypes.h>
     26        #include <pthread.h>
    2627        #include <linux/types.h>
    2728}
    2829
    2930//-----------------------------------------------------------------------------
    30 // Locks
    31 struct semaphore {
    32         __spinlock_t lock;
    33         int count;
    34         __queue_t($thread) waiting;
    35 };
    36 
    37 void  ?{}(semaphore & this, int count = 1);
    38 void ^?{}(semaphore & this);
    39 bool   P (semaphore & this);
    40 bool   V (semaphore & this);
    41 bool   V (semaphore & this, unsigned count);
     31// Underlying Locks
     32#ifdef __CFA_WITH_VERIFY__
     33        extern bool __cfaabi_dbg_in_kernel();
     34#endif
     35
     36extern "C" {
     37        char * strerror(int);
     38}
     39#define CHECKED(x) { int err = x; if( err != 0 ) abort("KERNEL ERROR: Operation \"" #x "\" return error %d - %s\n", err, strerror(err)); }
     40
     41struct __bin_sem_t {
     42        pthread_mutex_t         lock;
     43        pthread_cond_t          cond;
     44        int                     val;
     45};
     46
     47static inline void ?{}(__bin_sem_t & this) with( this ) {
     48        // Create the mutex with error checking
     49        pthread_mutexattr_t mattr;
     50        pthread_mutexattr_init( &mattr );
     51        pthread_mutexattr_settype( &mattr, PTHREAD_MUTEX_ERRORCHECK_NP);
     52        pthread_mutex_init(&lock, &mattr);
     53
     54        pthread_cond_init (&cond, (const pthread_condattr_t *)0p);  // workaround trac#208: cast should not be required
     55        val = 0;
     56}
     57
     58static inline void ^?{}(__bin_sem_t & this) with( this ) {
     59        CHECKED( pthread_mutex_destroy(&lock) );
     60        CHECKED( pthread_cond_destroy (&cond) );
     61}
     62
     63static inline void wait(__bin_sem_t & this) with( this ) {
     64        verify(__cfaabi_dbg_in_kernel());
     65        CHECKED( pthread_mutex_lock(&lock) );
     66                while(val < 1) {
     67                        pthread_cond_wait(&cond, &lock);
     68                }
     69                val -= 1;
     70        CHECKED( pthread_mutex_unlock(&lock) );
     71}
     72
     73static inline bool post(__bin_sem_t & this) with( this ) {
     74        bool needs_signal = false;
     75
     76        CHECKED( pthread_mutex_lock(&lock) );
     77                if(val < 1) {
     78                        val += 1;
     79                        pthread_cond_signal(&cond);
     80                        needs_signal = true;
     81                }
     82        CHECKED( pthread_mutex_unlock(&lock) );
     83
     84        return needs_signal;
     85}
     86
     87#undef CHECKED
    4288
    4389
     
    91137
    92138        // Termination synchronisation (user semaphore)
    93         semaphore terminated;
     139        oneshot terminated;
    94140
    95141        // pthread Stack
  • libcfa/src/concurrency/kernel/fwd.hfa

    r5869cea r7b91c0e  
    55// file "LICENCE" distributed with Cforall.
    66//
    7 // kernel/fwd.hfa --
     7// kernel/fwd.hfa -- PUBLIC
     8// Fundamental code needed to implement threading M.E.S. algorithms.
    89//
    910// Author           : Thierry Delisle
     
    134135                extern uint64_t thread_rand();
    135136
     137                // Semaphore which only supports a single thread
     138                struct single_sem {
     139                        struct $thread * volatile ptr;
     140                };
     141
     142                static inline {
     143                        void  ?{}(single_sem & this) {
     144                                this.ptr = 0p;
     145                        }
     146
     147                        void ^?{}(single_sem &) {}
     148
     149                        bool wait(single_sem & this) {
     150                                for() {
     151                                        struct $thread * expected = this.ptr;
     152                                        if(expected == 1p) {
     153                                                if(__atomic_compare_exchange_n(&this.ptr, &expected, 0p, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     154                                                        return false;
     155                                                }
     156                                        }
     157                                        else {
     158                                                /* paranoid */ verify( expected == 0p );
     159                                                if(__atomic_compare_exchange_n(&this.ptr, &expected, active_thread(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     160                                                        park();
     161                                                        return true;
     162                                                }
     163                                        }
     164
     165                                }
     166                        }
     167
     168                        bool post(single_sem & this) {
     169                                for() {
     170                                        struct $thread * expected = this.ptr;
     171                                        if(expected == 1p) return false;
     172                                        if(expected == 0p) {
     173                                                if(__atomic_compare_exchange_n(&this.ptr, &expected, 1p, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     174                                                        return false;
     175                                                }
     176                                        }
     177                                        else {
     178                                                if(__atomic_compare_exchange_n(&this.ptr, &expected, 0p, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     179                                                        unpark( expected );
     180                                                        return true;
     181                                                }
     182                                        }
     183                                }
     184                        }
     185                }
     186
     187                // Synchronozation primitive which only supports a single thread and one post
     188                // Similar to a binary semaphore with a 'one shot' semantic
     189                // is expected to be discarded after each party call their side
     190                struct oneshot {
     191                        // Internal state :
     192                        //     0p     : is initial state (wait will block)
     193                        //     1p     : fulfilled (wait won't block)
     194                        // any thread : a thread is currently waiting
     195                        struct $thread * volatile ptr;
     196                };
     197
     198                static inline {
     199                        void  ?{}(oneshot & this) {
     200                                this.ptr = 0p;
     201                        }
     202
     203                        void ^?{}(oneshot &) {}
     204
     205                        // Wait for the post, return immidiately if it already happened.
     206                        // return true if the thread was parked
     207                        bool wait(oneshot & this) {
     208                                for() {
     209                                        struct $thread * expected = this.ptr;
     210                                        if(expected == 1p) return false;
     211                                        /* paranoid */ verify( expected == 0p );
     212                                        if(__atomic_compare_exchange_n(&this.ptr, &expected, active_thread(), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     213                                                park();
     214                                                /* paranoid */ verify( this.ptr == 1p );
     215                                                return true;
     216                                        }
     217                                }
     218                        }
     219
     220                        // Mark as fulfilled, wake thread if needed
     221                        // return true if a thread was unparked
     222                        bool post(oneshot & this) {
     223                                struct $thread * got = __atomic_exchange_n( &this.ptr, 1p, __ATOMIC_SEQ_CST);
     224                                if( got == 0p ) return false;
     225                                unpark( got );
     226                                return true;
     227                        }
     228                }
     229
     230                // base types for future to build upon
     231                // It is based on the 'oneshot' type to allow multiple futures
     232                // to block on the same instance, permitting users to block a single
     233                // thread on "any of" [a given set of] futures.
     234                // does not support multiple threads waiting on the same future
     235                struct future_t {
     236                        // Internal state :
     237                        //     0p      : is initial state (wait will block)
     238                        //     1p      : fulfilled (wait won't block)
     239                        //     2p      : in progress ()
     240                        //     3p      : abandoned, server should delete
     241                        // any oneshot : a context has been setup to wait, a thread could wait on it
     242                        struct oneshot * volatile ptr;
     243                };
     244
     245                static inline {
     246                        void  ?{}(future_t & this) {
     247                                this.ptr = 0p;
     248                        }
     249
     250                        void ^?{}(future_t &) {}
     251
     252                        void reset(future_t & this) {
     253                                // needs to be in 0p or 1p
     254                                __atomic_exchange_n( &this.ptr, 0p, __ATOMIC_SEQ_CST);
     255                        }
     256
     257                        // check if the future is available
     258                        bool available( future_t & this ) {
     259                                return this.ptr == 1p;
     260                        }
     261
     262                        // Prepare the future to be waited on
     263                        // intented to be use by wait, wait_any, waitfor, etc. rather than used directly
     264                        bool setup( future_t & this, oneshot & wait_ctx ) {
     265                                /* paranoid */ verify( wait_ctx.ptr == 0p );
     266                                // The future needs to set the wait context
     267                                for() {
     268                                        struct oneshot * expected = this.ptr;
     269                                        // Is the future already fulfilled?
     270                                        if(expected == 1p) return false; // Yes, just return false (didn't block)
     271
     272                                        // The future is not fulfilled, try to setup the wait context
     273                                        /* paranoid */ verify( expected == 0p );
     274                                        if(__atomic_compare_exchange_n(&this.ptr, &expected, &wait_ctx, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     275                                                return true;
     276                                        }
     277                                }
     278                        }
     279
     280                        // Stop waiting on a future
     281                        // When multiple futures are waited for together in "any of" pattern
     282                        // futures that weren't fulfilled before the thread woke up
     283                        // should retract the wait ctx
     284                        // intented to be use by wait, wait_any, waitfor, etc. rather than used directly
     285                        void retract( future_t & this, oneshot & wait_ctx ) {
     286                                // Remove the wait context
     287                                struct oneshot * got = __atomic_exchange_n( &this.ptr, 0p, __ATOMIC_SEQ_CST);
     288
     289                                // got == 0p: future was never actually setup, just return
     290                                if( got == 0p ) return;
     291
     292                                // got == wait_ctx: since fulfil does an atomic_swap,
     293                                // if we got back the original then no one else saw context
     294                                // It is safe to delete (which could happen after the return)
     295                                if( got == &wait_ctx ) return;
     296
     297                                // got == 1p: the future is ready and the context was fully consumed
     298                                // the server won't use the pointer again
     299                                // It is safe to delete (which could happen after the return)
     300                                if( got == 1p ) return;
     301
     302                                // got == 2p: the future is ready but the context hasn't fully been consumed
     303                                // spin until it is safe to move on
     304                                if( got == 2p ) {
     305                                        while( this.ptr != 1p ) Pause();
     306                                        return;
     307                                }
     308
     309                                // got == any thing else, something wen't wrong here, abort
     310                                abort("Future in unexpected state");
     311                        }
     312
     313                        // Mark the future as abandoned, meaning it will be deleted by the server
     314                        bool abandon( future_t & this ) {
     315                                /* paranoid */ verify( this.ptr != 3p );
     316
     317                                // Mark the future as abandonned
     318                                struct oneshot * got = __atomic_exchange_n( &this.ptr, 3p, __ATOMIC_SEQ_CST);
     319
     320                                // If the future isn't already fulfilled, let the server delete it
     321                                if( got == 0p ) return false;
     322
     323                                // got == 2p: the future is ready but the context hasn't fully been consumed
     324                                // spin until it is safe to move on
     325                                if( got == 2p ) {
     326                                        while( this.ptr != 1p ) Pause();
     327                                        got = 1p;
     328                                }
     329
     330                                // The future is completed delete it now
     331                                /* paranoid */ verify( this.ptr != 1p );
     332                                free( &this );
     333                                return true;
     334                        }
     335
     336                        // from the server side, mark the future as fulfilled
     337                        // delete it if needed
     338                        bool fulfil( future_t & this ) {
     339                                for() {
     340                                        struct oneshot * expected = this.ptr;
     341                                        // was this abandoned?
     342                                        #if defined(__GNUC__) && __GNUC__ >= 7
     343                                                #pragma GCC diagnostic push
     344                                                #pragma GCC diagnostic ignored "-Wfree-nonheap-object"
     345                                        #endif
     346                                                if( expected == 3p ) { free( &this ); return false; }
     347                                        #if defined(__GNUC__) && __GNUC__ >= 7
     348                                                #pragma GCC diagnostic pop
     349                                        #endif
     350
     351                                        /* paranoid */ verify( expected != 1p ); // Future is already fulfilled, should not happen
     352                                        /* paranoid */ verify( expected != 2p ); // Future is bein fulfilled by someone else, this is even less supported then the previous case.
     353
     354                                        // If there is a wait context, we need to consume it and mark it as consumed after
     355                                        // If there is no context then we can skip the in progress phase
     356                                        struct oneshot * want = expected == 0p ? 1p : 2p;
     357                                        if(__atomic_compare_exchange_n(&this.ptr, &expected, want, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
     358                                                if( expected == 0p ) { /* paranoid */ verify( this.ptr == 1p); return false; }
     359                                                bool ret = post( *expected );
     360                                                __atomic_store_n( &this.ptr, 1p, __ATOMIC_SEQ_CST);
     361                                                return ret;
     362                                        }
     363                                }
     364
     365                        }
     366
     367                        // Wait for the future to be fulfilled
     368                        bool wait( future_t & this ) {
     369                                oneshot temp;
     370                                if( !setup(this, temp) ) return false;
     371
     372                                // Wait context is setup, just wait on it
     373                                bool ret = wait( temp );
     374
     375                                // Wait for the future to tru
     376                                while( this.ptr == 2p ) Pause();
     377                                // Make sure the state makes sense
     378                                // Should be fulfilled, could be in progress but it's out of date if so
     379                                // since if that is the case, the oneshot was fulfilled (unparking this thread)
     380                                // and the oneshot should not be needed any more
     381                                __attribute__((unused)) struct oneshot * was = this.ptr;
     382                                /* paranoid */ verifyf( was == 1p, "Expected this.ptr to be 1p, was %p\n", was );
     383
     384                                // Mark the future as fulfilled, to be consistent
     385                                // with potential calls to avail
     386                                // this.ptr = 1p;
     387                                return ret;
     388                        }
     389                }
     390
    136391                //-----------------------------------------------------------------------
    137392                // Statics call at the end of each thread to register statistics
  • libcfa/src/concurrency/kernel/startup.cfa

    r5869cea r7b91c0e  
    199199        void ?{}(processor & this) with( this ) {
    200200                ( this.idle ){};
    201                 ( this.terminated ){ 0 };
     201                ( this.terminated ){};
    202202                ( this.runner ){};
    203203                init( this, "Main Processor", *mainCluster );
     
    528528void ?{}(processor & this, const char name[], cluster & _cltr) {
    529529        ( this.idle ){};
    530         ( this.terminated ){ 0 };
     530        ( this.terminated ){};
    531531        ( this.runner ){};
    532532
     
    549549                __wake_proc( &this );
    550550
    551                 P( terminated );
     551                wait( terminated );
    552552                /* paranoid */ verify( active_processor() != &this);
    553553        }
  • libcfa/src/concurrency/locks.cfa

    r5869cea r7b91c0e  
    77//-----------------------------------------------------------------------------
    88// info_thread
    9 forall(dtype L | is_blocking_lock(L)) {
     9forall(L & | is_blocking_lock(L)) {
    1010        struct info_thread {
    1111                // used to put info_thread on a dl queue (aka sequence)
     
    195195//-----------------------------------------------------------------------------
    196196// alarm node wrapper
    197 forall(dtype L | is_blocking_lock(L)) {
     197forall(L & | is_blocking_lock(L)) {
    198198        struct alarm_node_wrap {
    199199                alarm_node_t alarm_node;
     
    239239//-----------------------------------------------------------------------------
    240240// condition variable
    241 forall(dtype L | is_blocking_lock(L)) {
     241forall(L & | is_blocking_lock(L)) {
    242242
    243243        void ?{}( condition_variable(L) & this ){
     
    356356        bool wait( condition_variable(L) & this, L & l, uintptr_t info, Time time         ) with(this) { WAIT_TIME( info, &l , time ) }
    357357}
     358
     359//-----------------------------------------------------------------------------
     360// Semaphore
     361void  ?{}( semaphore & this, int count = 1 ) {
     362        (this.lock){};
     363        this.count = count;
     364        (this.waiting){};
     365}
     366void ^?{}(semaphore & this) {}
     367
     368bool P(semaphore & this) with( this ){
     369        lock( lock __cfaabi_dbg_ctx2 );
     370        count -= 1;
     371        if ( count < 0 ) {
     372                // queue current task
     373                append( waiting, active_thread() );
     374
     375                // atomically release spin lock and block
     376                unlock( lock );
     377                park();
     378                return true;
     379        }
     380        else {
     381            unlock( lock );
     382            return false;
     383        }
     384}
     385
     386bool V(semaphore & this) with( this ) {
     387        $thread * thrd = 0p;
     388        lock( lock __cfaabi_dbg_ctx2 );
     389        count += 1;
     390        if ( count <= 0 ) {
     391                // remove task at head of waiting list
     392                thrd = pop_head( waiting );
     393        }
     394
     395        unlock( lock );
     396
     397        // make new owner
     398        unpark( thrd );
     399
     400        return thrd != 0p;
     401}
     402
     403bool V(semaphore & this, unsigned diff) with( this ) {
     404        $thread * thrd = 0p;
     405        lock( lock __cfaabi_dbg_ctx2 );
     406        int release = max(-count, (int)diff);
     407        count += diff;
     408        for(release) {
     409                unpark( pop_head( waiting ) );
     410        }
     411
     412        unlock( lock );
     413
     414        return thrd != 0p;
     415}
  • libcfa/src/concurrency/locks.hfa

    r5869cea r7b91c0e  
    1313//-----------------------------------------------------------------------------
    1414// is_blocking_lock
    15 trait is_blocking_lock(dtype L | sized(L)) {
     15trait is_blocking_lock(L & | sized(L)) {
    1616        // For synchronization locks to use when acquiring
    1717        void on_notify( L &, struct $thread * );
     
    3131// the info thread is a wrapper around a thread used
    3232// to store extra data for use in the condition variable
    33 forall(dtype L | is_blocking_lock(L)) {
     33forall(L & | is_blocking_lock(L)) {
    3434        struct info_thread;
    3535
     
    120120//-----------------------------------------------------------------------------
    121121// Synchronization Locks
    122 forall(dtype L | is_blocking_lock(L)) {
     122forall(L & | is_blocking_lock(L)) {
    123123        struct condition_variable {
    124124                // Spin lock used for mutual exclusion
     
    157157        bool wait( condition_variable(L) & this, L & l, uintptr_t info, Time time );
    158158}
     159
     160//-----------------------------------------------------------------------------
     161// Semaphore
     162struct semaphore {
     163        __spinlock_t lock;
     164        int count;
     165        __queue_t($thread) waiting;
     166};
     167
     168void  ?{}(semaphore & this, int count = 1);
     169void ^?{}(semaphore & this);
     170bool   P (semaphore & this);
     171bool   V (semaphore & this);
     172bool   V (semaphore & this, unsigned count);
  • libcfa/src/concurrency/monitor.cfa

    r5869cea r7b91c0e  
    5050static inline [$thread *, int] search_entry_queue( const __waitfor_mask_t &, $monitor * monitors [], __lock_size_t count );
    5151
    52 forall(dtype T | sized( T ))
     52forall(T & | sized( T ))
    5353static inline __lock_size_t insert_unique( T * array [], __lock_size_t & size, T * val );
    5454static inline __lock_size_t count_max    ( const __waitfor_mask_t & mask );
     
    949949}
    950950
    951 forall(dtype T | sized( T ))
     951forall(T & | sized( T ))
    952952static inline __lock_size_t insert_unique( T * array [], __lock_size_t & size, T * val ) {
    953953        if( !val ) return size;
  • libcfa/src/concurrency/monitor.hfa

    r5869cea r7b91c0e  
    2222#include "stdlib.hfa"
    2323
    24 trait is_monitor(dtype T) {
     24trait is_monitor(T &) {
    2525        $monitor * get_monitor( T & );
    2626        void ^?{}( T & mutex );
     
    5959void ^?{}( monitor_dtor_guard_t & this );
    6060
    61 static inline forall( dtype T | sized(T) | { void ^?{}( T & mutex ); } )
     61static inline forall( T & | sized(T) | { void ^?{}( T & mutex ); } )
    6262void delete( T * th ) {
    6363        ^(*th){};
  • libcfa/src/concurrency/mutex.cfa

    r5869cea r7b91c0e  
    164164}
    165165
    166 forall(dtype L | is_lock(L))
     166forall(L & | is_lock(L))
    167167void wait(condition_variable & this, L & l) {
    168168        lock( this.lock __cfaabi_dbg_ctx2 );
     
    176176//-----------------------------------------------------------------------------
    177177// Scopes
    178 forall(dtype L | is_lock(L))
     178forall(L & | is_lock(L))
    179179void lock_all  ( L * locks[], size_t count) {
    180180        // Sort locks based on addresses
     
    188188}
    189189
    190 forall(dtype L | is_lock(L))
     190forall(L & | is_lock(L))
    191191void unlock_all( L * locks[], size_t count) {
    192192        // Lock all
  • libcfa/src/concurrency/mutex.hfa

    r5869cea r7b91c0e  
    7070void unlock(recursive_mutex_lock & this) __attribute__((deprecated("use concurrency/locks.hfa instead")));
    7171
    72 trait is_lock(dtype L | sized(L)) {
     72trait is_lock(L & | sized(L)) {
    7373        void lock  (L &);
    7474        void unlock(L &);
     
    9494void wait(condition_variable & this) __attribute__((deprecated("use concurrency/locks.hfa instead")));
    9595
    96 forall(dtype L | is_lock(L))
     96forall(L & | is_lock(L))
    9797void wait(condition_variable & this, L & l) __attribute__((deprecated("use concurrency/locks.hfa instead")));
    9898
    9999//-----------------------------------------------------------------------------
    100100// Scopes
    101 forall(dtype L | is_lock(L)) {
     101forall(L & | is_lock(L)) {
    102102        #if !defined( __TUPLE_ARRAYS_EXIST__ )
    103103        void lock  ( L * locks [], size_t count);
  • libcfa/src/concurrency/preemption.cfa

    r5869cea r7b91c0e  
    616616}
    617617
     618// Prevent preemption since we are about to start terminating things
     619void __kernel_abort_lock(void) {
     620        signal_block( SIGUSR1 );
     621}
     622
    618623// Raii ctor/dtor for the preemption_scope
    619624// Used by thread to control when they want to receive preemption signals
  • libcfa/src/concurrency/thread.cfa

    r5869cea r7b91c0e  
    6262}
    6363
    64 FORALL_DATA_INSTANCE(ThreadCancelled, (dtype thread_t), (thread_t))
     64FORALL_DATA_INSTANCE(ThreadCancelled, (thread_t &), (thread_t))
    6565
    66 forall(dtype T)
     66forall(T &)
    6767void copy(ThreadCancelled(T) * dst, ThreadCancelled(T) * src) {
    6868        dst->virtual_table = src->virtual_table;
     
    7171}
    7272
    73 forall(dtype T)
     73forall(T &)
    7474const char * msg(ThreadCancelled(T) *) {
    7575        return "ThreadCancelled";
    7676}
    7777
    78 forall(dtype T)
     78forall(T &)
    7979static void default_thread_cancel_handler(ThreadCancelled(T) & ) {
    8080        abort( "Unhandled thread cancellation.\n" );
    8181}
    8282
    83 forall(dtype T | is_thread(T) | IS_EXCEPTION(ThreadCancelled, (T)))
     83forall(T & | is_thread(T) | IS_EXCEPTION(ThreadCancelled, (T)))
    8484void ?{}( thread_dtor_guard_t & this,
    85                 T & thrd, void(*defaultResumptionHandler)(ThreadCancelled(T) &)) {
    86         $monitor * m = get_monitor(thrd);
     85                T & thrd, void(*cancelHandler)(ThreadCancelled(T) &)) {
     86        $monitor * m = get_monitor(thrd);
    8787        $thread * desc = get_thread(thrd);
    8888
    8989        // Setup the monitor guard
    9090        void (*dtor)(T& mutex this) = ^?{};
    91         bool join = defaultResumptionHandler != (void(*)(ThreadCancelled(T)&))0;
     91        bool join = cancelHandler != (void(*)(ThreadCancelled(T)&))0;
    9292        (this.mg){&m, (void(*)())dtor, join};
    9393
     
    103103        }
    104104        desc->state = Cancelled;
    105         if (!join) {
    106                 defaultResumptionHandler = default_thread_cancel_handler;
    107         }
     105        void(*defaultResumptionHandler)(ThreadCancelled(T) &) =
     106                join ? cancelHandler : default_thread_cancel_handler;
    108107
    109108        ThreadCancelled(T) except;
     
    125124//-----------------------------------------------------------------------------
    126125// Starting and stopping threads
    127 forall( dtype T | is_thread(T) )
     126forall( T & | is_thread(T) )
    128127void __thrd_start( T & this, void (*main_p)(T &) ) {
    129128        $thread * this_thrd = get_thread(this);
     
    141140//-----------------------------------------------------------------------------
    142141// Support for threads that don't ues the thread keyword
    143 forall( dtype T | sized(T) | is_thread(T) | { void ?{}(T&); } )
     142forall( T & | sized(T) | is_thread(T) | { void ?{}(T&); } )
    144143void ?{}( scoped(T)& this ) with( this ) {
    145144        handle{};
     
    147146}
    148147
    149 forall( dtype T, ttype P | sized(T) | is_thread(T) | { void ?{}(T&, P); } )
     148forall( T &, P... | sized(T) | is_thread(T) | { void ?{}(T&, P); } )
    150149void ?{}( scoped(T)& this, P params ) with( this ) {
    151150        handle{ params };
     
    153152}
    154153
    155 forall( dtype T | sized(T) | is_thread(T) )
     154forall( T & | sized(T) | is_thread(T) )
    156155void ^?{}( scoped(T)& this ) with( this ) {
    157156        ^handle{};
     
    159158
    160159//-----------------------------------------------------------------------------
    161 forall(dtype T | is_thread(T) | IS_RESUMPTION_EXCEPTION(ThreadCancelled, (T)))
     160forall(T & | is_thread(T) | IS_RESUMPTION_EXCEPTION(ThreadCancelled, (T)))
    162161T & join( T & this ) {
    163162        thread_dtor_guard_t guard = { this, defaultResumptionHandler };
  • libcfa/src/concurrency/thread.hfa

    r5869cea r7b91c0e  
    2626//-----------------------------------------------------------------------------
    2727// thread trait
    28 trait is_thread(dtype T) {
     28trait is_thread(T &) {
    2929        void ^?{}(T& mutex this);
    3030        void main(T& this);
     
    3232};
    3333
    34 FORALL_DATA_EXCEPTION(ThreadCancelled, (dtype thread_t), (thread_t)) (
     34FORALL_DATA_EXCEPTION(ThreadCancelled, (thread_t &), (thread_t)) (
    3535        thread_t * the_thread;
    3636        exception_t * the_exception;
    3737);
    3838
    39 forall(dtype T)
     39forall(T &)
    4040void copy(ThreadCancelled(T) * dst, ThreadCancelled(T) * src);
    4141
    42 forall(dtype T)
     42forall(T &)
    4343const char * msg(ThreadCancelled(T) *);
    4444
     
    4747
    4848// Inline getters for threads/coroutines/monitors
    49 forall( dtype T | is_thread(T) )
     49forall( T & | is_thread(T) )
    5050static inline $coroutine* get_coroutine(T & this) __attribute__((const)) { return &get_thread(this)->self_cor; }
    5151
    52 forall( dtype T | is_thread(T) )
     52forall( T & | is_thread(T) )
    5353static inline $monitor  * get_monitor  (T & this) __attribute__((const)) { return &get_thread(this)->self_mon; }
    5454
     
    6060extern struct cluster * mainCluster;
    6161
    62 forall( dtype T | is_thread(T) )
     62forall( T & | is_thread(T) )
    6363void __thrd_start( T & this, void (*)(T &) );
    6464
     
    8282};
    8383
    84 forall( dtype T | is_thread(T) | IS_EXCEPTION(ThreadCancelled, (T)) )
     84forall( T & | is_thread(T) | IS_EXCEPTION(ThreadCancelled, (T)) )
    8585void ?{}( thread_dtor_guard_t & this, T & thrd, void(*)(ThreadCancelled(T) &) );
    8686void ^?{}( thread_dtor_guard_t & this );
     
    8989// thread runner
    9090// Structure that actually start and stop threads
    91 forall( dtype T | sized(T) | is_thread(T) )
     91forall( T & | sized(T) | is_thread(T) )
    9292struct scoped {
    9393        T handle;
    9494};
    9595
    96 forall( dtype T | sized(T) | is_thread(T) | { void ?{}(T&); } )
     96forall( T & | sized(T) | is_thread(T) | { void ?{}(T&); } )
    9797void ?{}( scoped(T)& this );
    9898
    99 forall( dtype T, ttype P | sized(T) | is_thread(T) | { void ?{}(T&, P); } )
     99forall( T &, P... | sized(T) | is_thread(T) | { void ?{}(T&, P); } )
    100100void ?{}( scoped(T)& this, P params );
    101101
    102 forall( dtype T | sized(T) | is_thread(T) )
     102forall( T & | sized(T) | is_thread(T) )
    103103void ^?{}( scoped(T)& this );
    104104
     
    115115void unpark( $thread * this );
    116116
    117 forall( dtype T | is_thread(T) )
     117forall( T & | is_thread(T) )
    118118static inline void unpark( T & this ) { if(!&this) return; unpark( get_thread( this ) );}
    119119
     
    128128//----------
    129129// join
    130 forall( dtype T | is_thread(T) | IS_RESUMPTION_EXCEPTION(ThreadCancelled, (T)) )
     130forall( T & | is_thread(T) | IS_RESUMPTION_EXCEPTION(ThreadCancelled, (T)) )
    131131T & join( T & this );
    132132
  • libcfa/src/containers/list.hfa

    r5869cea r7b91c0e  
    6666#define __DLISTED_MGD_JUSTIMPL(STRUCT)
    6767
    68 forall( dtype tE ) {
     68forall( tE & ) {
    6969        struct $mgd_link {
    7070                tE *elem;
     
    8383                (this.is_terminator){ 1 };
    8484        }
    85         forall ( otype tInit | { void ?{}( $mgd_link(tE) &, tInit); } )
     85        forall ( tInit | { void ?{}( $mgd_link(tE) &, tInit); } )
    8686        static inline void ?=?( $mgd_link(tE) &this, tInit i ) {
    8787                ^?{}( this );
     
    115115  __DLISTED_MGD_COMMON(STRUCT, STRUCT, $links)
    116116
    117 trait $dlistable(dtype Tnode, dtype Telem) {
     117trait $dlistable(Tnode &, Telem &) {
    118118        $mgd_link(Telem) & $prev_link(Tnode &);
    119119        $mgd_link(Telem) & $next_link(Tnode &);
     
    125125};
    126126
    127 forall (dtype Tnode, dtype Telem | $dlistable(Tnode, Telem)) {
     127forall (Tnode &, Telem & | $dlistable(Tnode, Telem)) {
    128128
    129129        // implemented as a sentinel item in an underlying cicrular list
  • libcfa/src/containers/maybe.cfa

    r5869cea r7b91c0e  
    1818
    1919
    20 forall(otype T)
     20forall(T)
    2121void ?{}(maybe(T) & this) {
    2222        this.has_value = false;
    2323}
    2424
    25 forall(otype T)
     25forall(T)
    2626void ?{}(maybe(T) & this, T value) {
    2727        this.has_value = true;
     
    2929}
    3030
    31 forall(otype T)
     31forall(T)
    3232void ?{}(maybe(T) & this, maybe(T) other) {
    3333        this.has_value = other.has_value;
     
    3737}
    3838
    39 forall(otype T)
     39forall(T)
    4040maybe(T) ?=?(maybe(T) & this, maybe(T) that) {
    4141        if (this.has_value && that.has_value) {
     
    5151}
    5252
    53 forall(otype T)
     53forall(T)
    5454void ^?{}(maybe(T) & this) {
    5555        if (this.has_value) {
     
    5858}
    5959
    60 forall(otype T)
     60forall(T)
    6161bool ?!=?(maybe(T) this, zero_t) {
    6262        return this.has_value;
    6363}
    6464
    65 forall(otype T)
     65forall(T)
    6666maybe(T) maybe_value(T value) {
    6767        return (maybe(T)){value};
    6868}
    6969
    70 forall(otype T)
     70forall(T)
    7171maybe(T) maybe_none() {
    7272        return (maybe(T)){};
    7373}
    7474
    75 forall(otype T)
     75forall(T)
    7676bool has_value(maybe(T) * this) {
    7777        return this->has_value;
    7878}
    7979
    80 forall(otype T)
     80forall(T)
    8181T get(maybe(T) * this) {
    8282        assertf(this->has_value, "attempt to get from maybe without value");
     
    8484}
    8585
    86 forall(otype T)
     86forall(T)
    8787void set(maybe(T) * this, T value) {
    8888        if (this->has_value) {
     
    9494}
    9595
    96 forall(otype T)
     96forall(T)
    9797void set_none(maybe(T) * this) {
    9898        if (this->has_value) {
  • libcfa/src/containers/maybe.hfa

    r5869cea r7b91c0e  
    1919
    2020// DO NOT USE DIRECTLY!
    21 forall(otype T)
     21forall(T)
    2222struct maybe {
    2323    bool has_value;
     
    2626
    2727
    28 forall(otype T)
     28forall(T)
    2929void ?{}(maybe(T) & this);
    3030
    31 forall(otype T)
     31forall(T)
    3232void ?{}(maybe(T) & this, T value);
    3333
    34 forall(otype T)
     34forall(T)
    3535void ?{}(maybe(T) & this, maybe(T) other);
    3636
    37 forall(otype T)
     37forall(T)
    3838void ^?{}(maybe(T) & this);
    3939
    40 forall(otype T)
     40forall(T)
    4141maybe(T) ?=?(maybe(T) & this, maybe(T) other);
    4242
    43 forall(otype T)
     43forall(T)
    4444bool ?!=?(maybe(T) this, zero_t);
    4545
    4646/* Waiting for bug#11 to be fixed.
    47 forall(otype T)
     47forall(T)
    4848maybe(T) maybe_value(T value);
    4949
    50 forall(otype T)
     50forall(T)
    5151maybe(T) maybe_none();
    5252*/
    5353
    54 forall(otype T)
     54forall(T)
    5555bool has_value(maybe(T) * this);
    5656
    57 forall(otype T)
     57forall(T)
    5858T get(maybe(T) * this);
    5959
    60 forall(otype T)
     60forall(T)
    6161void set(maybe(T) * this, T value);
    6262
    63 forall(otype T)
     63forall(T)
    6464void set_none(maybe(T) * this);
    6565
  • libcfa/src/containers/pair.cfa

    r5869cea r7b91c0e  
    1313#include <containers/pair.hfa>
    1414
    15 forall(otype R, otype S
     15forall(R, S
    1616        | { int ?==?(R, R); int ?<?(R, R); int ?<?(S, S); })
    1717int ?<?(pair(R, S) p, pair(R, S) q) {
     
    1919}
    2020
    21 forall(otype R, otype S
     21forall(R, S
    2222        | { int ?==?(R, R); int ?<?(R, R); int ?<=?(S, S); })
    2323int ?<=?(pair(R, S) p, pair(R, S) q) {
     
    2525}
    2626
    27 forall(otype R, otype S | { int ?==?(R, R); int ?==?(S, S); })
     27forall(R, S | { int ?==?(R, R); int ?==?(S, S); })
    2828int ?==?(pair(R, S) p, pair(R, S) q) {
    2929        return p.first == q.first && p.second == q.second;
    3030}
    3131
    32 forall(otype R, otype S | { int ?!=?(R, R); int ?!=?(S, S); })
     32forall(R, S | { int ?!=?(R, R); int ?!=?(S, S); })
    3333int ?!=?(pair(R, S) p, pair(R, S) q) {
    3434        return p.first != q.first || p.second != q.second;
    3535}
    3636
    37 forall(otype R, otype S
     37forall(R, S
    3838        | { int ?==?(R, R); int ?>?(R, R); int ?>?(S, S); })
    3939int ?>?(pair(R, S) p, pair(R, S) q) {
     
    4141}
    4242
    43 forall(otype R, otype S
     43forall(R, S
    4444        | { int ?==?(R, R); int ?>?(R, R); int ?>=?(S, S); })
    4545int ?>=?(pair(R, S) p, pair(R, S) q) {
  • libcfa/src/containers/pair.hfa

    r5869cea r7b91c0e  
    1616#pragma once
    1717
    18 forall(otype R, otype S) struct pair {
     18forall(R, S) struct pair {
    1919        R first;
    2020        S second;
    2121};
    2222
    23 forall(otype R, otype S
     23forall(R, S
    2424        | { int ?==?(R, R); int ?<?(R, R); int ?<?(S, S); })
    2525int ?<?(pair(R, S) p, pair(R, S) q);
    2626
    27 forall(otype R, otype S
     27forall(R, S
    2828        | { int ?==?(R, R); int ?<?(R, R); int ?<=?(S, S); })
    2929int ?<=?(pair(R, S) p, pair(R, S) q);
    3030
    31 forall(otype R, otype S | { int ?==?(R, R); int ?==?(S, S); })
     31forall(R, S | { int ?==?(R, R); int ?==?(S, S); })
    3232int ?==?(pair(R, S) p, pair(R, S) q);
    3333
    34 forall(otype R, otype S | { int ?!=?(R, R); int ?!=?(S, S); })
     34forall(R, S | { int ?!=?(R, R); int ?!=?(S, S); })
    3535int ?!=?(pair(R, S) p, pair(R, S) q);
    3636
    37 forall(otype R, otype S
     37forall(R, S
    3838        | { int ?==?(R, R); int ?>?(R, R); int ?>?(S, S); })
    3939int ?>?(pair(R, S) p, pair(R, S) q);
    4040
    41 forall(otype R, otype S
     41forall(R, S
    4242        | { int ?==?(R, R); int ?>?(R, R); int ?>=?(S, S); })
    4343int ?>=?(pair(R, S) p, pair(R, S) q);
  • libcfa/src/containers/result.cfa

    r5869cea r7b91c0e  
    1818
    1919
    20 forall(otype T, otype E)
     20forall(T, E)
    2121void ?{}(result(T, E) & this) {
    2222        this.has_value = false;
     
    2424}
    2525
    26 forall(otype T, otype E)
     26forall(T, E)
    2727void ?{}(result(T, E) & this, one_t, T value) {
    2828        this.has_value = true;
     
    3030}
    3131
    32 forall(otype T, otype E)
     32forall(T, E)
    3333void ?{}(result(T, E) & this, zero_t, E error) {
    3434        this.has_value = false;
     
    3636}
    3737
    38 forall(otype T, otype E)
     38forall(T, E)
    3939void ?{}(result(T, E) & this, result(T, E) other) {
    4040        this.has_value = other.has_value;
     
    4646}
    4747
    48 forall(otype T, otype E)
     48forall(T, E)
    4949result(T, E) ?=?(result(T, E) & this, result(T, E) that) {
    5050        if (this.has_value && that.has_value) {
     
    6363}
    6464
    65 forall(otype T, otype E)
     65forall(T, E)
    6666void ^?{}(result(T, E) & this) {
    6767        if (this.has_value) {
     
    7272}
    7373
    74 forall(otype T, otype E)
     74forall(T, E)
    7575bool ?!=?(result(T, E) this, zero_t) {
    7676        return this.has_value;
    7777}
    7878
    79 forall(otype T, otype E)
     79forall(T, E)
    8080result(T, E) result_value(T value) {
    8181        return (result(T, E)){1, value};
    8282}
    8383
    84 forall(otype T, otype E)
     84forall(T, E)
    8585result(T, E) result_error(E error) {
    8686        return (result(T, E)){0, error};
    8787}
    8888
    89 forall(otype T, otype E)
     89forall(T, E)
    9090bool has_value(result(T, E) * this) {
    9191        return this->has_value;
    9292}
    9393
    94 forall(otype T, otype E)
     94forall(T, E)
    9595T get(result(T, E) * this) {
    9696        assertf(this->has_value, "attempt to get from result without value");
     
    9898}
    9999
    100 forall(otype T, otype E)
     100forall(T, E)
    101101E get_error(result(T, E) * this) {
    102102        assertf(!this->has_value, "attempt to get from result without error");
     
    104104}
    105105
    106 forall(otype T, otype E)
     106forall(T, E)
    107107void set(result(T, E) * this, T value) {
    108108        if (this->has_value) {
     
    115115}
    116116
    117 forall(otype T, otype E)
     117forall(T, E)
    118118void set_error(result(T, E) * this, E error) {
    119119        if (this->has_value) {
  • libcfa/src/containers/result.hfa

    r5869cea r7b91c0e  
    1919
    2020// DO NOT USE DIRECTLY!
    21 forall(otype T, otype E)
     21forall(T, E)
    2222union inner_result{
    2323        T value;
     
    2525};
    2626
    27 forall(otype T, otype E)
     27forall(T, E)
    2828struct result {
    2929        bool has_value;
     
    3232
    3333
    34 forall(otype T, otype E)
     34forall(T, E)
    3535void ?{}(result(T, E) & this);
    3636
    37 forall(otype T, otype E)
     37forall(T, E)
    3838void ?{}(result(T, E) & this, one_t, T value);
    3939
    40 forall(otype T, otype E)
     40forall(T, E)
    4141void ?{}(result(T, E) & this, zero_t, E error);
    4242
    43 forall(otype T, otype E)
     43forall(T, E)
    4444void ?{}(result(T, E) & this, result(T, E) other);
    4545
    46 forall(otype T, otype E)
     46forall(T, E)
    4747void ^?{}(result(T, E) & this);
    4848
    49 forall(otype T, otype E)
     49forall(T, E)
    5050result(T, E) ?=?(result(T, E) & this, result(T, E) other);
    5151
    52 forall(otype T, otype E)
     52forall(T, E)
    5353bool ?!=?(result(T, E) this, zero_t);
    5454
    5555/* Wating for bug#11 to be fixed.
    56 forall(otype T, otype E)
     56forall(T, E)
    5757result(T, E) result_value(T value);
    5858
    59 forall(otype T, otype E)
     59forall(T, E)
    6060result(T, E) result_error(E error);
    6161*/
    6262
    63 forall(otype T, otype E)
     63forall(T, E)
    6464bool has_value(result(T, E) * this);
    6565
    66 forall(otype T, otype E)
     66forall(T, E)
    6767T get(result(T, E) * this);
    6868
    69 forall(otype T, otype E)
     69forall(T, E)
    7070E get_error(result(T, E) * this);
    7171
    72 forall(otype T, otype E)
     72forall(T, E)
    7373void set(result(T, E) * this, T value);
    7474
    75 forall(otype T, otype E)
     75forall(T, E)
    7676void set_error(result(T, E) * this, E error);
    7777
  • libcfa/src/containers/stackLockFree.hfa

    r5869cea r7b91c0e  
    99// Created On       : Wed May 13 20:58:58 2020
    1010// Last Modified By : Peter A. Buhr
    11 // Last Modified On : Sun Jun 14 13:25:09 2020
    12 // Update Count     : 64
     11// Last Modified On : Wed Jan 20 20:40:03 2021
     12// Update Count     : 67
    1313//
    1414
     
    1717#include <stdint.h>
    1818
    19 forall( dtype T )
     19forall( T & )
    2020union Link {
    2121        struct {                                                                                        // 32/64-bit x 2
     
    3131}; // Link
    3232
    33 forall( otype T | sized(T) | { Link(T) * ?`next( T * ); } ) {
     33forall( T | sized(T) | { Link(T) * ?`next( T * ); } ) {
    3434        struct StackLF {
    3535                Link(T) stack;
     
    4242
    4343                void push( StackLF(T) & this, T & n ) with(this) {
    44                         *( &n )`next = stack;                                   // atomic assignment unnecessary, or use CAA
     44                        *( &n )`next = stack;                                           // atomic assignment unnecessary, or use CAA
    4545                        for () {                                                                        // busy wait
    4646                          if ( __atomic_compare_exchange_n( &stack.atom, &( &n )`next->atom, (Link(T))@{ {&n, ( &n )`next->count + 1} }.atom, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) ) break; // attempt to update top node
     
    6565                                }
    6666                                if( next == 0p ) return false;
    67                                 link = (next)`next;
     67                                link = ( next )`next;
    6868                        }
    6969                }
  • libcfa/src/containers/vector.cfa

    r5869cea r7b91c0e  
    1818#include <stdlib.hfa>