prog.tex 130 KB

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