prog.tex 135 KB

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