prog.tex 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243
  1. %
  2. % $Id$
  3. % This file is part of the FPC documentation.
  4. % Copyright (C) 1997, by Michael Van Canneyt
  5. %
  6. % The FPC documentation is free text; you can redistribute it and/or
  7. % modify it under the terms of the GNU Library General Public License as
  8. % published by the Free Software Foundation; either version 2 of the
  9. % License, or (at your option) any later version.
  10. %
  11. % The FPC Documentation is distributed in the hope that it will be useful,
  12. % but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. % Library General Public License for more details.
  15. %
  16. % You should have received a copy of the GNU Library General Public
  17. % License along with the FPC documentation; see the file COPYING.LIB. If not,
  18. % write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19. % Boston, MA 02111-1307, USA.
  20. %
  21. \documentclass{report}
  22. \usepackage{a4}
  23. \usepackage{html}
  24. \latex{\usepackage{multicol}}
  25. \latex{\usepackage{fpcman}}
  26. \usepackage{fancyheadings}
  27. \pagestyle{fancy}
  28. \renewcommand{\chaptermark}[1]{\markboth{#1}{}}
  29. \html{\input{fpc-html.tex}}
  30. % define the version number here, and not in the fpc.sty !!!
  31. \newcommand{\remark}[1]{\par$\rightarrow$\textbf{#1}\par}
  32. \newcommand{\olabel}[1]{\label{option:#1}}
  33. % We should change this to something better. See \seef etc.
  34. \begin{document}
  35. \title{Free Pascal \\ Programmers' manual}
  36. \docdescription{Programmers' manual for \fpc, version \fpcversion}
  37. \docversion{1.4}
  38. \date{July 1998}
  39. \author{Micha\"el Van Canneyt}
  40. \maketitle
  41. \tableofcontents
  42. \newpage
  43. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  44. % Introduction
  45. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  46. \section*{About this document}
  47. This is the programmer's manual for \fpc.
  48. It describes some of the peculiarities of the \fpc compiler, and provides a
  49. glimpse of how the compiler generates its code, and how you can change the
  50. generated code. It will not, however, provide you with a detailed account of
  51. the inner workings of the compiler, nor will it tell you how to use the
  52. compiler (described in the \userref). It also will not describe the inner
  53. workings of the Run-Time Library (RTL). The best way to learn about the way
  54. the RTL is implemented is from the sources themselves.
  55. The things described here are useful if you want to do things which need
  56. greater flexibility than the standard Pascal language constructs.
  57. (described in the \refref)
  58. Since the compiler is continuously under development, this document may get
  59. out of date. Wherever possible, the information in this manual will be
  60. updated. If you find something which isn't correct, or you think something
  61. is missing, feel free to contact me\footnote{at
  62. \var{[email protected]}}.
  63. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  64. % Compiler switches
  65. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  66. \chapter{Compiler directives}
  67. \label{ch:CompSwitch}
  68. \fpc supports compiler directives in your source file. They are not the same
  69. as Turbo Pascal directives, although some are supported for compatibility.
  70. There is a distinction between local and global directives; local directives
  71. take effect from the moment they are encountered, global directives have an
  72. effect on all of the compiled code.
  73. Many switches have a long form also. If they do, then the name of the
  74. long form is given also. For long switches, the + or - character to switch
  75. the option on or off, may be replaced by \var{ON} or \var{OFF} keywords.
  76. Thus \verb|{$I+}| is equivalent to \verb|{$IOCHECKS ON}| or
  77. \verb|{$IOCHECKS +}| and
  78. \verb|{$C-}| is equivalent to \verb|{$ASSERTIONS OFF}| or
  79. \verb|{$ASSERTIONS -}|
  80. The long forms of the switches are the same as their Delphi
  81. counterparts.
  82. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  83. % Local switches
  84. \section{Local directives}
  85. \label{se:LocalSwitch}
  86. Local directives have no command-line counterpart. They influence the
  87. compiler's behaviour from the moment they're encountered until the moment
  88. another switch annihilates their behaviour, or the end of the unit or
  89. program is reached.
  90. \subsection{\var{\$DEFINE} : Define a symbol}
  91. The directive
  92. \begin{verbatim}
  93. {$DEFINE name}
  94. \end{verbatim}
  95. defines the symbol \var{name}. This symbol remains defined until the end of
  96. the current module, or until a \var{\$UNDEF name} directive is encountered.
  97. If \var{name} is already defined, this has no effect. \var{Name} is case
  98. insensitive.
  99. \subsection{\var{\$ELSE} : Switch conditional compilation}
  100. The \var{\{\$ELSE \}} switches between compiling and ignoting the source
  101. text delimited by the preceding \var{\{\$IFxxx\}} and following
  102. \var{\{\$ENDIF\}}. Any text after the \var{ELSE} keyword but before the
  103. brace is ignored:
  104. \begin{verbatim}
  105. {$ELSE some ignored text}
  106. \end{verbatim}
  107. is the same as
  108. \begin{verbatim}
  109. {$ELSE}
  110. \end{verbatim}
  111. This is useful for indication what switch is meant.
  112. \subsection{\var{\$ENDIF} : End conditional compilation}
  113. The \var{\{\$ENDIF\}} directive ends the conditional compilation initiated by the
  114. last \var{\{\$IFxxx\}} directive. Any text after the \var{ENDIF} keyword but
  115. before the closing brace is ignored:
  116. \begin{verbatim}
  117. {$ENDIF some ignored text}
  118. \end{verbatim}
  119. is the same as
  120. \begin{verbatim}
  121. {$ENDIF}
  122. \end{verbatim}
  123. This is useful for indication what switch is meant to be ended.
  124. \subsection{\var{\$ERROR} : Generate error message}
  125. The following code
  126. \begin{verbatim}
  127. {$ERROR This code is erroneous !}
  128. \end{verbatim}
  129. will display an error message when the compiler encounters it,
  130. and increase the error count of the compiler.
  131. The compiler will continue to compile, but no code will be emitted.
  132. \subsection{\var{\$F} : Far or near functions}
  133. This directive is recognized for compatibility with Turbo Pascal. Under the
  134. 32-bit programming model, the concept of near and far calls have no meaning,
  135. hence the directive is ignored. A warning is printed to the screen, telling
  136. you so.
  137. As an example, : the following piece of code :
  138. \begin{verbatim}
  139. {$F+}
  140. Procedure TestProc;
  141. begin
  142. Writeln ('Hello From TestProc');
  143. end;
  144. begin
  145. testProc
  146. end.
  147. \end{verbatim}
  148. Generates the following compiler output:
  149. \begin{verbatim}
  150. malpertuus: >pp -vw testf
  151. Compiler: ppc386
  152. Units are searched in: /home/michael;/usr/bin/;/usr/lib/ppc/0.9.1/linuxunits
  153. Target OS: Linux
  154. Compiling testf.pp
  155. testf.pp(1) Warning: illegal compiler switch
  156. 7739 kB free
  157. Calling assembler...
  158. Assembled...
  159. Calling linker...
  160. 12 lines compiled,
  161. 1.00000000000000E+0000
  162. \end{verbatim}
  163. You can see that the verbosity level was set to display warnings.
  164. If you declare a function as \var{Far} (this has the same effect as setting it
  165. between \var{\{\$F+\}...\{\$F-\}} directives), the compiler also generates a
  166. warning :
  167. \begin{verbatim}
  168. testf.pp(3) Warning: FAR ignored
  169. \end{verbatim}
  170. The same story is true for procedures declared as \var{Near}. The warning
  171. displayed in that case is:
  172. \begin{verbatim}
  173. testf.pp(3) Warning: NEAR ignored
  174. \end{verbatim}
  175. \subsection{\var{\$FATAL} : Generate fatal error message}
  176. The following code
  177. \begin{verbatim}
  178. {$FATAL This code is erroneous !}
  179. \end{verbatim}
  180. will display an error message when the compiler encounters it, and trigger
  181. and increase the error count of the compiler.
  182. The compiler will immediatly stop the compilation process.
  183. \subsection{\var{\$H} or \var{\$LONGSTRINGS} : Use AnsiStrings}
  184. If \var{\{\$LONGSTRINGS ON\}} is specified, the keyword \var{String} (no
  185. length specifier) will be treated as \var{AnsiString}, and the compiler
  186. will treat the corresponding varible as an ansistring, and will
  187. generate corresponding code.
  188. By default, the use of ansistrings is off, corresponding to \var{\{\$H-\}}.
  189. This feature is still experimental, and should be used with caution for the
  190. time being.
  191. \subsection{\var{\$HINT} : Generate hint message}
  192. If the generation of hints is turned on, through the \var{-vh} command-line
  193. option or the \var{\{\$HINTS ON\}} directive, then
  194. \begin{verbatim}
  195. {$Hint This code should be optimized }
  196. \end{verbatim}
  197. will display a hint message when the compiler encounters it.
  198. \subsection{\var{\$HINTS} : Emit hints}
  199. \var{\{\$HINTS ON\}} switches the generation of hints on.
  200. \var{\{\$HINTS OFF\}} switches the generation of hints off.
  201. Contrary to the command-line option \var{-vh} this is a local switch,
  202. this is useful for checking parts of your code.
  203. \subsection{\var{\$IF} : Start conditional compilation}
  204. The directive \var{\{\$IF expr\}} will continue the compilation
  205. if the boolean expression \var{expr} evaluates to \var{true}. If the
  206. compilation evaluates to false, then the source are skipped to the first
  207. \var{\{\$ELSE\}} or \var{\{\$ENDIF\}} directive.
  208. The compiler must be able to evaluate the expression at compile time.
  209. This means that you cannot use variables or constants that are defined in
  210. the source. Macros and symbols may be used, however.
  211. More information on this can be found in the section about
  212. conditionals.
  213. \subsection{\var{\$IFDEF} : Start conditional compilation}
  214. The \var{\{\$IFDEF name\}} will skip the compilation of the text that
  215. follows it if the symbol \var{name} is not defined. If it is defined, then
  216. compilation continues as if the directive wasn't there.
  217. \subsection{\var{\$IFNDEF} : Start conditional compilation}
  218. The \var{\{\$IFNDEF name\}} will skip the compilation of the text that
  219. follows it if the symbol \var{name} is defined. If it is not defined, then
  220. compilation continues as if the directive wasn't there.
  221. \subsection{\var{\$IFOPT} : Start conditional compilation}
  222. The \var{\{\$IFOPT switch\}} will skip the compilation of the text that
  223. follows it if the switch \var{switch} is currently not in the specified
  224. state. If it is in the specified state, then compilation continues as if the directive
  225. wasn't there.
  226. As an example:
  227. \begin{verbatim}
  228. {$IFOPT M+}
  229. Writeln ('Compiled with type information');
  230. {$ENDIF}
  231. \end{verbatim}
  232. Will compile the writeln statement if generation of type information is on.
  233. \subsection{\var{\$INFO} : Generate info message}
  234. If the generation of info is turned on, through the \var{-vi} command-line
  235. option, then
  236. \begin{verbatim}
  237. {$INFO This was coded on a rainy day by Bugs Bunny }
  238. \end{verbatim}
  239. will display an info message when the compiler encounters it.
  240. \subsection{\var{\$I} or \var{\$IOCHECK} : Input/Output checking}
  241. The \var{\{\$I-\}} or \var{\{\$IOCHECK OFF\}} directive tells the compiler
  242. not to generate input/output checking code in your program. By default, the
  243. compiler does not generate this code, you must switch it on using the
  244. \var{-Ci} command-lne switch.
  245. If you compile using the \var{-Ci} compiler switch, the \fpc compiler inserts input/output
  246. checking code after every input/output call in your program. If an error
  247. occurred during input or output, then a run-time error will be generated.
  248. Use this switch if you wish to avoid this behavior.
  249. If you still want to check if something went wrong, you can use the
  250. \var{IOResult} function to see if everything went without problems.
  251. Conversely, \var{\{\$I+\}} will turn error-checking back on, until another
  252. directive is encountered which turns it off again.
  253. The most common use for this switch is to check if the opening of a file
  254. went without problems, as in the following piece of code:
  255. \begin{verbatim}
  256. ...
  257. assign (f,'file.txt');
  258. {$I-}
  259. rewrite (f);
  260. {$I+}
  261. if IOResult<>0 then
  262. begin
  263. Writeln ('Error opening file : "file.txt"');
  264. exit
  265. end;
  266. ...
  267. \end{verbatim}
  268. \subsection{\var{\$I} or \var{\$INCLUDE} : Include file }
  269. The \var{\{\$I filename\}} or \var{\{\$INCLUDE filename\}} directive
  270. tells the compiler to read further statements from the file \var{filename}.
  271. The statements read there will be inserted as if they occurred in the
  272. current file.
  273. The compiler will append the \file{.pp} extension to the file if you don't
  274. specify an extension yourself. Do not put the filename between quotes, as
  275. they will be regarded as part of the file's name.
  276. You can nest included files, but not infinitely deep. The number of files is
  277. restricted to the number of file descriptors available to the \fpc compiler.
  278. Contrary to Turbo Pascal, include files can cross blocks. I.e. you can start
  279. a block in one file (with a \var{Begin} keyword) and end it in another (with
  280. a \var{End} keyword). The smallest entity in an include file must be a token,
  281. i.e. an identifier, keyword or operator.
  282. The compiler will look for the file to include in the following places:
  283. \begin{enumerate}
  284. \item It will look in the path specified in the incude file name.
  285. \item It will look in the directory where the current source file is.
  286. \item it will look in all directories specified in the include file search
  287. path.
  288. \end{enumerate}
  289. You can add files to the include file search path with the \var{-I}
  290. command-line option.
  291. \subsection{\var{\$I} or \var{\$INCLUDE} : Include compiler info}
  292. In this form:
  293. \begin{verbatim}
  294. {$INCLUDE %xxx%}
  295. \end{verbatim}
  296. where \var{xxx} is one of \var{TIME}, \var{DATE}, \var{FPCVERSION} or
  297. \var{FPCTARGET}, will generate a macro with the value of these things.
  298. If \var{xxx} is none of the above, then it is assumed to be the value of
  299. an environment variable. It's value will be fetched.
  300. % Assembler type
  301. \subsection{\var{\$I386\_XXX} : Specify assembler format}
  302. This switch can only be used in the i386 assembler.
  303. This switch informs the compiler what kind of assembler it can expect in an
  304. \var{asm} block. The \var{XXX} should be replaced by one of the following:
  305. \begin{description}
  306. \item [att\ ] Indicates that \var{asm} blocks contain AT\&T syntax assembler.
  307. \item [intel\ ] Indicates that \var{asm} blocks contain Intel syntax
  308. assembler.
  309. \item [direct\ ] Tells the compiler that asm blocks should be copied
  310. directly to the assembler file.
  311. \end{description}
  312. These switches are local, and retain their value to the end of the unit that
  313. is compiled, unless they are replaced by another directive of the same type.
  314. The command-line switch that corresponds to this switch is \var{-R}.
  315. \subsection{\var{\$L} or \var{\$LINK} : Link object file}
  316. The \var{\{\$L filename\}} or \var{\{\$LINK filename\}} directive
  317. tells the compiler that the file \file{filename} should be linked to
  318. your program.
  319. the compiler will look for this file in the following way:
  320. \begin{enumerate}
  321. \item It will look in the path specified in the object file name.
  322. \item It will look in the directory where the current source file is.
  323. \item it will look in all directories specified in the object file search path.
  324. \end{enumerate}
  325. You can add files to the object file search path with the \var{-Fo}
  326. option.
  327. On \linux systems, the name is case sensitive, and must be typed
  328. exactly as it appears on your system.
  329. {\em Remark :} Take care that the object file you're linking is in a
  330. format the linker understands. Which format this is, depends on the platform
  331. you're on. Typing \var{ld} on the command line gives a list of formats
  332. \var{ld} knows about.
  333. You can pass other files and options to the linker using the \var{-k}
  334. command-line option. You can specify more than one of these options, and
  335. they will be passed to the linker, in the order that you specified them on
  336. the command line, just before the names of the object files that must be
  337. linked.
  338. \subsection{\var{\$LINKLIB} : Link to a library}
  339. The \var{\{\$LINKLIB name\}} will link to a library \file{name}.
  340. This has the effect of passing \var{-lname} to the linker.
  341. As an example, consider the following unit:
  342. \begin{verbatim}
  343. unit getlen;
  344. interface
  345. {$LINKLIB c}
  346. function strlen (P : pchar) : longint;cdecl;
  347. implementation
  348. function strlen (P : pchar) : longint;cdecl;external;
  349. end.
  350. \end{verbatim}
  351. If one would issue the command the command
  352. \begin{verbatim}
  353. ppc386 foo.pp
  354. \end{verbatim}
  355. where foo.pp has the above unit in its \var{uses} clause,
  356. then the compiler would link your program to the c library, by passing the
  357. linker the \var{-lc} option.
  358. The same effect could be obtained by removing the linklib directive in the
  359. above unit, and specify \var{-k-lc} on the command-line:
  360. \begin{verbatim}
  361. ppc386 -k-lc foo.pp
  362. \end{verbatim}
  363. \subsection{\var{\$M} or \var{\$TYPEINFO} : Generate type info}
  364. This switch is recognized for Delphi compatibility only since the generation
  365. of type information isn't fully implemented yet.
  366. \subsection{\var{\$MMX} : Intel MMX support}
  367. As of version 0.9.8, \fpc supports optimization for the \textbf{MMX} Intel
  368. processor (see also \ref{ch:MMXSupport}). This optimizes certain code parts for the \textbf{MMX} Intel
  369. processor, thus greatly improving speed. The speed is noticed mostly when
  370. moving large amounts of data. Things that change are
  371. \begin{itemize}
  372. \item Data with a size that is a multiple of 8 bytes is moved using the
  373. \var{movq} assembler instruction, which moves 8 bytes at a time
  374. \end{itemize}
  375. When \textbf{MMX} support is on, you aren't allowed to do floating point
  376. arithmetic. You are allowed to move floating point data, but no arithmetic
  377. can be done. If you wish to do floating point math anyway, you must first
  378. switch of \textbf{MMX} support and clear the FPU using the \var{emms}
  379. function of the \file{cpu} unit.
  380. The following example will make this more clear:
  381. \begin{verbatim}
  382. Program MMXDemo;
  383. uses cpu;
  384. var
  385. d1 : double;
  386. a : array[0..10000] of double;
  387. i : longint;
  388. begin
  389. d1:=1.0;
  390. {$mmx+}
  391. { floating point data is used, but we do _no_ arithmetic }
  392. for i:=0 to 10000 do
  393. a[i]:=d2; { this is done with 64 bit moves }
  394. {$mmx-}
  395. emms; { clear fpu }
  396. { now we can do floating point arithmetic }
  397. ....
  398. end.
  399. \end{verbatim}
  400. See, however, the chapter on MMX (\ref{ch:MMXSupport}) for more information
  401. on this topic.
  402. \subsection{\var{\$NOTE} : Generate note message}
  403. If the generation of notes is turned on, through the \var{-vn} command-line
  404. option or the \var{\{\$NOTES ON\}} directive, then
  405. \begin{verbatim}
  406. {$NOTE Ask Santa Claus to look at this code }
  407. \end{verbatim}
  408. will display a note message when the compiler encounters it.
  409. \subsection{\var{\$NOTES} : Emit notes}
  410. \var{\{\$NOTES ON\}} switches the generation of notes on.
  411. \var{\{\$NOTES OFF\}} switches the generation of notes off.
  412. Contrary to the command-line option \var{-vn} this
  413. is a local switch, this is useful for checking parts of your code.
  414. \subsection{\var{\$OUTPUT\_FORMAT} : Specify the output format}
  415. \var{\{\$OUTPUT\_FORMAT format\}} has the same functionality as the \var{-A}
  416. command-line option : It tells the compiler what kind of object file must be
  417. generated. You can specify this switch \textbf{only} befor the \var{Program}
  418. or \var{Unit} clause in your source file. The different kinds of formats are
  419. shown in \seet{Formats}.
  420. \begin{FPCltable}{ll}{Formats generated by the x86 compiler}{Formats} \hline
  421. Switch value & Generated format \\ \hline
  422. att & AT\&T assembler file. \\
  423. o & Unix object file.\\
  424. obj & OMF file.\\
  425. wasm & assembler for the Watcom assembler. \\ \hline
  426. \end{FPCltable}
  427. \subsection{\var{\$P} or \var{\$OPENSTRINGS} : Use open strings}
  428. This switch is provided for compatibility only, as open strings aren't
  429. implemented yet.
  430. \subsection{\var{\$PACKENUM} : Minimum enumeration type size}
  431. This directive tells the compiler the minimum number of bytes it should
  432. use when storing enumerated types. It is of the following form:
  433. \begin{verbatim}
  434. {$PACKENUM xxx}
  435. {$MINENUMSIZE xxx}
  436. \end{verbatim}
  437. Where the form with \var{\$MINENUMSIZE} is for Delphi compatibility.
  438. var{xxx} can be one of \var{1,2} or \var{4}, or \var{NORMAL} or
  439. \var{DEFAULT}, corresponding to the default value of 4.
  440. As an alternative form one can use \var{\{\$Z1\}}, \var{\{\$Z2\}}
  441. \var{\{\$Z4\}}. Contrary to Delphi, the default size is 4 bytes
  442. (\var{\{\$Z4\}}).
  443. So the follwoing code
  444. \begin{verbatim}
  445. {$PACKENUM 1}
  446. Type
  447. Days = (monday, tuesday, wednesday, thursday, friday,
  448. saturday, sunday);
  449. \end{verbatim}
  450. will use 1 byte to store a variable of type \var{Days}, wheras it nomally
  451. would use 4 bytes. The above code is equivalent to
  452. \begin{verbatim}
  453. {$Z1}
  454. Type
  455. Days = (monday, tuesday, wednesday, thursday, friday,
  456. saturday, sunday);
  457. \end{verbatim}
  458. \subsection{\var{\$PACKRECORDS} : Alignment of record elements}
  459. This directive controls the byte alignment of the elements in a record,
  460. object or class type definition.
  461. It is of the following form:
  462. \begin{verbatim}
  463. {$PACKRECORDS xx}
  464. \end{verbatim}
  465. Where \var{xxx} is one of 1,2,4,16 or \var{NORMAL} or \var{DEFAULT}.
  466. This means that the elements of a record will be aligned on 1,2, 4 or
  467. 16 byte boundaries. Thus, the size of a record will always be a multiple of
  468. the alignment size.
  469. The default alignment (which can be selected with \var{DEFAULT}) is 2,
  470. contrary to Turbo Pascal, where it is 1.
  471. More information of this can be found in the reference guide, in the section
  472. about record types.
  473. \subsection{\var{\$STOP} : Generate fatal error message}
  474. The following code
  475. \begin{verbatim}
  476. {$STOP This code is erroneous !}
  477. \end{verbatim}
  478. will display an error message when the compiler encounters it.
  479. The compiler will immediatly stop the compilation process.
  480. It has the same effect as the \var{\{\$FATAL\}} directive.
  481. \subsection{\var{\$UNDEF} : Undefine a symbol}
  482. The directive
  483. \begin{verbatim}
  484. {$UNDEF name}
  485. \end{verbatim}
  486. un-defines the symbol \var{name} if it was previously defined.
  487. \var{Name} is case insensitive.
  488. \subsection{\var{\$V} or \var{\$VARSTRINGCHECKS} : Var-string checking}
  489. When in the \var{+} or \var{ON} state, the compiler checks that strings
  490. passed as parameters are of the same, identical, string type as the declared
  491. parameters of the procedure.
  492. \subsection{\var{\$WAIT} : Wait for enter key press}
  493. If the compiler encaounters a
  494. \begin{verbatim}
  495. {$WAIT }
  496. \end{verbatim}
  497. directive, it will resume compiling only after the user has pressed the
  498. enter key. If the generation of info messages is turned on, then the compiler
  499. will display the follwing message:
  500. \begin{verbatim}
  501. Press <return> to continue
  502. \end{verbatim}
  503. before waiting for a keypress. Careful ! this may interfere with automatic
  504. compilation processes. It should be used for debuggig purposes only.
  505. \subsection{\var{\$WARNING} : Generate warning message}
  506. If the generation of warnings is turned on, through the \var{-vw}
  507. command-line option or the \var{\{\$WARNINGS ON\}} directive, then
  508. \begin{verbatim}
  509. {$WARNING This is dubious code }
  510. \end{verbatim}
  511. will display a warning message when the compiler encounters it.
  512. \subsection{\var{\$WARNINGS} : Emit warnings}
  513. \var{\{\$WARNINGS ON\}} switches the generation of warnings on.
  514. \var{\{\$WARNINGS OFF\}} switches the generation of warnings off.
  515. Contrary to the command-line option \var{-vw} this
  516. is a local switch, this is useful for checking parts of your code.
  517. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  518. % Global switches
  519. \section{Global directives}
  520. \label{se:GlobalSwitch}
  521. Global directives affect the whole of the compilation process. That is why
  522. they also have a command - line counterpart. The command-line counterpart is
  523. given for each of the directives.
  524. \subsection{\var{\$A} or \var{\$ALIGN}: Align Data}
  525. This switch is recognized for Turbo Pascal Compatibility, but is not
  526. yet implemented. The alignment of data will be different in any case, since
  527. \fpc is a 32-bit compiler.
  528. \subsection{\var{\$B} or \var{\$BOOLEVAL}: Complete boolean evaluation}
  529. This switch is understood by the \fpc compiler, but is ignored. The compiler
  530. always uses shortcut evaluation, i.e. the evaluation of a boolean expression
  531. is stopped once the result of the total exression is known with certainty.
  532. So, in the following example, the function \var{Bofu}, which has a boolean
  533. result, will never get called.
  534. \begin{verbatim}
  535. If False and Bofu then
  536. ...
  537. \end{verbatim}
  538. \subsection{\var{\$D} or \var{\$DEBUGINFO}: Debugging symbols}
  539. When this switch is on (\var{\{\$DEBUGINFO ON\}}),
  540. the compiler inserts GNU debugging information in
  541. the executable. The effect of this switch is the same as the command-line
  542. switch \var{-g}. By default, insertion of debugging information is off.
  543. \subsection{\var{\$E} : Emulation of coprocessor}
  544. This directive controls the emulation of the coprocessor. There is no
  545. command-line counterpart for this directive.
  546. \subsubsection{ Intel x86 version }
  547. When this switch is enabled, all floating point instructions
  548. which are not supported by standard coprocessor emulators will give out
  549. a warning.
  550. The compiler itself doesn't do the emulation of the coprocessor.
  551. To use coprocessor emulation under \dos go32v1 there is nothing special
  552. required, as it is handled automatically.
  553. To use coprocessor emulation under \dos go32v2 you must use the
  554. emu387 unit, which contains correct initialization code for the
  555. emulator.
  556. Under \linux, the kernel takes care of the coprocessor support.
  557. \subsubsection{ Motorola 680x0 version }
  558. When the switch is on, no floating point opcodes are emitted
  559. by the code generator. Instead, internal run-time library routines
  560. are called to do the necessary calculations. In this case all
  561. real types are mapped to the single IEEE floating point type.
  562. \emph{ Remark : } By default, emulation is on. It is possible to
  563. intermix emulation code with real floating point opcodes, as
  564. long as the only type used is single or real.
  565. \subsection{\var{\$G} : Generate 80286 code}
  566. This option is recognised for Turbo Pascal compatibility, but is ignored,
  567. \subsection{\var{\$L} or \var{\$LOCALSYMBOLS}: Local symbol information}
  568. This switch (not to be confused with the \var{\{\$L file\}} file linking
  569. directive) is recognised for Turbo Pascal compatibility, but is ignored.
  570. generation of symbol information is controlled by the \var{\$D} switch.
  571. \subsection{\var{\$M} or \var{\$MEMORY}: Memory sizes}
  572. This switch can be used to set the heap and stacksize. It's format is as
  573. follows:
  574. \begin{verbatim}
  575. {$M StackSize,HeapSize}
  576. \end{verbatim}
  577. Wher \var{StackSize} and \var{HeapSize} should be two integer values,
  578. greater than 1024. The first number sets the size of the stack, and the
  579. second the size of the heap. (Stack setting is ignored under \linux).
  580. The two numbers can be set on the command line using the \var{-Ch}
  581. (and \var{-Cs} switches.
  582. \subsection{\var{\$N} : Numeric processing }
  583. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  584. ignored, since the compiler always uses the coprocessor for floating point
  585. mathematics.
  586. \subsection{\var{\$O} : Overlay code generation }
  587. This switch is recognised for Turbo Pascal compatibility, but is otherwise
  588. ignored.
  589. \subsection{\var{\$Q} \var{\$OVERFLOWCHECKS}: Overflow checking}
  590. The \var{\{\$Q+\}} or \var{\{\$OVERFLOWCHECKS ON\}} directive turns on
  591. integer overflow checking. This means that the compiler inserts code
  592. to check for overflow when doing computations with integers.
  593. When an overflow occurs, the run-time library will print a message
  594. \var{Overflow at xxx}, and exit the program with exit code 215.
  595. \emph{ Remark: } Overflow checking behaviour is not the same as in
  596. Turbo Pascal since all arithmetic operations are done via 32-bit
  597. values. Furthermore, the Inc() and Dec() standard system procedures
  598. \emph{ are } checked for overflow in \fpc, while in Turbo Pascal they
  599. are not.
  600. Using the \var{\{\$Q-\}} switch switches off the overflow checking code
  601. generation.
  602. The generation of overflow checking code can also be controlled
  603. using the \var{-Co} command line compiler option (see \userref).
  604. \subsection{\var{\$R} or \var{\$RANGECHECKS} : Range checking}
  605. By default, the computer doesn't generate code to check the ranges of array
  606. indices, enumeration types, subrange types, etc. Specifying the
  607. \var{\{\$R+\}} switch tells the computer to generate code to check these
  608. indices. If, at run-time, an index or enumeration type is specified that is
  609. out of the declared range of the compiler, then a run-time error is
  610. generated, and the program exits with exit code 201.
  611. The \var{\{\$RANGECHECKS OFF\}} switch tells the compiler not to generate range checking
  612. code. This may result in faulty program behaviour, but no run-time errors
  613. will be generated.
  614. {\em Remark: } Range checking for sets and enumerations are not yet fully
  615. implemented.
  616. \subsection{\var{\$S} : Stack checking}
  617. The \var{\{\$S+\}} directive tells the compiler to generate stack checking
  618. code. This generates code to check if a stack overflow occurred, i.e. to see
  619. whether the stack has grown beyond its maximally allowed size. If the stack
  620. grows beyond the maximum size, then a run-time error is generated, and the
  621. program will exit with exit code 202.
  622. Specifying \var{\{\$S-\}} will turn generation of stack-checking code off.
  623. The command-line compiler switch \var{-Ct} has the same effect as the
  624. \var{\{\$S+\}} directive.
  625. \subsection{\var{\$T} or \var{\$TYPEDADDRESS} : Typed address operator (@)}
  626. In the \var{\{\$T+\}} or \var{\{\$TYPEDADDRESS ON\}} state the @ operator,
  627. when applied to a variable, returns a result of type \var{\^{}T}, if the
  628. type of the variable is \var{T}. In the \var{\{\$T-\}} state, the result is
  629. always an untyped pointer, which is assignment compatible with all other
  630. pointer types.
  631. \subsection{\var{\$X} or \var{\$EXTENDEDSYNTAX} : Extended syntax}
  632. Extended syntax allows you to drop the result of a function. This means that
  633. you can use a function call as if it were a procedure. Standard this feature
  634. is on. You can switch it off using the \var{\{\$X-\}} or
  635. \var{\{\$EXTENDEDSYNTAX OFF\}}directive.
  636. The following, for instance, will not compile :
  637. \begin{verbatim}
  638. function Func (var Arg : sometype) : longint;
  639. begin
  640. ... { declaration of Func }
  641. end;
  642. ...
  643. {$X-}
  644. Func (A);
  645. \end{verbatim}
  646. The reason this construct is supported is that you may wish to call a
  647. function for certain side-effects it has, but you don't need the function
  648. result. In this case you don't need to assign the function result, saving
  649. you an extra variable.
  650. The command-line compiler switch \var{-Sa1} has the same effect as the
  651. \var{\{\$X+\}} directive.
  652. \subsection{\var{\$Y} or \var{\$REFERENCEINFO} : Insert Browser information}
  653. This switch controls the generation of browser inforation. It is recognized
  654. for compatibility with Turbo Pascal and Delphi only, as Browser information
  655. generation is not yet fully supported.
  656. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  657. % Using conditionals and macros
  658. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  659. \chapter{Using conditionals, Messages and macros}
  660. \label{ch:CondMessageMacro}
  661. The \fpc compiler supports conditionals as in normal Turbo Pascal. It does,
  662. however, more than that. It allows you to make macros which can be used in
  663. your code, and it allows you to define messages or errors which will be
  664. displayed when compiling.
  665. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  666. % Conditionals
  667. \section{Conditionals}
  668. \label{se:Conditionals}
  669. The rules for using conditional symbols are the same as under Turbo Pascal.
  670. Defining a symbol goes as follows:
  671. \begin{verbatim}
  672. {$Define Symbol }
  673. \end{verbatim}
  674. From this point on in your code, the compiler know the symbol \var{Symbol}
  675. Symbols are, like the Pascal language, case insensitive.
  676. You can also define a symbol on the command line. the \var{-dSymbol} option
  677. defines the symbol \var{Symbol}. You can specify as many symbols on the
  678. command line as you want.
  679. Undefining an existing symbol is done in a similar way:
  680. \begin{verbatim}
  681. {$Undef Symbol }
  682. \end{verbatim}
  683. If the symbol didn't exist yet, this doesn't do anything. If the symbol
  684. existed previously, the symbol will be erased, and will not be recognized
  685. any more in the code following the \verb|{$Undef ...}| statement.
  686. You can also undefine symbols from the command line with the \var{-u}
  687. command-line switch..
  688. To compile code conditionally, depending on whether a symbol is defined or
  689. not, you can enclose the code in a \verb|{$ifdef Symbol}| .. \verb|{$endif}|
  690. pair. For instance the following code will never be compiled :
  691. \begin{verbatim}
  692. {$Undef MySymbol}
  693. {$ifdef Mysymbol}
  694. DoSomething;
  695. ...
  696. {$endif}
  697. \end{verbatim}
  698. Similarly, you can enclose your code in a \verb|{$Ifndef Symbol}| .. \verb|{$endif}|
  699. pair. Then the code between the pair will only be compiled when the used
  700. symbol doesn't exist. For example, in the following example, the call to the
  701. \var{DoSomething} will always be compiled:
  702. \begin{verbatim}
  703. {$Undef MySymbol}
  704. {$ifndef Mysymbol}
  705. DoSomething;
  706. ...
  707. {$endif}
  708. \end{verbatim}
  709. You can combine the two alternatives in one structure, namely as follows
  710. \begin{verbatim}
  711. {$ifdef Mysymbol}
  712. DoSomething;
  713. {$else}
  714. DoSomethingElse
  715. {$endif}
  716. \end{verbatim}
  717. In this example, if \var{MySymbol} exists, then the call to \var{DoSomething}
  718. will be compiled. If it doesn't exist, the call to \var{DoSomethingElse} is
  719. compiled.
  720. The \fpc compiler defines some symbols before starting to compile your
  721. program or unit. You can use these symbols to differentiate between
  722. different versions of the compiler, and between different compilers.
  723. In \seet{Symbols}, a list of pre-defined symbols is given\footnote{Remark:
  724. The \var{FPK} symbol is still defined for compatibility with older versions.}. In that table,
  725. you should change \var{v} with the version number of the compiler
  726. you're using, \var{r} with the release number and \var{p}
  727. with the patch-number of the compiler. 'OS' needs to be changed by the type
  728. of operating system. Currently this can be one of \var{DOS}, \var{GO32V2},
  729. \var{LINUX}, \var{OS2}, \var{WIN32}, \var{MACOS}, \var{AMIGA} or \var{ATARI}. This symbol is undefined if you
  730. specify a target that is different from the platform you're compiling on.
  731. the \var{-TSomeOS} option on the command line will define the \var{SomeOS} symbol,
  732. and will undefined the existing platform symbol\footnote{In versions prior to
  733. 0.9.4, this didn't happen, thus making Cross-compiling impossible.}.
  734. \begin{FPCltable}{c}{Symbols defined by the compiler.}{Symbols} \hline
  735. Free \\
  736. VER\var{v} \\
  737. VER\var{v}\_\var{r} \\
  738. VER\var{v}\_\var{r}\_\var{p} \\
  739. OS \\ \hline
  740. \end{FPCltable}
  741. As an example : Version 0.9.1 of the compiler, running on a Linux system,
  742. defines the following symbols before reading the command line arguments:
  743. \var{FPC}, \var{VER0}, \var{VER0\_9}, \var{VER0\_9\_1} and \var{LINUX}.
  744. Specifying \var{-TOS2} on the command-line will undefine the \var{LINUX}
  745. symbol, and will define the \var{OS2} symbol.
  746. {\em Remark: } Symbols, even when they're defined in the interface part of
  747. a unit, are not available outside that unit.
  748. \fpc supports the \var{\{\$IFOPT \}} directive for Turbo Pascal
  749. compatibility, but doesn't act on it. It always rejects the condition, so
  750. code between \var{\{\$IFOPT \}} and \var{\{\$Endif\}} is never compiled.
  751. Except for the Turbo Pascal constructs, from version 0.9.8 and higher,
  752. the \fpc compiler also supports a stronger conditional compile mechanism:
  753. The \var{\{\$If \}} construct.
  754. The prototype of this construct is as follows :
  755. \begin{verbatim}
  756. {$If expr}
  757. CompileTheseLines;
  758. {$else}
  759. BetterCompileTheseLines;
  760. {$endif}
  761. \end{verbatim}
  762. In this directive \var{expr} is a Pascal expression which is evaluated using
  763. strings, unless both parts of a comparision can be evaluated as numbers,
  764. in which case they are evaluated using numbers\footnote{Otherwise
  765. \var{\{\$If 8>54} would evaluate to \var{True}}.
  766. If the complemete expression evaluates to \var{'0'}, then it is considered
  767. false and rejected. Otherwise it is considered true and accepted. This may
  768. have unsexpected consequences :
  769. \begin{verbatim}
  770. {$If 0}
  771. \end{verbatim}
  772. Will evaluate to \var{False} and be rejected, while
  773. \begin{verbatim}
  774. {$If 00}
  775. \end{verbatim}
  776. Will evaluate to \var{True}.
  777. You can use any Pascal operator to construct your expression : \var{=, <>,
  778. >, <, >=, <=, AND, NOT, OR} and you can use round brackets to change the
  779. precedence of the operators.
  780. The following example shows you many of the possibilities:
  781. \begin{verbatim}
  782. {$ifdef fpc}
  783. var
  784. y : longint;
  785. {$else fpc}
  786. var
  787. z : longint;
  788. {$endif fpc}
  789. var
  790. x : longint;
  791. begin
  792. {$if (fpc_version=0) and (fpc_release>6) and (fpc_patch>4)}
  793. {$info At least this is version 0.9.5}
  794. {$else}
  795. {$fatalerror Problem with version check}
  796. {$endif}
  797. {$define x:=1234}
  798. {$if x=1234}
  799. {$info x=1234}
  800. {$else}
  801. {$fatalerror x should be 1234}
  802. {$endif}
  803. {$if 12asdf and 12asdf}
  804. {$info $if 12asdf and 12asdf is ok}
  805. {$else}
  806. {$fatalerror $if 12asdf and 12asdf rejected}
  807. {$endif}
  808. {$if 0 or 1}
  809. {$info $if 0 or 1 is ok}
  810. {$else}
  811. {$fatalerror $if 0 or 1 rejected}
  812. {$endif}
  813. {$if 0}
  814. {$fatalerror $if 0 accepted}
  815. {$else}
  816. {$info $if 0 is ok}
  817. {$endif}
  818. {$if 12=12}
  819. {$info $if 12=12 is ok}
  820. {$else}
  821. {$fatalerror $if 12=12 rejected}
  822. {$endif}
  823. {$if 12<>312}
  824. {$info $if 12<>312 is ok}
  825. {$else}
  826. {$fatalerror $if 12<>312 rejected}
  827. {$endif}
  828. {$if 12<=312}
  829. {$info $if 12<=312 is ok}
  830. {$else}
  831. {$fatalerror $if 12<=312 rejected}
  832. {$endif}
  833. {$if 12<312}
  834. {$info $if 12<312 is ok}
  835. {$else}
  836. {$fatalerror $if 12<312 rejected}
  837. {$endif}
  838. {$if a12=a12}
  839. {$info $if a12=a12 is ok}
  840. {$else}
  841. {$fatalerror $if a12=a12 rejected}
  842. {$endif}
  843. {$if a12<=z312}
  844. {$info $if a12<=z312 is ok}
  845. {$else}
  846. {$fatalerror $if a12<=z312 rejected}
  847. {$endif}
  848. {$if a12<z312}
  849. {$info $if a12<z312 is ok}
  850. {$else}
  851. {$fatalerror $if a12<z312 rejected}
  852. {$endif}
  853. {$if not(0)}
  854. {$info $if not(0) is OK}
  855. {$else}
  856. {$fatalerror $if not(0) rejected}
  857. {$endif}
  858. {$info *************************************************}
  859. {$info * Now have to follow at least 2 error messages: *}
  860. {$info *************************************************}
  861. {$if not(0}
  862. {$endif}
  863. {$if not(<}
  864. {$endif}
  865. end.
  866. \end{verbatim}
  867. As you can see from the example, this construct isn't useful when used
  868. with normal symbols, but it is if you use macros, which are explained in
  869. \sees{Macros}, they can be very useful. When trying this example, you must
  870. switch on macro support, with the \var{-Sm} command-line switch.
  871. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  872. % Macros
  873. \section{Messages}
  874. \label{se:Messages}
  875. \fpc lets you define normal, warning and error messages in your code.
  876. Messages can be used to display useful information, such as copyright
  877. notices, a list of symbols that your code reacts on etc.
  878. Warnings can be used if you think some part of your code is still buggy, or
  879. if you think that a certain combination of symbols isn't useful. In general
  880. anything which may cause problems when compiling.
  881. Error messages can be useful if you need a certain symbol to be defined
  882. to warn that a certain variable isn't defined or so, or when the compiler
  883. version isn't suitable for your code.
  884. The compiler treats these messages as if they were generated by the
  885. compiler. This means that if you haven't turned on warning messages, the
  886. warning will not e displayed. Errors are always displayed, and the compiler
  887. stops as if an error had occurred.
  888. For messages, the syntax is as follows :
  889. \begin{verbatim}
  890. {$Message Message text }
  891. \end{verbatim}
  892. Or
  893. \begin{verbatim}
  894. {$Info Message text }
  895. \end{verbatim}
  896. For notes:
  897. \begin{verbatim}
  898. {$Note Message text }
  899. \end{verbatim}
  900. For warnings:
  901. \begin{verbatim}
  902. {$Warning Warning Message text }
  903. \end{verbatim}
  904. For errors :
  905. \begin{verbatim}
  906. {$Error Error Message text }
  907. \end{verbatim}
  908. Lastly, for fatal errors :
  909. \begin{verbatim}
  910. {$FatalError Error Message text }
  911. \end{verbatim}
  912. or
  913. \begin{verbatim}
  914. {$Stop Error Message text }
  915. \end{verbatim}
  916. The difference between \var{\$Error} and \var{\$FatalError} or \var{\$Stop}
  917. messages is that when the compiler encounters an error, it still continues
  918. to compile. With a fatal error, the compiler stops.
  919. {\em Remark :} You cannot use the '\var{\}}' character in your message, since
  920. this will be treated as the closing brace of the message.
  921. As an example, the following piece of code will generate an error when
  922. the symbol \var{RequiredVar} isn't defined:
  923. \begin{verbatim}
  924. {$ifndef RequiredVar}
  925. {$Error Requiredvar isn't defined !}
  926. {$endif}
  927. \end{verbatim}
  928. But the compiler will continue to compile. It will not, however, generate a
  929. unit file or a program (since an error occurred).
  930. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  931. % Macros
  932. \section{Macros}
  933. \label{se:Macros}
  934. Macros are very much like symbols in their syntax, the difference is that
  935. macros have a value whereas a symbol simply is defined or is not defined.
  936. If you want macro support, you need to specify the \var{-Sm} command-line
  937. switch, otherwise your macro will be regarded as a symbol.
  938. Defining a macro in your program is done in the same way as defining a symbol;
  939. in a \var{\{\$define \}} preprocessor statement\footnote{In compiler
  940. versions older than 0.9.8, the assignment operator for a macros wasn't
  941. \var{:=}, but \var{=}}:
  942. \begin{verbatim}
  943. {$define ident:=expr}
  944. \end{verbatim}
  945. If the compiler encounters \var{ident} in the rest of the source file, it
  946. will be replaced immediately by \var{expr}. This replacement works
  947. recursive, meaning that when the compiler expanded one of your macros, it
  948. will look at the resulting expression again to see if another replacement
  949. can be made. You need to be careful with this, because an infinite loop can
  950. occur in this manner.
  951. Here are two examples which illustrate the use of macros:
  952. \begin{verbatim}
  953. {$define sum:=a:=a+b;}
  954. ...
  955. sum { will be expanded to 'a:=a+b;'
  956. remark the absence of the semicolon}
  957. ...
  958. {$define b:=100}
  959. sum { Will be expanded recursively to a:=a+100; }
  960. ...
  961. \end{verbatim}
  962. The previous example could go wrong :
  963. \begin{verbatim}
  964. {$define sum:=a:=a+b;}
  965. ...
  966. sum { will be expanded to 'a:=a+b;'
  967. remark the absence of the semicolon}
  968. ...
  969. {$define b=sum} { DON'T do this !!!}
  970. sum { Will be infinitely recursively expanded... }
  971. ...
  972. \end{verbatim}
  973. On my system, the last example results in a heap error, causing the compiler
  974. to exit with a run-time error 203.
  975. {\em Remark: } Macros defined in the interface part of a unit are not
  976. available outside that unit ! They can just be used as a notational
  977. convenience, or in conditional compiles.
  978. By default, from version 0.9.8 of the compiler on, the compiler predefines three
  979. macros, containing the version number, the release number and the patch
  980. number. They are listed in \seet{DefMacros}.
  981. \begin{FPCltable}{ll}{Predefined macros}{DefMacros} \hline
  982. Symbol & Contains \\ \hline
  983. \var{FPC\_VERSION} & The version number of the compiler. \\
  984. \var{FPC\_RELEASE} & The release number of the compiler. \\
  985. \var{FPC\_PATCH} & The patch number of the compiler. \\
  986. \hline
  987. \end{FPCltable}
  988. {\em Remark: } Don't forget that macros support isn't on by default. You
  989. need to compile with the \var{-Sm} command-line switch.
  990. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  991. % Using assembly language
  992. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  993. \chapter{Using Assembly language}
  994. \label{ch:AsmLang}
  995. \fpc supports inserting of assembler instructions in your code. The
  996. mechanism for this is the same as under Turbo Pascal. There are, however
  997. some substantial differences, as will be explained in the following.
  998. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  999. % Intel syntax
  1000. \section{Intel syntax}
  1001. \label{se:Intel}
  1002. As of version 0.9.7, \fpc supports Intel syntax for the Intel family of Ix86
  1003. processors in it's \var{asm} blocks.
  1004. The Intel syntax in your \var{asm} block is converted to AT\&T syntax by the
  1005. compiler, after which it is inserted in the compiled source.
  1006. The supported assembler constructs are a subset of the normal assembly
  1007. syntax. In what follows we specify what constructs are not supported in
  1008. \fpc, but which exist in Turbo Pascal:
  1009. \begin{itemize}
  1010. \item The \var{TBYTE} qualifier is not supported.
  1011. \item The \var{\&} identifier override is not supported.
  1012. \item The \var{HIGH} operator is not supported.
  1013. \item The \var{LOW} operator is not supported.
  1014. \item The \var{OFFSET} and \var{SEG} operators are not supported.
  1015. use \var{LEA} and the various \var{Lxx} instructions instead.
  1016. \item Expressions with constant strings are not allowed.
  1017. \item Access to record fields via parenthesis is not allowed
  1018. \item Typecasts with normal pascal types are not allowed, only
  1019. recognized assembler typecasts are allowed.\\ Example:
  1020. \begin{verbatim}
  1021. mov al, byte ptr MyWord -- allowed,
  1022. mov al, byte(MyWord) -- allowed,
  1023. mov al, shortint(MyWord) -- not allowed.
  1024. \end{verbatim}
  1025. \item Pascal type typecasts on constants are not allowed. \\
  1026. Example:
  1027. \begin{verbatim}
  1028. const s= 10; const t = 32767;
  1029. \end{verbatim}
  1030. in Turbo Pascal:
  1031. \begin{verbatim}
  1032. mov al, byte(s) -- useless typecast.
  1033. mov al, byte(t) -- syntax error!
  1034. \end{verbatim}
  1035. In this parser, either of those cases will give out a syntax error.
  1036. \item Constant references expressions with constants only are not
  1037. allowed (in all cases they do not work in protected mode,
  1038. under linux i386). \\ Examples:
  1039. \begin{verbatim}
  1040. mov al,byte ptr ['c'] -- not allowed.
  1041. mov al,byte ptr [100h] -- not allowed.
  1042. \end{verbatim}
  1043. (This is due to the limitation of Turbo Assembler).
  1044. \item Brackets within brackets are not allowed
  1045. \item Expressions with segment overrides fully in brackets are
  1046. presently not supported, but they can easily be implemented
  1047. in BuildReference if requested. \\ Example:
  1048. \begin{verbatim}
  1049. mov al,[ds:bx] -- not allowed
  1050. \end{verbatim}
  1051. use instead:
  1052. \begin{verbatim}
  1053. mov al,ds:[bx]
  1054. \end{verbatim}
  1055. \item Possible allowed indexing are as follows:
  1056. \begin{itemize}
  1057. \item \var{Sreg:[REG+REG*SCALING+/-disp]}
  1058. \item \var{SReg:[REG+/-disp]}
  1059. \item \var{SReg:[REG]}
  1060. \item \var{SReg:[REG+REG+/-disp]}
  1061. \item \var{SReg:[REG+REG*SCALING]}
  1062. \end{itemize}
  1063. Where \var{Sreg} is optional and specifies the segment override.
  1064. {\em Notes:}
  1065. \begin{enumerate}
  1066. \item The order of terms is important contrary to Turbo Pascal.
  1067. \item The Scaling value must be a value, and not an identifier
  1068. to a symbol.\\ Examples:
  1069. \begin{verbatim}
  1070. const myscale = 1;
  1071. ...
  1072. mov al,byte ptr [esi+ebx*myscale] -- not allowed.
  1073. \end{verbatim}
  1074. use:
  1075. \begin{verbatim}
  1076. mov al, byte ptr [esi+ebx*1]
  1077. \end{verbatim}
  1078. \end{enumerate}
  1079. \item Possible variable identifier syntax is as follows:
  1080. (Id = Variable or typed constant identifier.)
  1081. \begin{enumerate}
  1082. \item \var{ID}
  1083. \item \var{[ID]}
  1084. \item \var{[ID+expr]}
  1085. \item \var{ID[expr]}
  1086. \end{enumerate}
  1087. Possible fields are as follow:
  1088. \begin{enumerate}
  1089. \item \var{ID.subfield.subfield ...}
  1090. \item \var{[ref].ID.subfield.subfield ...}
  1091. \item \var{[ref].typename.subfield ...}
  1092. \end{enumerate}
  1093. \item Local Labels: Contrary to Turbo Pascal, local labels, must
  1094. at least contain one character after the local symbol indicator.\\
  1095. Example:
  1096. \begin{verbatim}
  1097. @: -- not allowed
  1098. \end{verbatim}
  1099. use instead, for example:
  1100. \begin{verbatim}
  1101. @1: -- allowed
  1102. \end{verbatim}
  1103. \item Contrary to Turbo Pascal local references cannot be used as references,
  1104. only as displacements. \\ example:
  1105. \begin{verbatim}
  1106. lds si,@mylabel -- not allowed
  1107. \end{verbatim}
  1108. \item Contrary to Turbo Pascal, \var{SEGCS}, \var{SEGDS}, \var{SEGES} and
  1109. \var{SEGSS} segment overrides are presently not supported.
  1110. (This is a planned addition though).
  1111. \item Contrary to Turbo Pascal where memory sizes specifiers can
  1112. be practically anywhere, the \fpc Intel inline assembler requires
  1113. memory size specifiers to be outside the brackets. \\
  1114. example:
  1115. \begin{verbatim}
  1116. mov al,[byte ptr myvar] -- not allowed.
  1117. \end{verbatim}
  1118. use:
  1119. \begin{verbatim}
  1120. mov al,byte ptr [myvar] -- allowed.
  1121. \end{verbatim}
  1122. \item Base and Index registers must be 32-bit registers.
  1123. (limitation of the GNU Assembler).
  1124. \item \var{XLAT} is equivalent to \var{XLATB}.
  1125. \item Only Single and Double FPU opcodes are supported.
  1126. \item Floating point opcodes are currently not supported
  1127. (except those which involve only floating point registers).
  1128. \end{itemize}
  1129. The Intel inline assembler supports the following macros :
  1130. \begin{description}
  1131. \item [@Result] represents the function result return value.
  1132. \item [Self] represents the object method pointer in methods.
  1133. \end{description}
  1134. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1135. % AT&T syntax
  1136. \section{AT\&T Syntax}
  1137. \label{se:AttSyntax}
  1138. \fpc uses the \gnu \var{as} assembler to generate its object files for
  1139. the Intel Ix86 processors . Since
  1140. the \gnu assembler uses AT\&T assembly syntax, the code you write should
  1141. use the same syntax. The differences between AT\&T and Intel syntax as used
  1142. in Turbo Pascal are summarized in the following:
  1143. \begin{itemize}
  1144. \item The opcode names include the size of the operand. In general, one can
  1145. say that the AT\&T opcode name is the Intel opcode name, suffixed with a
  1146. '\var{l}', '\var{w}' or '\var{b}' for, respectively, longint (32 bit),
  1147. word (16 bit) and byte (8 bit) memory or register references. As an example,
  1148. the Intel construct \mbox{'\var{mov al bl}} is equivalent to the AT\&T style '\var{movb
  1149. \%bl,\%al}' instruction.
  1150. \item AT\&T immediate operands are designated with '\$', while Intel syntax
  1151. doesn't use a prefix for immediate operands. Thus the Intel construct
  1152. '\var{mov ax, 2}' becomes '\var{movb \$2, \%al}' in AT\&T syntax.
  1153. \item AT\&T register names are preceded by a '\var{\%}' sign.
  1154. They are undelimited in Intel syntax.
  1155. \item AT\&T indicates absolute jump/call operands with '\var{*}', Intel
  1156. syntax doesn't delimit these addresses.
  1157. \item The order of the source and destination operands are switched. AT\&T
  1158. syntax uses '\var{Source, Dest}', while Intel syntax features '\var{Dest,
  1159. Source}'. Thus the Intel construct '\var{add eax, 4}' transforms to
  1160. '\var{addl \$4, \%eax}' in the AT\&T dialect.
  1161. \item Immediate long jumps are prefixed with the '\var{l}' prefix. Thus the
  1162. Intel '\var{call/jmp section:offset'} is transformed to '\var{lcall/ljmp
  1163. \$section,\$offset}'. Similarly the far return is '\var{lret}', instead of the
  1164. Intel '\var{ret far}'.
  1165. \item Memory references are specified differently in AT\&T and Intel
  1166. assembly. The Intel indirect memory reference
  1167. \begin{quote}
  1168. \var{Section:[Base + Index*Scale + Offs]}
  1169. \end{quote}
  1170. is written in AT\&T syntax as :
  1171. \begin{quote}
  1172. \var{Section:Offs(Base,Index,Scale)}
  1173. \end{quote}
  1174. Where \var{Base} and \var{Index} are optional 32-bit base and index
  1175. registers, and \var{Scale} is used to multiply \var{Index}. It can take the
  1176. values 1,2,4 and 8. The \var{Section} is used to specify an optional section
  1177. register for the memory operand.
  1178. \end{itemize}
  1179. More information about the AT\&T syntax can be found in the \var{as} manual,
  1180. although the following differences with normal AT\&T assembly must be taken
  1181. into account :
  1182. \begin{itemize}
  1183. \item Only the following directives are presently supported:
  1184. \begin{description}
  1185. \item[.byte]
  1186. \item[.word]
  1187. \item[.long]
  1188. \item[.ascii]
  1189. \item[.asciz]
  1190. \item[.globl]
  1191. \end{description}
  1192. \item The following directives are recognized but are not
  1193. supported:
  1194. \begin{description}
  1195. \item[.align]
  1196. \item[.lcomm]
  1197. \end{description}
  1198. Eventually they will be supported.
  1199. \item Directives are case sensitive, other identifiers are not case sensitive.
  1200. \item Contrary to GAS local labels/symbols {\em must} start with \var{.L}
  1201. \item The nor operator \var{'!'} is not supported.
  1202. \item String expressions in operands are not supported.
  1203. \item Constant expressions which represent memory references are not
  1204. allowed even though constant immediate value expressions are supported. \\
  1205. examples:
  1206. \begin{verbatim}
  1207. const myid = 10;
  1208. ...
  1209. movl $myid,%eax -- allowed
  1210. movl myid(%esi),%eax -- not allowed.
  1211. \end{verbatim}
  1212. \item When the \var{.globl} directive is found, the symbol following
  1213. it is made public and is immediately emitted.
  1214. Therefore label names with this name will be ignored.
  1215. \item Only Single and Double FPU opcodes are supported.
  1216. \end{itemize}
  1217. The AT\&T inline assembler supports the following macros :
  1218. \begin{description}
  1219. \item [\_\_RESULT] represents the function result return value.
  1220. \item [\_\_SELF] represents the object method pointer in methods.
  1221. \item [\_\_OLDEBP] represents the old base pointer in recusrive routines.
  1222. \end{description}
  1223. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1224. % Calling mechanism
  1225. \section{Calling mechanism}
  1226. \label{se:Calling}
  1227. Procedures and Functions are called with their parameters on the stack.
  1228. Contrary to Turbo Pascal, {\em all} parameters are pushed on the stack, and
  1229. they are pushed {\em right} to {\em left}, instead of left to right for
  1230. Turbo Pascal. This is especially important if you have some assembly
  1231. subroutines in Turbo Pascal which you would like to translate to \fpc.
  1232. Function results are returned in the accumulator, if they fit in the
  1233. register.
  1234. The registers are {\em not} saved when calling a function or procedure. If
  1235. you want to call a procedure or function from assembly language, you must
  1236. save any registers you wish to preserve.
  1237. The first thing a procedure does is saving the base pointer, and setting the
  1238. base pointer equal to the stack pointer. References to the pushed parameters
  1239. and local variables are constructed using the base pointer.
  1240. When the procedure or function exits, it clears the stack.
  1241. When you want your code to be called by a C library or used in a C
  1242. program, you will run into trouble because of this calling mechanism. In C,
  1243. the calling procedure is expected to clear the stack, not the called
  1244. procedure. In other words, the arguments still are on the stack when the
  1245. procedure exits. To avoid this problem, \fpc supports the \var{export}
  1246. modifier. Procedures that are defined using the export modifier, use a
  1247. C-compatible calling mechanism. This means that they can be called from a
  1248. C program or library, or that you can use them as a callback function.
  1249. This also means that you cannot call this procedure or function from your
  1250. own program, since your program uses the Pascal calling convention.
  1251. However, in the exported function, you can of course call other Pascal
  1252. routines.
  1253. As of version 0.9.8, the \fpc compiler supports also the \var{cdecl} and
  1254. \var{stdcall} modifiers, as found in Delphi. The \var{cdecl} modifier does
  1255. the same as the \var{export} modifier, and \var{stdcall} does nothing, since
  1256. \fpc pushes the paramaters from right to left by default.
  1257. In addition to the Delphi \var{cdecl} construct, \fpc also supports the
  1258. \var{popstack} directive; it is nearly the same a the \var{cdecl} directive,
  1259. only it still mangles the name, i.e. makes it into a name such as the
  1260. compiler uses internally.
  1261. All this is summarized in \seet{Calling}. The first column lists the
  1262. modifier you specify for a procedure declaration. The second one lists the
  1263. order the paramaters are pushed on the stack. The third column specifies who
  1264. is responsible for cleaning the stack: the caller or the called function.
  1265. Finally, the last column specifies if registers are used to pass parameters
  1266. to the function.
  1267. \begin{FPCltable}{llll}{Calling mechanisms in \fpc}{Calling}\hline
  1268. Modifier & Pushing order & Stack cleaned by & Parameters in registers \\
  1269. \hline
  1270. (none) & Right-to-left & Function & No \\
  1271. cdecl & Right-to-left & Caller & No \\
  1272. export & Right-to-left & Caller & No \\
  1273. stdcall & Right-to-left & Function & No \\
  1274. popstack & Right-to-left & Caller & No \\ \hline
  1275. \end{FPCltable}
  1276. More about this can be found in \seec{Linking} on linking.
  1277. \subsection{ Ix86 calling conventions }
  1278. Standard entry code for procedures and functions is as follows on the
  1279. x86 architecture:
  1280. \begin{verbatim}
  1281. pushl %ebp
  1282. movl %esp,%ebp
  1283. \end{verbatim}
  1284. The generated exit sequence for procedure and functions looks as follows:
  1285. \begin{verbatim}
  1286. leave
  1287. ret $xx
  1288. \end{verbatim}
  1289. Where \var{xx} is the total size of the pushed parameters.
  1290. To have more information on function return values take a look at the
  1291. \seec{RegConvs} section.
  1292. \subsection{ M680x0 calling conventions }
  1293. Standard entry code for procedures and functions is as follows on the
  1294. 680x0 architecture:
  1295. \begin{verbatim}
  1296. move.l a6,-(sp)
  1297. move.l sp,a6
  1298. \end{verbatim}
  1299. The generated exit sequence for procedure and functions looks as follows:
  1300. \begin{verbatim}
  1301. unlk a6
  1302. move.l (sp)+,a0 ; Get return address
  1303. add.l #xx,sp ; Remove allocated stack
  1304. move.l a0,-(sp) ; Put back return address on top of the stack
  1305. \end{verbatim}
  1306. Where \var{xx} is the total size of the pushed parameters.
  1307. To have more information on function return values take a look at the
  1308. \seec{RegConvs} section.
  1309. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1310. % Telling the compiler what registers have changed
  1311. \section{Signalling changed registers}
  1312. \label{se:RegChanges}
  1313. When the compiler uses variables, it sometimes stores them, or the result of
  1314. some calculations, in the processor registers. If you insert assembler code
  1315. in your program that modifies the processor registers, then this may
  1316. interfere with the compiler's idea about the registers. To avoid this
  1317. problem, \fpc allows you to tell the compiler which registers have changed.
  1318. The compiler will then avoid using these registers. Telling the compiler
  1319. which registers have changed, is done by specifying a set of register names
  1320. behind an assembly block, as follows:
  1321. \begin{verbatim}
  1322. asm
  1323. ...
  1324. end ['R1',...,'Rn'];
  1325. \end{verbatim}
  1326. Here \var{R1} to \var{Rn} are the names of the 32-bit registers you
  1327. modify in your assembly code.
  1328. As an example :
  1329. \begin{verbatim}
  1330. asm
  1331. movl BP,%eax
  1332. movl 4(%eax),%eax
  1333. movl %eax,__RESULT
  1334. end ['EAX'];
  1335. \end{verbatim}
  1336. This example tells the compiler that the \var{EAX} register was modified.
  1337. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1338. % Register conventions
  1339. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1340. \section{Register Conventions}
  1341. \label{se:RegConvs}
  1342. The compiler has different register conventions, depending on the
  1343. target processor used.
  1344. \subsection{ Intel x86 version }
  1345. When optimizations are on, no register can be freely modified, without
  1346. first being saved and then restored. Otherwise, EDI is usually used as
  1347. a scratch register and can be freely used in assembler blocks.
  1348. \subsection{ Motorola 680x0 version }
  1349. Registers which can be freely modified without saving are registers
  1350. D0, D1, D6, A0, A1, and floating point registers FP2 to FP7. All other
  1351. registers are to be considered reserved and should be saved and then
  1352. restored when used in assembler blocks.
  1353. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1354. % Linking issues
  1355. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1356. \chapter{Linking issues}
  1357. \label{ch:Linking}
  1358. When you only use Pascal code, and Pascal units, then you will not see much
  1359. of the part that the linker plays in creating your executable.
  1360. The linker is only called when you compile a program. When compiling units,
  1361. the linker isn't invoked.
  1362. However, there are times that you want to C libraries, or to external
  1363. object files that are generated using a C compiler (or even another pascal
  1364. compiler). The \fpc compiler can generate calls to a C function,
  1365. and can generate functions that can be called from C (exported functions).
  1366. However, these exported functions cannot be called from
  1367. inside Pascal anymore. More on these calling conventions can be found in
  1368. \sees{Calling}.
  1369. In general, there are 2 things you must do to use a function that resides in
  1370. an external library or object file:
  1371. \begin{enumerate}
  1372. \item You must make a pascal declaration of the function or procedure you
  1373. want to use.
  1374. \item You must tell the compiler where the function resides, i.e. in what
  1375. object file or what library, so the compiler can link the necessary code in.
  1376. \end{enumerate}
  1377. The following sections attempt to explain how to do this.
  1378. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1379. % Declaring an external function or procedure
  1380. \section{Declaring an external function or procedure}
  1381. \label{se:ExternalDeclaration}
  1382. The first step in using external code blocks is declaring the function you
  1383. want to use. \fpc supports Delphi syntax, i.e. you must use the
  1384. \var{external} directive.
  1385. There exist four variants of the external direcive :
  1386. \begin{enumerate}
  1387. \item A simple external declaration:
  1388. \begin{verbatim}
  1389. Procedure ProcName (Args : TPRocArgs); external;
  1390. \end{verbatim}
  1391. The \var{external} directive tells the compiler that the function resides in
  1392. an external block of code. You can use this together with the \var{\{\$L \}}
  1393. or \var{\{\$LinkLib \}} directives to link to a function or procedure in a
  1394. library or external object file.
  1395. \item You can give the \var{external} directive a library name as an
  1396. argument:
  1397. \begin{verbatim}
  1398. Procedure ProcName (Args : TPRocArgs); external 'Name';
  1399. \end{verbatim}
  1400. This tells the compiler that the procedure resides in a library with name
  1401. \var{'Name'}. This method is equivalent to the following:
  1402. \begin{verbatim}
  1403. Procedure ProcName (Args : TPRocArgs);external;
  1404. {$LinkLib 'Name'}
  1405. \end{verbatim}
  1406. \item The \var{external} can also be used with two arguments:
  1407. \begin{verbatim}
  1408. Procedure ProcName (Args : TPRocArgs); external 'Name'
  1409. name 'OtherProcName';
  1410. \end{verbatim}
  1411. This has the same meaning as the previous declaration, only the compiler
  1412. will use the name \var{'OtherProcName'} when linking to the library. This
  1413. can be used to give different names to procedures and functions in an
  1414. external library.
  1415. This method is equivalent to the following code:
  1416. \begin{verbatim}
  1417. Procedure OtherProcName (Args : TProcArgs); external;
  1418. {$LinkLib 'Name'}
  1419. Procedure ProcName (Args : TPRocArgs);
  1420. begin
  1421. OtherProcName (Args);
  1422. end;
  1423. \end{verbatim}
  1424. \item Lastly, onder \windows and \ostwo, there is a fourth possibility
  1425. to specify an external function: In \file{.DLL} files, functionas also have
  1426. a unique number (their index). It is possible to refer to these fuctions
  1427. using their index:
  1428. \begin{verbatim}
  1429. Procedure ProcName (Args : TPRocArgs); external 'Name' Index SomeIndex;
  1430. \end{verbatim}
  1431. This tells the compiler that the procedure \var{ProcName} resides in a
  1432. dynamic link library, with index {SomeIndex}.
  1433. \em{Remark:} Note that this is ONLY available under \windows and \ostwo.
  1434. \end{enumerate}
  1435. In earlier versions of the \fpc compiler, the following construct was
  1436. also possible :
  1437. \begin{verbatim}
  1438. Procedure ProcName (Args : TPRocArgs); [ C ];
  1439. \end{verbatim}
  1440. This method is equivalent to the following statement:
  1441. \begin{verbatim}
  1442. Procedure ProcName (Args : TPRocArgs); cdecl; external;
  1443. \end{verbatim}
  1444. However, the \var{[ C ]} directive is no longer supoerted as of version
  1445. 0.99.5 of \fpc, therefore you should use the
  1446. \var{external} directive, with the \var{cdecl} directive, if needed.
  1447. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1448. % Linking an object file in your program
  1449. \section{Linking to an object file}
  1450. \label{se:LinkIn}
  1451. Having declared the external function that resides in an object file,
  1452. you can use it as if it was defined in your own program or unit.
  1453. To produce an executable, you must still link the object file in.
  1454. This can be done with the \var{\{\$L 'file.o'\}} directive.
  1455. This will cause the linker to link in the object file \file{file.o}. On
  1456. \linux systems, this filename is case sensitive. Under \dos, case isn't
  1457. important. Note that \var{file.o} must be in the current directory if you
  1458. don't specify a path. The linker will not search for \file{file.o} if it
  1459. isn't found.
  1460. You cannot specify libraries in this way, it is for object files only.
  1461. Here we present an example. Consider that you have some assembly routine that
  1462. calculates the nth Fibonacci number :
  1463. \begin{verbatim}
  1464. .text
  1465. .align 4
  1466. .globl Fibonacci
  1467. .type Fibonacci,@function
  1468. Fibonacci:
  1469. pushl %ebp
  1470. movl %esp,%ebp
  1471. movl 8(%ebp),%edx
  1472. xorl %ecx,%ecx
  1473. xorl %eax,%eax
  1474. movl $1,%ebx
  1475. incl %edx
  1476. loop:
  1477. decl %edx
  1478. je endloop
  1479. movl %ecx,%eax
  1480. addl %ebx,%eax
  1481. movl %ebx,%ecx
  1482. movl %eax,%ebx
  1483. jmp loop
  1484. endloop:
  1485. movl %ebp,%esp
  1486. popl %ebp
  1487. ret
  1488. \end{verbatim}
  1489. Then you can call this function with the following Pascal Program:
  1490. \begin{verbatim}
  1491. Program FibonacciDemo;
  1492. var i : longint;
  1493. Function Fibonacci (L : longint):longint;cdecl;external;
  1494. {$L fib.o}
  1495. begin
  1496. For I:=1 to 40 do
  1497. writeln ('Fib(',i,') : ',Fibonacci (i));
  1498. end.
  1499. \end{verbatim}
  1500. With just two commands, this can be made into a program :
  1501. \begin{verbatim}
  1502. as -o fib.o fib.s
  1503. pp fibo.pp
  1504. \end{verbatim}
  1505. This example supposes that you have your assembler routine in \file{fib.s},
  1506. and your Pascal program in \file{fibo.pp}.
  1507. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1508. % Linking your program to a library
  1509. \section{Linking to a library}
  1510. \label{se:LinkOut}
  1511. To link your program to a library, the procedure depends on how you declared
  1512. the external procedure. If you used thediffers a little from the
  1513. procedure when you link in an object file. although the declaration step
  1514. remains the same (see \ref{se:ExternalDeclaration} on how to do that).
  1515. In case you used the follwing syntax to declare your procedure:
  1516. \begin{verbatim}
  1517. Procedure ProcName (Args : TPRocArgs); external 'Name';
  1518. \end{verbatim}
  1519. You don't need to take additional steps to link your file in, the compiler
  1520. will do all that is needed for you.
  1521. In case you used
  1522. \begin{verbatim}
  1523. Procedure ProcName (Args : TPRocArgs); external;
  1524. \end{verbatim}
  1525. You still need to explicity link to the library. This can be done in 2 ways:
  1526. \begin{enumerate}
  1527. \item You can tell the compiler in the source file what library to link to
  1528. using the \var{\{\$LinkLib 'Name'\}} directive:
  1529. \begin{verbatim}
  1530. {$LinkLib 'gpm'}
  1531. \end{verbatim}
  1532. This will link to the \file{gpm} library. On \linux systems, you needn't
  1533. specify the extension or 'lib' prefix of the library. The compiler takes
  1534. care of that. On \dos or \windows systems, you need to specify the full
  1535. name.
  1536. \item You can also tell the compiler on the command-line to link in a
  1537. library: The \var{-k} option can be used for that. For example
  1538. \begin{verbatim}
  1539. ppc386 -k'-lgpm' myprog.pp
  1540. \end{verbatim}
  1541. Is equivalent to the above method, and tells the linker to link to the
  1542. \file{gpm} library.
  1543. \end{enumerate}
  1544. As an example; consider the following program :
  1545. \begin{verbatim}
  1546. program printlength;
  1547. {$linklib c} { Case sensitive }
  1548. { Declaration for the standard C function strlen }
  1549. Function strlen (P : pchar) : longint; cdecl;external;
  1550. begin
  1551. Writeln (strlen('Programming is easy !'));
  1552. end.
  1553. \end{verbatim}
  1554. This program can be compiled with :
  1555. \begin{verbatim}
  1556. pp prlen.pp
  1557. \end{verbatim}
  1558. Supposing, of course, that the program source resides in \file{prlen.pp}.
  1559. You cannot use procedures or functions that have a variable number of
  1560. arguments in C. Pascal doesn't support this feature of C.
  1561. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1562. % Making a shared library
  1563. \section{Making a shared library}
  1564. \label{se:SharedLib}
  1565. \fpc supports making shared libraries in a straightforward and easy manner.
  1566. If you want to make libraries for other \fpc programmers, you just need to
  1567. provide a command line switch. If you want C programmers to be able to use
  1568. your code as well, you will need to adapt your code a little. This process
  1569. is described first.
  1570. % Adapting your code
  1571. \subsection{Adapting your code}
  1572. If you want to make your procedures and functions available to C
  1573. programmers, you can do this very easily. All you need to do is declare the
  1574. functions and procedures that you want to make available as \var{Export}, as
  1575. follows:
  1576. \begin{verbatim}
  1577. Procedure ExportedProcedure ; export;
  1578. \end{verbatim}
  1579. This tells the compiler that it shouldn't clear the stack upon exiting the
  1580. procedure (see \sees{Calling}), thus enabling a C program to call your
  1581. function. It also means that your Pascal program can't call this function,
  1582. since it will be using the C calling mechanism.
  1583. {\em Remark :} You can only declare a function as exported in the
  1584. \var{Implementation} section of a unit. This function may {\em not} appear
  1585. in the interface part of a unit. This is logical, since a Pascal routine
  1586. cannot call an exported function, anyway.
  1587. However, the generated object file will not contain the name of the function
  1588. as you declared it. The \fpc compiler ''mangles'' the name you give your
  1589. function. It makes the name all-uppercase, and adds the types of all
  1590. parameters to it. For \fpc units, this doesn't matter, since the \file{.ppu}
  1591. unit file contains all information to map your function declaration onto the
  1592. mangled name in the object file. For a C programmer, who has no access to
  1593. the \var{.ppu} file, this is not very convenient. That is why \fpc
  1594. has the \var{Alias} modifier. The \var{Alias} modifier allows you to specify
  1595. another name (a nickname) for your function or procedure.
  1596. The prototype for an aliased function or procedure is as follows :
  1597. \begin{verbatim}
  1598. Procedure AliasedProc; [ Alias : 'AliasName'];
  1599. \end{verbatim}
  1600. The procedure \var{AliasedProc} will also be known as \var{AliasName}. Take
  1601. care, the name you specify is case sensitive (as C is).
  1602. Of course, you want to combine these two features of \fpc, to export a
  1603. function under a reasonable name; If you want to do that, you must first
  1604. specify that the function is to be exported, and then only declare an alias:
  1605. \begin{verbatim}
  1606. Procedure ExportToCProc; Export; [Alias : 'procname'];
  1607. \end{verbatim}
  1608. After that, any C program will be able to use your procedure or function.
  1609. {\em Remark: }
  1610. If you use in your unit functions that are in other units, or
  1611. system functions, then the C program will need to link in the object files
  1612. from the units too.
  1613. % Compiling libraries
  1614. \subsection {Compiling libraries}
  1615. Once you have your (adapted) code, with exported and other functions,
  1616. you can compile your unit, and tell the compiler to make it into a library.
  1617. The compiler will simply compile your unit, and perform the necessary steps
  1618. to transform it into a \var{static} or \var{shared} (\var{dynamical}) library.
  1619. You can do this as follows, for a dynamical library:
  1620. \begin{verbatim}
  1621. ppc386 -Uld myunit
  1622. \end{verbatim}
  1623. On \linux this will leave you with a file \file{libmyunit.so}. On \windows
  1624. and \ostwo, this will leave you with \file{myunit.dll}.
  1625. If you want a static library, you can do
  1626. \begin{verbatim}
  1627. ppc386 -Uls myunit
  1628. \end{verbatim}
  1629. This will leave you with \file{libmyunit.a} and a file \file{myunit.ppl}.
  1630. The \file{myunit.ppl} is the unit file needed by the \fpc compiler.
  1631. The extension \file{.ppl} means that the file describes a unit that resides
  1632. in a library.
  1633. The resulting files are then libraries. To make static libraries, you need
  1634. the \file{ranlib} or \var{ar} program on your system. It is standard on any
  1635. \linux system, and is provided with the \file{GCC} compiler under \dos.
  1636. {\em BEWARE:} This command doesn't include anything but the current unit in
  1637. thelibrary. Other units are left out, so if you use code from other units,
  1638. you must dpley them together with your library.
  1639. % Moving units
  1640. \subsection{Moving units into a library}
  1641. You can put multiple units into a library with the \var{ppumove} command, as
  1642. follows:
  1643. \begin{verbatim}
  1644. ppumove unit1 unit2 unit3 name
  1645. \end{verbatim}
  1646. This will move 3 units in 1 library (called \file{libname.so} on linux,
  1647. \file{name.dll} on \windows) and it will create 3 files \file{unit1.ppl},
  1648. \file{unit2.ppl} and \file{file3.ppl}, which are unit files, but which tell
  1649. the compiler to look in library \var{name} when linking your executable.
  1650. The \var{ppumove} program has options to create statical or dynammical
  1651. libraries. It is provided with the compiler.
  1652. % unit searching
  1653. \subsection{Unit searching strategy}
  1654. When you compile a program or unit, the compiler will by
  1655. default always look for \file{.ppl} files. If it doesn't find one, it will
  1656. look for a \file{.ppu} file. You can disable this behaviour by
  1657. specifying the \var{-Cs} switch. This tells the compiler to make a static
  1658. binary, and refrains it from looking for units which reside in a library.
  1659. You can tell the compiler only to use dynamic libraries by specifying
  1660. the \var{-Cd} switch; the compiler will then only look for \var{.ppl} files,
  1661. and will give an error if it doesn't find one.
  1662. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1663. % Objects
  1664. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1665. \chapter{Objects}
  1666. \label{ch:Objects}
  1667. In this short chapter we give some technical things about objects. For
  1668. instructions on how to use and declare objects, see \refref.
  1669. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1670. % Constructor and Destructor calls.
  1671. \section{Constructor and Destructor calls}
  1672. \label{se:ConsDest}
  1673. When using objects that need virtual methods, the compiler uses two help
  1674. procedures that are in the run-time library. They are called
  1675. \var{Help\_Destructor} and \var{Help\_Constructor}, and they are written in
  1676. assembly language. They are used to allocate the necessary memory if needed,
  1677. and to insert the Virtual Method Table (VMT) pointer in the newly allocated
  1678. object.
  1679. When the compiler encounters a call to an object's constructor,
  1680. it sets up the stack frame for the call, and inserts a call to the
  1681. \var{Help\_Constructor}
  1682. procedure before issuing the call to the real constructor.
  1683. The helper procedure allocates the needed memory (if needed) and inserts the
  1684. VMT pointer in the object. After that, the real constructor is called.
  1685. A call to \var{Help\_Destructor} is inserted in every destructor declaration,
  1686. just before the destructor's exit sequence.
  1687. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1688. % memory storage of Objects
  1689. \section{Memory storage of objects}
  1690. \label{se:ObjMemory}
  1691. Objects are stored in memory just as ordinary records with an extra field :
  1692. a pointer to the Virtual Method Table (VMT). This field is stored first, and
  1693. all fields in the object are stored in the order they are declared.
  1694. This field is initialized by the call to the object's \var{Constructor} method.
  1695. If the object you defined has no virtual methods, then a \var{nil} is stored
  1696. in the VMT pointer. This ensures that the size of objects is equal, whether
  1697. they have virtual methods ore not.
  1698. The memory allocated looks as in \seet{ObjMem}.
  1699. \begin{FPCltable}{ll}{Object memory layout}{ObjMem} \hline
  1700. Offset & What \\ \hline
  1701. +0 & Pointer to VMT. \\
  1702. +4 & Data. All fields in the order the've been declared. \\
  1703. ... & \\
  1704. \hline
  1705. \end{FPCltable}
  1706. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1707. % The virtual method table.
  1708. \section{The Virtual Method Table}
  1709. \label{se:VMT}
  1710. The Virtual Method Table (VMT) for each object type consists of 2 check
  1711. fields (containing the size of the data), a pointer to the object's anchestor's
  1712. VMT (\var{Nil} if there is no anchestor), and then the pointers to all virtual
  1713. methods. The VMT layout is illustrated in \seet{VMTMem}.
  1714. The VMT is constructed by the compiler. Every instance of an object receives
  1715. a pointer to its VMT.
  1716. \begin{FPCltable}{ll}{Virtual Method Table memory layout}{VMTMem} \hline
  1717. Offset & What \\ \hline
  1718. +0 & Size of object type data \\
  1719. +4 & Minus the size of object type data. Enables determining of valid VMT
  1720. pointers. \\
  1721. +8 & Pointer to ancestor VMT, \var{Nil} if no ancestor available.\\
  1722. +12 & Pointers to the virtual methods. \\
  1723. ... & \\
  1724. \hline
  1725. \end{FPCltable}
  1726. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1727. % Generated code
  1728. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1729. \chapter{Generated code}
  1730. \label{ch:GenCode}
  1731. The \fpc compiler relies on the assembler to make object files. It generates
  1732. just the assembly language file. In the following two sections, we discuss
  1733. what is generated when you compile a unit or a program.
  1734. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1735. % Units
  1736. \section{Units}
  1737. \label{se:Units}
  1738. When you compile a unit, the \fpc compiler generates 2 files :
  1739. \begin{enumerate}
  1740. \item A unit description file (with extension \file{.ppu}).
  1741. \item An assembly language file (with extension \file{.s}).
  1742. \end{enumerate}
  1743. The assembly language file contains the actual source code for the
  1744. statements in your unit, and the necessary memory allocations for any
  1745. variables you use in your unit. This file is converted by the assembler to
  1746. an object file (with extension \file{.o}) which can then be linked to other
  1747. units and your program, to form an executable.
  1748. By default (compiler version 0.9.4 and up), the assembly file is removed
  1749. after it has been compiled. Only in the case of the \var{-s} command-line
  1750. option, the assembly file must be left on disk, so the assembler can be
  1751. called later.
  1752. The unit file contains all the information the compiler needs to use the
  1753. unit:
  1754. \begin{enumerate}
  1755. \item Other used units, both in interface and implementation.
  1756. \item Types and variables from the interface section of the unit.
  1757. \item Function declarations from the interface section of the unit.
  1758. \item Some debugging information, when compiled with debugging.
  1759. \item A date and time stamp.
  1760. \end{enumerate}
  1761. Macros, symbols and compiler directives are {\em not} saved to the unit
  1762. description file. Aliases for functions are also not written to this file,
  1763. which is logical, since they cannot appear in the interface section of a
  1764. unit.
  1765. The detailed contents and structure of this file are described in the first
  1766. appendix. You can examine a unit description file using the \file{dumpppu}
  1767. program, which shows the contents of the file.
  1768. If you want to distribute a unit without source code, you must provide both
  1769. the unit description file and the object file.
  1770. You can also provide a C header file to go with the object file. In that
  1771. case, your unit can be used by someone who wishes to write his programs in
  1772. C. However, you must make this header file yourself since the \fpc compiler
  1773. doesn't make one for you.
  1774. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1775. % Programs
  1776. \section{Programs}
  1777. \label{se:Programs}
  1778. When you compile a program, the compiler produces again 2 files :
  1779. \begin{enumerate}
  1780. \item An assembly language file containing the statements of your program,
  1781. and memory allocations for all used variables.
  1782. \item A linker response file. This file contains a list of object files the
  1783. linker must link together.
  1784. \end{enumerate}
  1785. The link response file is, by default, removed from the disk. Only when you
  1786. specify the \var{-s} command-line option or when linking fails, then the ile
  1787. is left on the disk. It is named \file{link.res}.
  1788. The assembly language file is converted to an object file by the assembler,
  1789. and then linked together with the rest of the units and a program header, to
  1790. form your final program.
  1791. The program header file is a small assembly program which provides the entry
  1792. point for the program. This is where the execution of your program starts,
  1793. so it depends on the operating system, because operating systems pass
  1794. parameters to executables in wildly different ways.
  1795. It's name is \file{prt0.o}, and the
  1796. source file resides in \file{prt0.s} or some variant of this name. It
  1797. usually resided where the system unit source for your system resides.
  1798. It's main function is to save the environment and command-line arguments,
  1799. set up the stack. Then it calls the main program.
  1800. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1801. % MMX Support
  1802. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1803. \chapter{Intel MMX support}
  1804. \label{ch:MMXSupport}
  1805. \section{What is it about ?}
  1806. \label{se:WhatisMMXabout}
  1807. \fpc supports the new MMX (Multi-Media extensions)
  1808. instructions of Intel processors. The idea of MMX is to
  1809. process multiple data with one instruction, for example the processor
  1810. can add simultaneously 4 words. To implement this efficiently, the
  1811. Pascal language needs to be extended. So Free Pascal allows
  1812. to add for example two \var{array[0..3] of word},
  1813. if MMX support is switched on. The operation is done
  1814. by the \var{MMX} unit and allows people without assembler knowledge to take
  1815. advantage of the MMX extensions.
  1816. Here is an example:
  1817. \begin{verbatim}
  1818. uses
  1819. MMX; { include some predefined data types }
  1820. const
  1821. { tmmxword = array[0..3] of word;, declared by unit MMX }
  1822. w1 : tmmxword = (111,123,432,4356);
  1823. w2 : tmmxword = (4213,63456,756,4);
  1824. var
  1825. w3 : tmmxword;
  1826. l : longint;
  1827. begin
  1828. if is_mmx_cpu then { is_mmx_cpu is exported from unit mmx }
  1829. begin
  1830. {$mmx+} { turn mmx on }
  1831. w3:=w1+w2;
  1832. {$mmx-}
  1833. end
  1834. else
  1835. begin
  1836. for i:=0 to 3 do
  1837. w3[i]:=w1[i]+w2[i];
  1838. end;
  1839. end.
  1840. \end{verbatim}
  1841. \section{Saturation support}
  1842. \label{se:SaturationSupport}
  1843. One important point of MMX is the support of saturated operations.
  1844. If a operation would cause an overflow, the value stays at the
  1845. highest or lowest possible value for the data type:
  1846. If you use byte values you get normally 250+12=6. This is very
  1847. annoying when doing color manipulations or changing audio samples,
  1848. when you have to do a word add and check if the value is greater than
  1849. 255. The solution is saturation: 250+12 gives 255.
  1850. Saturated operations are supported by the \var{MMX} unit. If you
  1851. want to use them, you have simple turn the switch saturation on:
  1852. \var{\$saturation+}
  1853. Here is an example:
  1854. \begin{verbatim}
  1855. Program SaturationDemo;
  1856. {
  1857. example for saturation, scales data (for example audio)
  1858. with 1.5 with rounding to negative infinity
  1859. }
  1860. var
  1861. audio1 : tmmxword;
  1862. const
  1863. helpdata1 : tmmxword = ($c000,$c000,$c000,$c000);
  1864. helpdata2 : tmmxword = ($8000,$8000,$8000,$8000);
  1865. begin
  1866. { audio1 contains four 16 bit audio samples }
  1867. {$mmx+}
  1868. { convert it to $8000 is defined as zero, multiply data with 0.75 }
  1869. audio1:=tmmxfixed16(audio1+helpdata2)*tmmxfixed(helpdata1);
  1870. {$saturation+}
  1871. { avoid overflows (all values>$7fff becomes $ffff) }
  1872. audio1:=(audio1+helpdata2)-helpdata2;
  1873. {$saturation-}
  1874. { now mupltily with 2 and change to integer }
  1875. audio1:=(audio1 shl 1)-helpdata2;
  1876. {$mmx-}
  1877. end.
  1878. \end{verbatim}
  1879. \section{Restrictions of MMX support}
  1880. \label{se:MMXrestrictions}
  1881. In the beginning of 1997 the MMX instructions were introduced in the
  1882. Pentium processors, so multitasking systems wouldn't save the
  1883. newly introduced MMX registers. To work around that problem, Intel
  1884. mapped the MMX registers to the FPU register.
  1885. The consequence is that
  1886. you can't mix MMX and floating point operations. After using
  1887. MMX operations and before using floating point operations, you
  1888. have to call the routine \var{EMMS} of the \var{MMX} unit.
  1889. This routine restores the FPU registers.
  1890. {\em careful:} The compiler doesn't warn, if you mix floating point and
  1891. MMX operations, so be careful.
  1892. The MMX instructions are optimized for multi media (what else?).
  1893. So it isn't possible to perform each operation, some opertions
  1894. give a type mismatch, see section \ref {se:SupportedMMX} for the supported
  1895. MMX operations
  1896. An important restriction is that MMX operations aren't range or overflow
  1897. checked, even when you turn range and overflow checking on. This is due to
  1898. the nature of MMX operations.
  1899. The \var{MMX} unit must be always used when doing MMX operations
  1900. because the exit code of this unit clears the MMX unit. If it wouldn't do
  1901. that, other program will crash. A consequence of this is that you can't use
  1902. MMX operations in the exit code of your units or programs, since they would
  1903. interfere with the exit code of the \var{MMX} unit. The compiler can't
  1904. check this, so you are responsible for this !
  1905. \section{Supported MMX operations}
  1906. \label{se:SupportedMMX}
  1907. \section{Optimizing MMX support}
  1908. \label{se:OptimizingMMX}
  1909. Here are some helpful hints to get optimal performance:
  1910. \begin{itemize}
  1911. \item The \var{EMMS} call takes a lot of time, so try to seperate floating
  1912. point and MMX operations.
  1913. \item Use MMX only in low level routines because the compiler
  1914. saves all used MMX registers when calling a subroutine.
  1915. \item The NOT-operator isn't supported natively by MMX, so the
  1916. compiler has to generate a workaround and this operation
  1917. is inefficient.
  1918. \item Simple assignements of floating point numbers don't access
  1919. floating point registers, so you need no call to the \var{EMMS}
  1920. procedure. Only when doing arithmetic, you need to call the \var{EMMS}
  1921. procedure.
  1922. \end{itemize}
  1923. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1924. % Memory issues
  1925. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1926. \chapter{Memory issues}
  1927. \label{ch:Memory}
  1928. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1929. % The 32-bit model
  1930. \section{The 32-bit model.}
  1931. \label{se:ThirtytwoBit}
  1932. The \fpc Pascal compiler issues 32-bit code. This has several consequences:
  1933. \begin{itemize}
  1934. \item You need a 386 processor to run the generated code. The
  1935. compiler functions on a 286 when you compile it using Turbo Pascal,
  1936. but the generated programs cannot be assembled or executed.
  1937. \item You don't need to bother with segment selectors. Memory can be
  1938. addressed using a single 32-bit pointer.
  1939. The amount of memory is limited only by the available amount of (virtual)
  1940. memory on your machine.
  1941. \item The structures you define are unlimited in size. Arrays can be as long
  1942. as you want. You can request memory blocks from any size.
  1943. \end{itemize}
  1944. The fact that 32-bit code is used, means that some of the older Turbo Pascal
  1945. constructs and functions are obsolete. The following is a list of functions
  1946. which shouldn't be used anymore:
  1947. \begin{description}
  1948. \item [Seg()] : Returned the segment of a memory address. Since segments have
  1949. no more meaning, zero is returned in the \fpc run-time library implementation of
  1950. \var{Seg}.
  1951. \item [Ofs()] : Returned the offset of a memory address. Since segments have
  1952. no more meaning, the complete address is returned in the \fpc implementation
  1953. of this function. This has as a consequence that the return type is
  1954. \var{Longint} instead of \var{Word}.
  1955. \item [Cseg(), Dseg()] : Returned, respectively, the code and data segments
  1956. of your program. This returns zero in the \fpc implementation of the
  1957. system unit, since both code and data are in the same memory space.
  1958. \item [Ptr] accepted a segment and offset from an address, and would return
  1959. a pointer to this address. This has been changed in the run-time library.
  1960. Standard it returns now simply the offset. If you want to retain the old
  1961. functionality, you can recompile the run-time library with the
  1962. \var{DoMapping} symbol defined. This will restore the Turbo Pascal
  1963. behaviour.
  1964. \item [memw and mem] these arrays gave access to the \dos memory. \fpc
  1965. supports them, they are mapped into \dos memory space. You need the
  1966. \var{GO32} unit for this.
  1967. \end{description}
  1968. You shouldn't use these functions, since they are very non-portable, they're
  1969. specific to \dos and the ix86 processor. The \fpc compiler is designed to be
  1970. portable to other platforms, so you should keep your code as portable as
  1971. possible, and not system specific. That is, unless you're writing some driver
  1972. units, of course.
  1973. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1974. % The stack
  1975. \section{The stack}
  1976. \label{se:Stack}
  1977. The stack is used to pass parameters to procedures or functions,
  1978. to store local variables, and, in some cases, to return function
  1979. results.
  1980. When a function or procedure is called, then the following is done by the
  1981. compiler :
  1982. \begin{enumerate}
  1983. \item If there are any parameters to be passed to the procedure, they are
  1984. pushed from right to left on the stack.
  1985. \item If a function is called that returns a variable of type \var{String},
  1986. \var{Set}, \var{Record}, \var{Object} or \var{Array}, then an address to
  1987. store the function result in, is pushed on the stack.
  1988. \item If the called procedure or function is an object method, then the
  1989. pointer to \var{self} is pushed on the stack.
  1990. \item If the procedure or function is nested in another function or
  1991. procedure, then the frame pointer of the parent procedure is pushed on the
  1992. stack.
  1993. \item The return address is pushed on the stack (This is done automatically
  1994. by the instruction which calls the subroutine).
  1995. \end{enumerate}
  1996. The resulting stack frame upon entering looks as in \seet{StackFrame}.
  1997. \begin{FPCltable}{llc}{Stack frame when calling a procedure}{StackFrame}
  1998. \hline
  1999. Offset & What is stored & Optional ? \\ \hline
  2000. +x & parameters & Yes \\
  2001. +12 & function result & Yes \\
  2002. +8 & self & Yes \\
  2003. +4 & Frame pointer of parent procedure & Yes \\
  2004. +0 & Return address & No\\ \hline
  2005. \end{FPCltable}
  2006. \subsection{ Intel x86 version }
  2007. The stack is cleared with the \var{ret} I386 instruction, meaning that the
  2008. size of all pushed parameters is limited to 64K.
  2009. \subsubsection{ DOS }
  2010. Under the DOS targets , the default stack is set to 256Kb. This value
  2011. cannot be modified for the GO32V1 target. But this can be modified
  2012. with the GO32V2 target using a special DJGPP utility \var{stubedit}.
  2013. It is to note that the stack size may be changed with some compiler
  2014. switches, this stack size, if \emph{greater} then the default stack
  2015. size will be used instead, otherwise the default stack size is used.
  2016. \subsubsection{ Linux }
  2017. Under Linux, stack size is only limited by the available memory by
  2018. the system.
  2019. \subsubsection{ OS/2 }
  2020. Under OS/2, stack size is determined by one of the runtime
  2021. environment variables set for EMX. Therefore, the stack size
  2022. is user defined.
  2023. \subsection{ Motorola 680x0 version }
  2024. All depending on the processor target, the stack can be cleared in two
  2025. manners, if the target processor is a MC68020 or higher, the stack will
  2026. be cleared with a simple \var{rtd} instruction, meaning that the size
  2027. of all pushed parameters is limited to 32K.
  2028. Otherwise on MC68000/68010 processors, the stack clearing mechanism
  2029. is sligthly more complicated, the exit code will look like this:
  2030. \begin{verbatim}
  2031. {
  2032. move.l (sp)+,a0
  2033. add.l paramsize,a0
  2034. move.l a0,-(sp)
  2035. rts
  2036. }
  2037. \end{verbatim}
  2038. \subsubsection{ Amiga }
  2039. Under AmigaOS, stack size is determined by the user, which sets this
  2040. value using the stack program. Typical sizes range from 4K to 40K.
  2041. \subsubsection{ Atari }
  2042. Under Atari TOS, stack size is currently limited to 8K, and it cannot
  2043. be modified. This may change in a future release of the compiler.
  2044. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2045. % The heap
  2046. \section{The heap}
  2047. \label{se:Heap}
  2048. The heap is used to store all dynamic variables, and to store class
  2049. instances. The interface to the heap is the same as in Turbo Pascal,
  2050. although the effects are maybe not the same. On top of that, the \fpc
  2051. run-time library has some extra possibilities, not available in Turbo
  2052. Pascal. These extra possibilities are explained in the next subsections.
  2053. % The heap grows
  2054. \subsection{The heap grows}
  2055. \fpc supports the \var{HeapEerror} procedural variable. If this variable is
  2056. non-nil, then it is called in case you try to allocate memory, and the heap
  2057. is full. By default, \var{HeapError} points to the \var{GrowHeap} function,
  2058. which tries to increase the heap.
  2059. The growheap function issues a system call to try to increase the size of the
  2060. memory available to your program. It first tries to increase memory in a 1 Mb.
  2061. chunk. If this fails, it tries to increase the heap by the amount you
  2062. requested from the heap.
  2063. If the call to \var{GrowHeap} has failed, then a run-time error is generated,
  2064. or nil is returned, depending on the \var{GrowHeap} result.
  2065. If the call to \var{GrowHeap} was successful, then the needed memory will be
  2066. allocated.
  2067. % Using Blocks
  2068. \subsection{Using Blocks}
  2069. If you need to allocate a lot of small block for a small period, then you
  2070. may want to recompile the run-time library with the \var{USEBLOCKS} symbol
  2071. defined. If it is recompiled, then the heap management is done in a
  2072. different way.
  2073. The run-time library keeps a linked list of allocated blocks with size
  2074. up to 256 bytes\footnote{The size can be set using the \var{max\_size}
  2075. constant in the \file{heap.inc} source file.}. By default, it keeps 32 of
  2076. these lists\footnote{The actual size is \var{max\_size div 8}.}.
  2077. When a piece of memory in a block is deallocated, the heap manager doesn't
  2078. really deallocate the occupied memory. The block is simply put in the linked
  2079. list corresponding to its size.
  2080. When you then again request a block of memory, the manager checks in the
  2081. list if there is a non-allocated block which fits the size you need (rounded
  2082. to 8 bytes). If so, the block is used to allocate the memory you requested.
  2083. This method of allocating works faster if the heap is very fragmented, and
  2084. you allocate a lot of small memory chunks.
  2085. Since it is invisible to the program, this provides an easy way of improving
  2086. the performance of the heap manager.
  2087. % The splitheap
  2088. \subsection{Using the split heap}
  2089. {\em Remark : The split heap is still somewhat buggy. Use at your own risk
  2090. for the moment.}
  2091. The split heap can be used to quickly release a lot of blocks you alloated
  2092. previously.
  2093. Suppose that in a part of your program, you allocate a lot of memory chunks
  2094. on the heap. Suppose that you know that you'll release all this memory when
  2095. this particular part of you program is finished.
  2096. In Turbo Pascal, you could foresee this, and mark the position of the heap
  2097. (using the \var{Mark} function) when entering this particular part of your
  2098. program, and release the occupied memory in one call with the \var{Release}
  2099. call.
  2100. For most purposes, this works very good. But sometimes, you may need to
  2101. allocate something on the heap that you {\em don't} want deallocated when you
  2102. release the allocated memory. That is where the split heap comes in.
  2103. When you split the heap, the heap manager keeps 2 heaps: the base heap (the
  2104. normal heap), and the temporary heap. After the call to split the heap,
  2105. memory is allocated from the temporary heap. When you're finished using all
  2106. this memory, you unsplit the heap. This clears all the memory on the split
  2107. heap with one call. After that, memory will be allocated from the base heap
  2108. again.
  2109. So far, nothing special, nothing that can't be done with calls to \var{mark}
  2110. and \var{release}. Suppose now that you have split the heap, and that you've
  2111. come to a point where you need to allocate memory that is to stay allocated
  2112. after you unsplit the heap again. At this point, mark and release are of no
  2113. use. But when using the split heap, you can tell the heap manager to
  2114. --temporarily-- use the base heap again to allocate memory.
  2115. When you've allocated the needed memory, you can tell the heap manager that
  2116. it should start using the temporary heap again.
  2117. When you're finished using the temporary heap, you release it, and the
  2118. memory you allocated on the base heap will still be allocated.
  2119. To use the split-heap, you must recompile the run-time library with the \var{TempHeap}
  2120. symbol defined.
  2121. This means that the following functions are available :
  2122. \begin{verbatim}
  2123. procedure Split_Heap;
  2124. procedure Switch_To_Base_Heap;
  2125. procedure Switch_To_Temp_Heap;
  2126. procedure Switch_Heap;
  2127. procedure ReleaseTempHeap;
  2128. procedure GetempMem(var p : pointer;size : longint);
  2129. \end{verbatim}
  2130. \var{split\_heap} is used to split the heap. It cannot be called two times
  2131. in a row, without a call to \var{releasetempheap}. \var{Releasetempheap}
  2132. completely releases the memory used by the temporary heap.
  2133. Switching temporarily back to the base heap can be done using the
  2134. \var{switch\_to\_base\_heap} call, and returning to the temporary heap is done
  2135. using the \var{switch\_to\_temp\_heap} call. Switching from one to the other
  2136. without knowing on which one your are right now, can be done using the
  2137. \var{switch\_heap} call, which will split the heap first if needed.
  2138. A call to \var{GetTempMem} will allocate a memory block on the temporary
  2139. heap, whatever the current heap is. The current heap after this call will be
  2140. the temporary heap.
  2141. Typically, what will appear in your code is the following sequence :
  2142. \begin{verbatim}
  2143. Split_Heap
  2144. ...
  2145. { Memory allocation }
  2146. ...
  2147. { !! non-volatile memory needed !!}
  2148. Switch_To_Base_Heap;
  2149. getmem (P,size);
  2150. Switch_To_Temp_Heap;
  2151. ...
  2152. {Memory allocation}
  2153. ...
  2154. ReleaseTempHeap;
  2155. {All allocated memory is now freed, except for the memory pointed to by 'P' }
  2156. ...
  2157. \end{verbatim}
  2158. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2159. % Accessing DOS memory under the GO32 extender
  2160. \section{using \dos memory under the Go32 extender}
  2161. \label{se:AccessingDosMemory}
  2162. Because \fpc is a 32 bit compiler, and uses a \dos extender, accessing DOS
  2163. memory isn't trivial. What follows is an attempt to an explanation of how to
  2164. access and use \dos or real mode memory\footnote{Thanks to an explanation of
  2165. Thomas schatzl (E-mail:\var{tom\_at\[email protected]}).}.
  2166. In {\em Proteced Mode}, memory is accessed through {\em Selectors} and
  2167. {\em Offsets}. You can think of Selectors as the protected mode
  2168. equivalents of segments.
  2169. In \fpc, a pointer is an offset into the \var{DS} selector, which points to
  2170. the Data of your program.
  2171. To access the (real mode) \dos memory, somehow you need a selector that
  2172. points to the \dos memory.
  2173. The \file{GO32} unit provides you with such a selector: The
  2174. \var{DosMemSelector} variable, as it is conveniently called.
  2175. You can also allocate memory in \dos's memory space, using the
  2176. \var{global\_dos\_alloc} function of the \file{GO32} unit.
  2177. This function will allocate memory in a place where \dos sees it.
  2178. As an example, here is a function that returns memory in real mode \dos and
  2179. returns a selector:offset pair for it.
  2180. \begin{verbatim}
  2181. procedure dosalloc(var selector : word;
  2182. var segment : word;
  2183. size : longint);
  2184. var result : longint;
  2185. begin
  2186. result := global_dos_alloc(size);
  2187. selector := word(result);
  2188. segment := word(result shr 16);
  2189. end;
  2190. \end{verbatim}
  2191. (you need to free this memory using the \var{global\_dos\_free} function.)
  2192. You can access any place in memory using a selector. You can get a selector
  2193. using the \var{allocate\_ldt\_descriptor} function, and then let this selector
  2194. point to the physical memory you want using the
  2195. \var{set\_segment\_base\_address} function, and set its length using
  2196. \var{set\_segment\_limit} function.
  2197. You can manipulate the memory pointed to by the selector using the functions
  2198. of the GO32 unit. For instance with the \var{seg\_fillchar} function.
  2199. After using the selector, you must free it again using the
  2200. \var{free\_ldt\_selector} function.
  2201. More information on all this can be found in the \unitsref, the chapter on
  2202. the \file{GO32} unit.
  2203. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2204. % Optimizations done in the compiler
  2205. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2206. \chapter{Optimizations}
  2207. \section{ Non processor specific }
  2208. The following sections describe the general optimizations
  2209. done by the compiler, they are non processor specific. Some
  2210. of these require some compiler switch override while others are done
  2211. automatically (those which require a switch will be noted as such).
  2212. \subsection{ Constant folding }
  2213. In \fpc, if the operand(s) of an operator are constants, they
  2214. will be evaluated at compile time.
  2215. Example
  2216. \begin{verbatim}
  2217. x:=1+2+3+6+5;
  2218. will generate the same code as
  2219. x:=17;
  2220. \end{verbatim}
  2221. Furthermore, if an array index is a constant, the offset will
  2222. be evaluated at compile time. This means that accessing MyData[5]
  2223. is as efficient as accessing a normal variable.
  2224. Finally, calling \var{Chr}, \var{Hi}, \var{Lo}, \var{Ord}, \var{Pred},
  2225. or \var{Succ} functions with constant parameters generates no
  2226. run-time library calls, instead, the values are evaluated at
  2227. compile time.
  2228. \subsection{ Constant merging }
  2229. Using the same constant string two or more times generates only
  2230. one copy of the string constant.
  2231. \subsection{ Short cut evaluation }
  2232. Evaluation of boolean expression stops as soon as the result is
  2233. known, which makes code execute faster then if all boolean operands
  2234. were evaluted.
  2235. \subsection{ Constant set inlining }
  2236. Using the \var{in} operator is always more efficient then using the
  2237. equivalent <>, =, <=, >=, < and > operators. This is because
  2238. range comparisons can be done more easily with \var{in} then with
  2239. normal comparison operators.
  2240. \subsection{ Small sets }
  2241. Sets which contain less then 33 elements can be directly encoded
  2242. using a 32-bit value, therefore no run-time library calls to
  2243. evaluate operands on these sets are required; they are directly encoded
  2244. by the code generator.
  2245. \subsection{ Range checking }
  2246. Assignments of constants to variables are range checked at compile
  2247. time, which removes the need the generation of runtime range checking
  2248. code.
  2249. \emph{Remark:} This feature was not implemented before version
  2250. 0.99.5 of \fpc.
  2251. \subsection{ Shifts instead of multiply or divide }
  2252. When one of the operands in a multiplication is a power of
  2253. two, they are encoded using arithmetic shifts instructions,
  2254. which generates more efficient code.
  2255. Similarly, if the divisor in a \var{div} operation is a power
  2256. of two, it is encoded using arithmetic shifts instructions.
  2257. The same is true when accessing array indexes which are
  2258. powers of two, the address is calculated using arithmetic
  2259. shifts instead of the multiply instruction.
  2260. \subsection{ Automatic alignment }
  2261. By default all variables larger then a byte are guaranteed to be aligned
  2262. at least on a word boundary.
  2263. Furthermore all pointers allocated using the standard runtime
  2264. library (\var{New} and \var{GetMem} among others) are guaranteed
  2265. to return pointers aligned on a quadword boundary (64-bit alignment).
  2266. Alignment of variables on the stack depends on the target processor.
  2267. \emph{ Remark: } Quadword alignment of pointers is not guaranteed
  2268. on systems which don't use an internal heap, such as for the Win32
  2269. target.
  2270. \emph{ Remark: } Alignment is also done \emph{between} fields in
  2271. records, objects and classes, this is \emph{not} the same as
  2272. in Turbo Pascal and may cause problems when using disk I/O with these
  2273. types. To get no alignment between fields use the \var{packed} directive
  2274. or the \var{\{\$PackRecords n\}} switch. For further information, take a
  2275. look at the reference manual under the \var{record} heading.
  2276. \subsection{ Smart linking }
  2277. This feature removes all unreferenced code in the final executable
  2278. file, making the executable file much smaller.
  2279. \emph{ Remark: } Smart linking was implemented starting with
  2280. version 0.99.6 of \fpc.
  2281. \subsection{ Inline routines }
  2282. The following runtime library routines are coded directly into the
  2283. final executable : \var{Lo}, \var{Hi}, \var{High}, \var{Sizeof},
  2284. \var{TypeOf}, \var{Length}, \var{Pred}, \var{Succ}, \var{Inc},
  2285. \var{Dec} and \var{Assigned}.
  2286. \emph{ Remark: } Inline \var{Inc} and \var{Dec} were not completely
  2287. implemented until version 0.99.6 of \fpc.
  2288. \subsection{ Case optimization }
  2289. When using the \var{-Oa} switch, case statements in certain cases will
  2290. be decoded using a jump table, which in certain cases will make the
  2291. case statement execute faster.
  2292. \subsection{ Stack frame omission }
  2293. When using the \var{-Ox} switch, under certain specific conditions,
  2294. the stack frame (entry and exit code for the routine) will be omitted, and
  2295. the variable will directly be accessed via the stack pointer.
  2296. Conditions for omission of the stack frame :
  2297. \begin{itemize}
  2298. \item Routine does not call other routines
  2299. \item Routine does not contain assembler statements
  2300. \item Routine is not declared using the \var{Interrupt} directive
  2301. \item Routine is not a constructor or destructor
  2302. \end{itemize}
  2303. \subsection{ Register variables }
  2304. When using the \var{-Ox} switch, local variables or parameters
  2305. which are used very often will be moved to registers for faster
  2306. access.
  2307. \emph{ Remark: } Register variable allocation is currently
  2308. broken and should not be used.
  2309. \subsection{ Intel x86 specific }
  2310. Here follows a listing of the opimizing techniques used in the compiler:
  2311. \begin{enumerate}
  2312. \item When optimizing for a specific Processor (\var{-O3, -O4, -O5 -O6},
  2313. the following is done:
  2314. \begin{itemize}
  2315. \item In \var{case} statements, a check is done whether a jump table
  2316. or a sequence of conditional jumps should be used for optimal performance.
  2317. \item Determines a number of strategies when doing peephole optimization:
  2318. \var{movzbl (\%ebp), \%eax} on PentiumPro and PII systems will be changed
  2319. into \var{xorl \%eax,\%eax; movb (\%ebp),\%al } for lesser systems.
  2320. \end{itemize}
  2321. Cyrix \var{6x86} processor owners should optimize with \var{-O4} instead of
  2322. \var{-O5}, because \var{-O5} leads to larger code, and thus to smaller
  2323. speed, according to the Cyrix developers FAQ.
  2324. \item When optimizing for speed (\var{-OG}) or size (\var{-Og}), a choice is
  2325. made between using shorter instructions (for size) such as \var{enter \$4},
  2326. or longer instructions \var{subl \$4,\%esp} for speed. When smaller size is
  2327. requested, things aren't aligned on 4-byte boundaries. When speed is
  2328. requested, things are aligned on 4-byte boundaries as much as possible.
  2329. \item Simple optimization (\var{-Oa}) makes sure the peephole optimizer is
  2330. used, as well as the reloading optimizer.
  2331. \item Uncertain optimizations (\var{-Oz}): With this switch, the reloading
  2332. optimizer (enabled with \var{-Oa}) can be forced into making uncertain
  2333. optimizations.
  2334. You can enable uncertain optimizations only in certain cases,
  2335. otherwise you will produce a bug; the following technical description
  2336. tells you when to use them:
  2337. \begin{quote}
  2338. % Jonas's own words..
  2339. \em
  2340. If uncertain optimizations are enabled, the reloading optimizer assumes
  2341. that
  2342. \begin{itemize}
  2343. \item If something is written to a local/global register or a
  2344. procedure/function parameter, this value doesn't overwrite the value to
  2345. which a pointer points.
  2346. \item If something is written to memory pointed to by a pointer variable,
  2347. this value doesn't overwrite the value of a local/global variable or a
  2348. procedure/function parameter.
  2349. \end{itemize}
  2350. % end of quote
  2351. \end{quote}
  2352. The practical upshot of this is that you cannot use the uncertain
  2353. optimizations if you access any local or global variables through pointers. In
  2354. theory, this includes \var{Var} parameters, but it is all right
  2355. if you don't both read the variable once through its \var{Var} reference
  2356. and then read it using it's name.
  2357. The following example will produce bad code when you switch on
  2358. uncertain optimizations:
  2359. \begin{verbatim}
  2360. Var temp: Longint;
  2361. Procedure Foo(Var Bar: Longint);
  2362. Begin
  2363. If (Bar = temp)
  2364. Then
  2365. Begin
  2366. Inc(Bar);
  2367. If (Bar <> temp) then Writeln('bug!')
  2368. End
  2369. End;
  2370. Begin
  2371. Foo(Temp);
  2372. End.
  2373. \end{verbatim}
  2374. The reason it produces bad code is because you access the global variable
  2375. \var{Temp} both through its name \var{Temp} and through a pointer, in this
  2376. case using the \var{Bar} variable parameter, which is nothing but a pointer
  2377. to \var{Temp} in the above code.
  2378. On the other hand, you can use the uncertain optimizations if
  2379. you access global/local variables or parameters through pointers,
  2380. and {\em only} access them through this pointer\footnote{
  2381. You can use multiple pointers to point to the same variable as well, that
  2382. doesn't matter.}.
  2383. For example:
  2384. \begin{verbatim}
  2385. Type TMyRec = Record
  2386. a, b: Longint;
  2387. End;
  2388. PMyRec = ^TMyRec;
  2389. TMyRecArray = Array [1..100000] of TMyRec;
  2390. PMyRecArray = ^TMyRecArray;
  2391. Var MyRecArrayPtr: PMyRecArray;
  2392. MyRecPtr: PMyRec;
  2393. Counter: Longint;
  2394. Begin
  2395. New(MyRecArrayPtr);
  2396. For Counter := 1 to 100000 Do
  2397. Begin
  2398. MyRecPtr := @MyRecArrayPtr^[Counter];
  2399. MyRecPtr^.a := Counter;
  2400. MyRecPtr^.b := Counter div 2;
  2401. End;
  2402. End.
  2403. \end{verbatim}
  2404. Will produce correct code, because the global variable \var{MyRecArrayPtr}
  2405. is not accessed directly, but through a pointer (\var{MyRecPtr} in this
  2406. case).
  2407. In conclusion, one could say that you can use uncertain optimizations {\em
  2408. only} when you know what you're doing.
  2409. \end{enumerate}
  2410. \subsection{ Motorola 680x0 specific }
  2411. Using the \var{-O2} switch does several optimizations in the
  2412. code produced, the most notable being:
  2413. \begin{itemize}
  2414. \item Sign extension from byte to long will use \var{EXTB}
  2415. \item Returning of functions will use \var{RTD}
  2416. \item Range checking will generate no run-time calls
  2417. \item Multiplication will use the long \var{MULS} instruction, no
  2418. runtime library call will be generated
  2419. \item Division will use the long \var{DIVS} instruction, no
  2420. runtime library call will be generated
  2421. \end{itemize}
  2422. \section{ Floating point }
  2423. This is where can be found processor specific information on Floating
  2424. point code generated by the compiler.
  2425. \subsection{ Intel x86 specific }
  2426. All normal floating point types map to their real type, including
  2427. \var{comp} and \var{extended}.
  2428. \subsection{ Motorola 680x0 specific }
  2429. Early generations of the Motorola 680x0 processors did not have integrated
  2430. floating point units, so to circumvent this fact, all floating point
  2431. operations are emulated (when the \var{\$E+} switch ,which is the default)
  2432. using the IEEE \var{Single} floating point type. In other words when
  2433. emulation is on, Real, Single, Double and Extended all map to the
  2434. \var{single} floating point type.
  2435. When the \var{\$E} switch is turned off, normal 68882/68881/68040
  2436. floating point opcodes are emitted. The Real type still maps to
  2437. \var{Single} but the other types map to their true floating point
  2438. types. Only basic FPU opcodes are used, which means that it can
  2439. work on 68040 processors correctly.
  2440. \emph{ Remark: } \var{Double} and \var{Extended} types in true floating
  2441. point mode have not been extensively tested as of version 0.99.5.
  2442. \emph{ Remark: } The \var{comp} data type is currently not supported.
  2443. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2444. % Appendices
  2445. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2446. \appendix
  2447. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2448. % Appendix A
  2449. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2450. \chapter{Anatomy of a unit file}
  2451. \label{ch:AppA}
  2452. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2453. % Basics
  2454. \section{Basics}
  2455. The best and most updated documentation about the ppu files can be found
  2456. in \file{ppu.pas} and \file{ppudump.pp} which can be found in
  2457. \file{rtl/utils/}.
  2458. To read or write the ppufile, you can use the ppu unit \file{ppu.pas}
  2459. which has an object called tppufile which holds all routines that deal
  2460. with ppufile handling. Describing the layout of a ppufile, the methods
  2461. which can be used for it are described.
  2462. A unit file consists of basically five or six parts:
  2463. \begin{enumerate}
  2464. \item A unit header.
  2465. \item A file interface part.
  2466. \item A definition part. Contains all type and procedure definitions.
  2467. \item A symbol part. Contains all symbol names and references to their
  2468. definitions.
  2469. \item A browser part. Contains all references from this unit to other
  2470. units and inside this unit. Only available when the \var{uf\_has\_browser} flag is
  2471. set in the unit flags
  2472. \item A file implementation part (currently unused).
  2473. implementation part.
  2474. \end{enumerate}
  2475. \section{reading ppufiles}
  2476. We will first create an object ppufile which will be used below. We are
  2477. opening unit \file{test.ppu} as an example.
  2478. \begin{verbatim}
  2479. var
  2480. ppufile : pppufile;
  2481. begin
  2482. { Initialize object }
  2483. ppufile:=new(pppufile,init('test.ppu');
  2484. { open the unit and read the header, returns false when it fails }
  2485. if not ppufile.open then
  2486. error('error opening unit test.ppu');
  2487. { here we can read the unit }
  2488. { close unit }
  2489. ppufile.close;
  2490. { release object }
  2491. dispose(ppufile,done);
  2492. end;
  2493. \end{verbatim}
  2494. Note: When a function fails (for example not enough bytes left in an
  2495. entry) it sets the \var{ppufile.error} variable.
  2496. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2497. % The Header
  2498. \section{The Header}
  2499. The header consists of a record containing 24 bytes:
  2500. \begin{verbatim}
  2501. tppuheader=packed record
  2502. id : array[1..3] of char; { = 'PPU' }
  2503. ver : array[1..3] of char;
  2504. compiler : word;
  2505. cpu : word;
  2506. target : word;
  2507. flags : longint;
  2508. size : longint; { size of the ppufile without header }
  2509. checksum : longint; { checksum for this ppufile }
  2510. end;
  2511. \end{verbatim}
  2512. The header is already read by the \var{ppufile.open} command.
  2513. You can access all fields using \var{ppufile.header} which holds
  2514. the current header record.
  2515. \begin{tabular}{lp{10cm}}
  2516. \raggedright
  2517. field & description \\ \hline
  2518. \var{id} &
  2519. this is allways 'PPU', can be checked with
  2520. \mbox{\var{function ppufile.CheckPPUId:boolean;}} \\
  2521. \var{ver} & ppu version, currently '015', can be checked with
  2522. \mbox{\var{function ppufile.GetPPUVersion:longint;}} (returns 15) \\
  2523. \var{compiler}
  2524. & compiler version used to create the unit. Doesn't contain the
  2525. patchlevel. Currently 0.99 where 0 is the high byte and 99 the
  2526. low byte \\
  2527. \var{cpu} & cpu for which this unit is created.
  2528. 0 = i386
  2529. 1 = m68k \\
  2530. \var{target} & target for which this unit is created, this depends also on the
  2531. cpu!
  2532. For i386:
  2533. \begin{tabular}[t]{ll}
  2534. 0 & Go32v1 \\
  2535. 1 & Go32V2 \\
  2536. 2 & Linux-i386 \\
  2537. 3 & OS/2 \\
  2538. 4 & Win32
  2539. \end{tabular}
  2540. For m68k:
  2541. \begin{tabular}[t]{ll}
  2542. 0 & Amiga \\
  2543. 1 & Mac68k \\
  2544. 2 & Atari \\
  2545. 3 & Linux-m68k
  2546. \end{tabular} \\
  2547. \var{flag} &
  2548. the unit flags, contains a combination of the uf\_ constants which
  2549. are definied in \file{ppu.pas} \\
  2550. \var{size} & size of this unit without this header \\
  2551. \var{checksum} &
  2552. checksum of the interface parts of this unit, which determine if
  2553. a unit is changed or not, so other units can see if they need to
  2554. be recompiled
  2555. \\ \hline
  2556. \end{tabular}
  2557. % The sections
  2558. \section{The sections}
  2559. After this header follow the sections. All sections work the same!
  2560. A section contains of entries and is ended with also an entry, but
  2561. containing the specific ibend constant (see \file{ppu.pas} for a list).
  2562. Each entry starts with an entryheader.
  2563. \begin{verbatim}
  2564. tppuentry=packed record
  2565. id : byte;
  2566. nr : byte;
  2567. size : longint;
  2568. end;
  2569. \end{verbatim}
  2570. \begin{tabular}{lp{10cm}}
  2571. field & Description \\ \hline
  2572. id & this is 1 or 2 and can be check if it the entry is correctly
  2573. found. 1 means its a main entry, which says that it is part of the
  2574. basic layout as explained before. 2 toggles that it it a sub entry
  2575. of a record or object \\
  2576. nr & contains the ib constant number which determines what kind of
  2577. entry it is \\
  2578. size & size of this entry without the header, can be used to skip entries
  2579. very easily. \\ \hline
  2580. \end{tabular}
  2581. To read an entry you can simply call \var{ppufile.readentry:byte},
  2582. it returns the
  2583. \var{tppuentry.nr} field, which holds the type of the entry.
  2584. A common way how this works is (example is for the symbols):
  2585. \begin{verbatim}
  2586. repeat
  2587. b:=ppufile.readentry;
  2588. case b of
  2589. ib<etc> : begin
  2590. end;
  2591. ibendsyms : break;
  2592. end;
  2593. until false;
  2594. \end{verbatim}
  2595. Then you can parse each entry type yourself. \var{ppufile.readentry} will take
  2596. care of skipping unread bytes in the entry an read the next entry
  2597. correctly! A special function is \var{skipuntilentry(untilb:byte):boolean;}
  2598. which will read the ppufile until it finds entry \var{untilb} in the main
  2599. entries.
  2600. Parsing an entry can be done with \var{ppufile.getxxx} functions. The
  2601. available functions are:
  2602. \begin{verbatim}
  2603. procedure ppufile.getdata(var b;len:longint);
  2604. function getbyte:byte;
  2605. function getword:word;
  2606. function getlongint:longint;
  2607. function getreal:ppureal;
  2608. function getstring:string;
  2609. \end{verbatim}
  2610. To check if you're at the end of an entry you can use the following
  2611. function:
  2612. \begin{verbatim}
  2613. function EndOfEntry:boolean;
  2614. \end{verbatim}
  2615. {\em notes:}
  2616. \begin{enumerate}
  2617. \item \var{ppureal} is the best real that exists for the cpu where the
  2618. unit is created for. Currently it is \var{extended} for i386 and
  2619. \var{single} for m68k.
  2620. \item the \var{ibobjectdef} and \var{ibrecorddef} have stored a definition
  2621. and symbol section for themselves. So you'll need a recursive call. See
  2622. \file{ppudump.pp} for a correct implementation.
  2623. \end{enumerate}
  2624. A complete list of entries and what their fields contain can be found
  2625. in \file{ppudump.pp}.
  2626. \section{Creating ppufiles}
  2627. Creating a new ppufile works almost the same as writing. First you need
  2628. to init the object and call create:
  2629. \begin{verbatim}
  2630. ppufile:=new(pppufile,'output.ppu');
  2631. ppufile.create;
  2632. \end{verbatim}
  2633. After that you can simply write all needed entries. You'll have to take
  2634. care that you write at least the basic entries for the sections:
  2635. \begin{verbatim}
  2636. ibendinterface
  2637. ibenddefs
  2638. ibendsyms
  2639. ibendbrowser (only when you've set uf_has_browser!)
  2640. ibendimplementation
  2641. ibend
  2642. \end{verbatim}
  2643. Writing an entry is a little different than reading it. You need to first
  2644. put everything in the entry with ppufile.putxxx:
  2645. \begin{verbatim}
  2646. procedure putdata(var b;len:longint);
  2647. procedure putbyte(b:byte);
  2648. procedure putword(w:word);
  2649. procedure putlongint(l:longint);
  2650. procedure putreal(d:ppureal);
  2651. procedure putstring(s:string);
  2652. \end{verbatim}
  2653. After putting all the things in the entry you need to call
  2654. \var{ppufile.writeentry(ibnr:byte)} where \var{ibnr} is the entry number
  2655. you're writing.
  2656. At the end of the file you need to call \var{ppufile.writeheader} to write the
  2657. new header to the file. This takes automatically care of the new size of the
  2658. ppufile. When that is also done you can call \var{ppufile.close} and dispose the
  2659. object.
  2660. Extra functions/variables available for writing are:
  2661. \begin{verbatim}
  2662. ppufile.NewHeader;
  2663. ppufile.NewEntry;
  2664. \end{verbatim}
  2665. This will give you a clean header or entry. Normally called automatically
  2666. in \var{ppufile.writeentry}, so you can't forget it.
  2667. \begin{verbatim}
  2668. ppufile.flush;
  2669. \end{verbatim}
  2670. to flush the current buffers to the disk
  2671. \begin{verbatim}
  2672. ppufile.do_crc:boolean;
  2673. \end{verbatim}
  2674. set to false if you don't want that the crc is updated, this is necessary
  2675. if you write for example the browser data.
  2676. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2677. % Appendix B
  2678. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2679. \chapter{Compiler and RTL source tree structure}
  2680. \label{ch:AppB}
  2681. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2682. % The compiler source tree
  2683. \section{The compiler source tree}
  2684. All compiler source files are in one directory, normally in
  2685. \file{source/compiler}. For more informations
  2686. about the structure of the compiler have a look at the
  2687. Compiler Manual which contains also some informations about
  2688. compiler internals.
  2689. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2690. % Appendix C
  2691. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2692. \chapter{Compiler limits}
  2693. \label{ch:AppC}
  2694. Although many of the restrictions imposed by the MS-DOS system are removed
  2695. by use of an extender, or use of another operating system, there still are
  2696. some limitations to the compiler:
  2697. \begin{enumerate}
  2698. \item Procedure or Function definitions can be nested to a level of 32.
  2699. \item Maximally 255 units can be used in a program when using the real-mode
  2700. compiler. When using the 32-bit compiler, the limit is set to 1024. You can
  2701. change this by redefining the \var{maxunits} constant in the
  2702. \file{files.pas} compiler source file.
  2703. \end{enumerate}
  2704. \end{document}