cg.doc 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857
  1. .\" $Header$
  2. .RP
  3. .TL
  4. The table driven code generator from
  5. .br
  6. the Amsterdam Compiler Kit
  7. .AU
  8. Hans van Staveren
  9. .AI
  10. Dept. of Mathematics and Computer Science
  11. Vrije Universiteit
  12. Amsterdam, The Netherlands
  13. .AB
  14. It is possible to automate the process of compiler building
  15. to a great extent using collections of tools.
  16. The Amsterdam Compiler Kit is such a collection of tools.
  17. This document provides a description of the internal workings
  18. of the table driven code generator in the Amsterdam Compiler Kit,
  19. and a description of syntax and semantics of the driving table.
  20. .AE
  21. .NH 1
  22. Introduction
  23. .PP
  24. Part of the Amsterdam Compiler Kit is a code generator system consisting
  25. of a code generator generator (\fIcgg\fP for short) and some machine
  26. independent C code.
  27. .I Cgg
  28. reads a machine description table and creates two files,
  29. tables.h and tables.c.
  30. These are then used together with other C code to produce
  31. a code generator for the machine at hand.
  32. .PP
  33. This in turn reads compact EM code and produces
  34. assembly code.
  35. The remainder of this document will first broadly describe
  36. the working of the code generator,
  37. then a description of the machine table follows after which
  38. the internal workings of the code generator will be explained.
  39. .PP
  40. The reader is assumed to have at least a vague notion about the
  41. semantics of the intermediary EM code.
  42. Someone wishing to write a table for a new machine
  43. should be thoroughly acquainted with EM code
  44. and the assembly code of the machine at hand.
  45. .NH 1
  46. Global overview of the workings of the code generator.
  47. .PP
  48. The code generator or
  49. .I cg
  50. tries to generate good code by simulating the runtime stack
  51. of the program compiled and delaying emission of code as long
  52. as possible.
  53. It also keeps track of register contents, which enables it to
  54. eliminate redundant moves, and tries to eliminate redundant tests
  55. by keeping information about condition code status,
  56. if applicable for the machine.
  57. .PP
  58. .I Cg
  59. maintains a `fakestack' containing `tokens' that are built
  60. by executing the pseudo code contained in the code rules given
  61. by the table writer.
  62. One can think of the fakestack as a logical extension of the real
  63. stack the program compiled will have when run.
  64. During code generation tokens will be kept on the fakestack as long
  65. as possible but when they are moved to the real stack,
  66. by generating code for the push,
  67. all tokens above\u*\d
  68. .FS
  69. * in the rest of this document the stack is assumed to grow downwards,
  70. although the top of the stack will mean the first element that will
  71. be popped.
  72. .FE
  73. the tokens pushed will be pushed also,
  74. so that the fakestack will not contain holes.
  75. .PP
  76. The main loop of
  77. .I cg
  78. is this:
  79. .IP 1)
  80. find a pattern of EM instructions starting at the current one to
  81. generate code for.
  82. This pattern will usually be of length one but longer patterns can be used.
  83. .IP 2)
  84. Select one of the possibly many stack patterns that go with this
  85. EM pattern on the basis of heuristics and/or lookahead.
  86. .IP 3)
  87. Force the current fakestack contents to match the pattern.
  88. This may involve
  89. copying tokens to registers, making dummy transformations, e.g. to
  90. transform a "local" into an "register offsetted" or might even
  91. cause to have the complete fakestack contents put to the real stack
  92. and then back into registers if no suitable transformations
  93. were provided by the table writer.
  94. .IP 4)
  95. Execute the pseudocode associated with the code rule just selected,
  96. this may cause registers to be allocated,
  97. code to be emitted etc..
  98. .IP 5)
  99. Put tokens onto the fakestack to reflect the result of the operation.
  100. .IP 6)
  101. Insert some EM instructions into the stream,
  102. this is possible but not common.
  103. .IP 7)
  104. Account for the cost.
  105. The cost is kept in a (space, time) vector and lookahead decisions
  106. are based on a linear combination of these.
  107. .PP
  108. The table that drives
  109. .I cg
  110. is not read in every time,
  111. but instead is used at compiletime
  112. of
  113. .I cg
  114. to set parameters and to load pseudocode tables.
  115. A program called
  116. .I cgg
  117. reads the table and produces large lists of numbers that are
  118. compiled together with machine independent code to produce
  119. a code generator for the machine at hand.
  120. .NH 1
  121. Description of the machine table
  122. .PP
  123. The machine description table consists of the following sections:
  124. .IP 1)
  125. Constant definitions
  126. .IP 2)
  127. Register definitions
  128. .IP 3)
  129. Token definitions
  130. .IP 4)
  131. Token expression definitions
  132. .IP 5)
  133. Code rules
  134. .IP 6)
  135. Move definitions
  136. .IP 7)
  137. Test definitions
  138. .IP 8)
  139. Stacking definitions
  140. .PP
  141. Input is in free format, white space and newlines may be used
  142. at will to improve legibility.
  143. Identifiers used in the table have the same syntax as C identifiers,
  144. upper and lower case considered different, all characters significant.
  145. There is however one exception:
  146. identifiers must be more than one character long for parsing reasons.
  147. C style comments are accepted
  148. .DS
  149. /* this is a comment */
  150. .DE
  151. and #define macros may be used if the need arises.
  152. .NH 2
  153. Some constants
  154. .PP
  155. Before anything else three constants must be defined,
  156. all with the syntax NAME=value, value being an integer.
  157. These constants are:
  158. .IP EM_WSIZE 10
  159. Number of bytes in a machine word.
  160. This is the number of bytes
  161. a simple \fBloc\fP instruction will put on the stack.
  162. .IP EM_PSIZE
  163. Number of bytes in a pointer.
  164. This is the number of bytes
  165. a \fBlal\fP instruction will put on the stack.
  166. .IP EM_BSIZE
  167. Number of bytes in the hole between AB and LB.
  168. If the calling sequence just saves PC and LB this
  169. size will be twice the pointersize.
  170. .PP
  171. EM_WSIZE and EM_PSIZE are checked when a program is compiled
  172. with the resulting code generator.
  173. EM_BSIZE is used by
  174. .I cg
  175. to add to the offset of instructions dealing with locals
  176. having positive offsets,
  177. i.e. parameters.
  178. .PP
  179. Optionally one can give here the factors with which the size and time
  180. parts of the cost function have to be multiplied to ensure they have the
  181. same order of magnitude.
  182. This can be done as
  183. .DS
  184. TIMEFACTOR = C\d1\u/C\d2\u
  185. SIZEFACTOR = C\d3\u/C\d4\u
  186. .DE
  187. Above numbers must be read as rational numbers.
  188. Defaults are 1/1 for both of them.
  189. These constants set the default size/time tradeoff in the code generator,
  190. so if TIMEFACTOR and SIZEFACTOR are both 1 the code generator will choose
  191. at random between two codesequences where one has
  192. cost (10,4) and the other has cost (8,6).
  193. See also the description of the cost field below.
  194. .PP
  195. Also optional is the definition of a printformat for integers in the codefile.
  196. This is given as
  197. .DS
  198. FORMAT = string
  199. .DE
  200. The default for string is "%d" or "%ld" depending on the wordsize of
  201. the machine. For example on the PDP 11 one can use
  202. .DS
  203. FORMAT= "0%o"
  204. .DE
  205. to satisfy the old UNIX assembler that reads octal unless followed by
  206. a period, and the ACK assembler that follows C conventions.
  207. .NH 2
  208. Register definition
  209. .PP
  210. The next part of the tables describes the various registers of the
  211. machine and defines identifiers
  212. to be used in later parts of the tables.
  213. Example for the PDP-11:
  214. .DS L
  215. REGISTERS:
  216. R0 = ( "r0",2), REG.
  217. R1 = ( "r1",2), REG, ODDREG.
  218. R2 = ( "r2",2), REG.
  219. R3 = ( "r3",2), REG, ODDREG.
  220. R4 = ( "r4",2), REG.
  221. LB = ( "r5",2), LOCALBASE.
  222. R01= ( "r0",4,R0,R1), REGPAIR.
  223. R23= ( "r2",4,R2,R3), REGPAIR.
  224. FR0= ( "r0",4), FREG.
  225. FR1= ( "r1",4), FREG.
  226. FR2= ( "r2",4), FREG.
  227. FR3= ( "r3",4), FREG.
  228. DR0= ( "r0",8,FR0), DREG.
  229. DR1= ( "r1",8,FR1), DREG.
  230. DR2= ( "r2",8,FR2), DREG.
  231. DR3= ( "r3",8,FR3), DREG.
  232. .DE
  233. .PP
  234. The identifier before the '=' sign is the name of the register
  235. as used further on in the table.
  236. The string is the name of the register as far as the assembler is concerned.
  237. The number is the size of the register in bytes.
  238. Identifiers following the number but within the parentheses are previously
  239. defined registernames that are contained in the register being defined.
  240. The identifiers following the closing parenthesis are properties
  241. of the register.
  242. So for example R23 is a register with assembler name r2, 4 bytes long,
  243. contains the registers R2 and R3 and has the property REGPAIR.
  244. .PP
  245. It might seem wise to list each and every property of a register,
  246. so one might give R0 the extra property MFPTREG named after the not
  247. too well known MFPT instruction on newer PDP-11 types,
  248. but this is not a good idea.
  249. Every extra property means the registerset is more unorthogonal
  250. and
  251. .I cg
  252. execution time is influenced by that,
  253. because it has to take into account a larger set of registers
  254. that are not equivalent.
  255. .PP
  256. There is a predefined property SCRATCH that is dynamic,
  257. i.e. a register can have the property SCRATCH one time,
  258. and loose it the next.
  259. A register has the property SCRATCH when it has a reference count of one.
  260. One needs to be able to discriminate between SCRATCH registers
  261. and others,
  262. because it is only allowed to do arithmetic on
  263. SCRATCH registers.
  264. .NH 2
  265. Stack token definition
  266. .PP
  267. The next part describes all possible tokens that can reside on
  268. the fakestack during code generation.
  269. Attributes of a token are described in the form of a C struct declaration,
  270. this is followed by the size in bytes of the token,
  271. optionally followed by the cost of the token when used as an addressing mode
  272. and the format
  273. to be used on output.
  274. .PP
  275. Tokens should usually be declared for every addressing mode
  276. of the machine at hand and for every size directly usable in
  277. a machine instruction.
  278. Example for the PDP-11 (incomplete):
  279. .DS L
  280. TOKENS:
  281. IREG2 = { REGISTER reg; } 2 "*%[reg]" /* indirect register */
  282. REGCONST = { REGISTER reg; STRING off; } 2 /* not really addressable */
  283. REGOFF2 = { REGISTER reg; STRING off; } 2 "%[off](%[reg])"
  284. IREGOFF2 = { REGISTER reg; STRING off; } 2 "*%[off](%[reg])"
  285. CONST = { INT off; } 2 cost=(2,850) "$%[off]."
  286. EXTERN2 = { STRING off; } 2 "%[off]"
  287. IEXTERN2 = { STRING off; } 2 "*%[off]"
  288. PAIRSIGNED = { REGISTER regeven,regodd; } 2 "%[regeven]"
  289. .DE
  290. .PP
  291. Types allowed in the struct are REGISTER, INT and STRING.
  292. Tokens without a printformat should never be output.
  293. .PP
  294. Notice that tokens need not correspond to addressing modes,
  295. the REGCONST token listed above,
  296. meaning the sum of the contents of the register and the constant,
  297. has no corresponding addressing mode on the PDP-11,
  298. but is included so that a sequence of add constant, load indirect,
  299. can be handled efficiently.
  300. This REGCONST token is needed as part of the path
  301. .DS
  302. REGISTER -> REGCONST -> REGOFF
  303. .DE
  304. of which the first and the last "exist" and the middle is needed
  305. only as an intermediate step.
  306. .NH 2
  307. Token expressions
  308. .PP
  309. Usually machines have certain collections of addressing modes that
  310. can be used with certain instructions.
  311. The stack patterns in the table are lists of these collections
  312. and since it is cumbersome to write out these long lists
  313. every time, there is a section here to give names to these
  314. collections.
  315. Please note that it is not forbidden to write out a token expression
  316. in the remainder of the table,
  317. but for clarity it is usually better not to.
  318. Example for the PDP-11 (incomplete):
  319. .DS L
  320. TOKENEXPRESSIONS:
  321. SOURCE2 = REG + IREG2 + REGOFF2 + IREGOFF2 + CONST + EXTERN2 +
  322. IEXTERN2
  323. SREG = REG * SCRATCH
  324. .DE
  325. Permissible in the expressions are all PASCAL set operators, i.e.
  326. .IP +
  327. set union
  328. .IP -
  329. set difference
  330. .IP *
  331. set intersection
  332. .PP
  333. Every tokenidentifier is also a token expression identifier
  334. denoting the singleton collection of tokens containing
  335. just itself.
  336. Every register property as defined above is also a token expression
  337. matching all registers with that property when on the fakestack.
  338. The standard token expression identifier ALL denotes the collection of
  339. all tokens.
  340. .NH 2
  341. Expressions
  342. .PP
  343. Throughout the rest of the table expressions can be used in some
  344. places.
  345. This section will give the syntax and semantics of expressions.
  346. There are four types of expressions: integer, string, register and undefined.
  347. Type checking is performed by
  348. .I cgg .
  349. An operator with at least one undefined operand returns undefined except
  350. for the defined() function mentioned below.
  351. An undefined expression is interpreted as FALSE when it is needed
  352. as a truth value.
  353. Basic terms in an expression are
  354. .IP number 16
  355. A number is a constant of type integer.
  356. .IP "string"
  357. A string within double quotes is a constant of type string.
  358. All the normal C style escapes may be used within the string.
  359. .IP REGIDENT
  360. The name of a register is a constant of type register.
  361. .IP $\fIi\fP
  362. A dollarsign followed by a number is the representation of the argument
  363. of EM instruction \fI\fP.
  364. The type of the operand is dependent on the instruction,
  365. sometimes it is integer,
  366. sometimes it is string.
  367. It is undefined when the instruction has no operand.
  368. .br
  369. Although an exhaustive list could be given describing all the types
  370. the following rule of thumb will suffice.
  371. If you cannot imagine the operand of the instruction ever to be
  372. something different from a plain integer, the type is integer,
  373. otherwise it is string.
  374. .br
  375. .I Cg
  376. makes all necessary conversions for you,
  377. like adding EM_BSIZE to positive arguments of instructions
  378. dealing with locals,
  379. prepending underlines to global names,
  380. converting codelabels into a unique representation etc.
  381. Details about this can be found in the section about
  382. machine dependent C code.
  383. .IP %[1]
  384. This in general means the token mentioned first in the
  385. stack pattern.
  386. When used inside an expression the token must be a simple register.
  387. Type of this is register.
  388. .IP %[1.off]
  389. This means field "off" of the first stack pattern token.
  390. Type is the same as that of field "off".
  391. To use this expression implies a check that all tokens
  392. in the token expression used have the same attributes.
  393. .IP %[1.1]
  394. This is the first subregister of the first token.
  395. Previous comments apply.
  396. .IP %[b]
  397. The second allocated register.
  398. .IP %[a.2]
  399. The second subregister of the first allocated register.
  400. .PP
  401. All normal C operators apply to integers,
  402. the + operator serves for string concatenation
  403. and register expressions can only be compared to each other.
  404. Furthermore there are some special "functions":
  405. .IP tostring(e) 16
  406. Converts an integer expression e to a string.
  407. .IP defined(e)
  408. Returns 1 if expression e is defined, 0 otherwise.
  409. .IP samesign(e1,e2)
  410. Returns 1 if integer expression e1 and e2 have the same sign.
  411. .IP sfit(e1,e2)
  412. Returns 1 if integer expression e1 fits as a signed integer
  413. into a field of e2 bits, 0 otherwise.
  414. .IP ufit(e1,e2)
  415. Same as above but now for unsigned e1.
  416. .IP rom(a,n)
  417. Integer expression giving the n'th argument from the \fBrom\fP descriptor
  418. pointed at by the a'th EM instruction.
  419. Undefined if that descriptor does not exist.
  420. .IP loww(a)
  421. Returns the lower half of the argument of the a'th EM instruction.
  422. This is used to split the arguments of a \fBldc\fP instruction.
  423. .IP highw(a)
  424. Same for upper half.
  425. .NH 2
  426. Code rules
  427. .PP
  428. The largest section of the tables consists of the code generation rules.
  429. They specify EM patterns, stack patterns, code to be generated etc.
  430. Syntax is
  431. .DS L
  432. code rule : EM pattern '|' stack pattern '|' code '|'
  433. stack replacement '|' EM replacement '|' cost ;
  434. .DE
  435. All parts are optional, however there must be at least one pattern present.
  436. If the empattern is missing the rule becomes a rewriting rule or
  437. .I coercion
  438. to be used when code generation cannot continue
  439. because of an invalid stack pattern.
  440. The code rules are preceded by the word
  441. .DS
  442. CODE:
  443. .DE
  444. The next paragraphs describe the various parts in detail.
  445. .NH 3
  446. The EM pattern
  447. .PP
  448. The EM pattern consists of a list of EM mnemonics followed
  449. by a boolean expression.
  450. Examples:
  451. .DS
  452. \fBloe\fP
  453. .DE
  454. will match a single \fBloe\fP instruction,
  455. .DS
  456. \fBloc\fP \fBloc\fP \fBcif\fP $1==2 && $2==8
  457. .DE
  458. is a pattern that will match
  459. .DS
  460. \fBloc\fP 2
  461. \fBloc\fP 8
  462. \fBcif\fP
  463. .DE
  464. and
  465. .DS
  466. \fBlol\fP \fBinc\fP \fBstl\fP $1==$3
  467. .DE
  468. will match for example
  469. .DS
  470. .ta 10m 20m 30m 40m 50m 60m
  471. \fBlol\fP 6 \fBlol\fP -2 \fBlol\fP 4
  472. \fBinc\fP \fBinc\fP but \fInot\fP \fBinc\fP
  473. \fBstl\fP 6 \fBstl\fP -2 \fBstl\fP -4
  474. .DE
  475. A missing boolean expression evaluates to TRUE.
  476. .PP
  477. When the EM pattern is the same as in the previous code rule the pattern
  478. should be given as `...'.
  479. The code generator will match the longest EM pattern on every occasion,
  480. if two patterns of the same length match the first in the table will be chosen,
  481. while all patterns of length greater than or equal to three are considered
  482. to be of the same length.
  483. .NH 3
  484. The stack pattern
  485. .PP
  486. The stack pattern is a list of token expressions,
  487. usually token expression identifiers for clarity.
  488. No boolean expression is allowed here.
  489. The first expression is the one that matches the top of the stack.
  490. .PP
  491. The pattern can be followed by the word STACK
  492. in which case the pattern only matches if there is nothing
  493. else on the fakestack.
  494. The code generator will stack everything not matched at the start
  495. of the rule.
  496. .PP
  497. The pattern can be preceded with the word
  498. .DS
  499. nocoercions:
  500. .DE
  501. which tells the code generator not to try to coerce to the pattern
  502. but only to use it when it is already there.
  503. There are two reasons for this construction,
  504. correctness and speed.
  505. It is needed for correctness when the pattern contains a register
  506. that is not transparent when data is moved through it.
  507. .PP
  508. Example: on the PDP-11 the shortest code for
  509. .DS
  510. \fBlae\fP a
  511. \fBloi\fP 8
  512. \fBlae\fP b
  513. \fBsti\fP 8
  514. .DE
  515. is
  516. .DS
  517. movf _a,fr0
  518. movf fr0,_b
  519. .DE
  520. assuming that the floating point processor is in double
  521. precision mode and fr0 is free.
  522. Unfortunately this is not correct since a trap can occur on certain
  523. kinds of data.
  524. This could happen if there was a pattern for \fBsti\fP\ 8 that allowed
  525. one to move a floating point register not preceded by nocoercions: .
  526. The code generator would then find that moving the 8-byte global _a
  527. to a floating point register and then storing it to _b was the cheapest,
  528. assuming that the space/time knob was turned far enough to space.
  529. It is unfortunate that the type information is no longer present,
  530. since if _a really is a floating point number the move could be
  531. made without error.
  532. .PP
  533. The second reason for the nocoercions: construct is speed.
  534. When the code generator has a long list of possible stack patterns
  535. for one EM pattern it can waste a lot of time trying to find coercions
  536. to all of them, while the mere presence of such a long list
  537. indicates that the table writer has given a lot of special cases.
  538. In this case prepending all the special cases by nocoercions:
  539. will stop the code generator from trying to find things there aren't.
  540. .NH 3
  541. The code part
  542. .PP
  543. The code part consists of three parts, stack cleanup, register allocation
  544. and code to generate.
  545. All of these may be omitted.
  546. .NH 4
  547. Stack cleanup
  548. .PP
  549. The stack cleanup part describes certain stacktokens that should neither remain on
  550. the fakestack, nor remembered as contents of registers.
  551. This is usually only required with store operations.
  552. The entire fakestack, except for the part matched in the stack pattern,
  553. is searched for tokens matching the expression and they are copied
  554. to the real stack.
  555. Every register that contains the stacktoken is marked as empty.
  556. .PP
  557. Syntax is
  558. .DS
  559. remove(token expression) \fIor\fP
  560. remove(token expression, boolean expression)
  561. .DE
  562. Example:
  563. .DS
  564. remove(REGOFF2,%[reg] != LB || %[off] == $1)
  565. .DE
  566. is part of a remove() call for use in the \fBstl\fP code rule.
  567. It removes all register offsetted tokens where the register is not the
  568. localbase plus the local wherein the store is done.
  569. The necessity for this can be seen from the following example:
  570. .DS
  571. \fBlol\fP 4
  572. \fBinl\fP 4
  573. \fBstl\fP 6
  574. .DE
  575. Without a proper remove() call in the rule for \fBinl\fP code would
  576. be generated as here
  577. .DS
  578. inc 4(r5)
  579. mov 4(r5),6(r5)
  580. .DE
  581. so local 6 would be given the new value of local 4 instead of the old
  582. as the EM code prescribed.
  583. .PP
  584. When generating something like a branch instruction it
  585. might be needed to empty the fakestack completely.
  586. This can of course be done with
  587. .DS
  588. remove(ALL)
  589. .DE
  590. .NH 4
  591. Register allocation
  592. .PP
  593. The register allocation part describes the kind of registers needed.
  594. Syntax for allocate() is
  595. .DS
  596. allocate(itemlist)
  597. .DE
  598. where itemlist is a list of three kinds of things:
  599. .IP 1)
  600. a tokendescription, for example %[1].
  601. .br
  602. This will instruct the code generator to temporarily decrement the reference count
  603. of all registers contained in the token,
  604. so that they are available for allocation in this allocate() call
  605. if they were only used in that token.
  606. See example below.
  607. .IP 2)
  608. a register property.
  609. .br
  610. This will allocate a register with that property.
  611. The register will be marked as empty at this point.
  612. Lookahead will be performed if necessary.
  613. .IP 3)
  614. a register property with initialization.
  615. .br
  616. This will allocate the register as in 2) but will also
  617. initialize it.
  618. This eases the task of the code generator because it can
  619. find a register already filled with the right value
  620. if it exists.
  621. .PP
  622. Examples:
  623. .DS
  624. allocate(OREG)
  625. .DE
  626. will allocate an odd register, while
  627. .DS
  628. allocate(REG={REGOFF2,LB,$1})
  629. .DE
  630. will allocate a register while simultaneously filling it with
  631. the asked value.
  632. .br
  633. Inside the coercion from SOURCE2 to REGISTER in the PDP-11 table
  634. the following allocate() can be found.
  635. .DS
  636. allocate(%[1],REG=%[1])
  637. .DE
  638. This tells the code generator that registers contained in %[1] can be used
  639. again and asks to fill the register allocated with %[1].
  640. So if %[1]={REGOFF2,R3,"4"} and R3 has a reference count of 1
  641. the following code might be generated.
  642. .DS
  643. mov 4(r3),r3
  644. .DE
  645. In the rest of the line the registers allocated can be named by
  646. %[a] and %[b.1],%[b.2], i.e. with lower case letters
  647. in order of allocation.
  648. .PP
  649. Warning:
  650. .DS
  651. allocate(R3)
  652. .DE
  653. is \fRnot\fP the way to allocate R3.
  654. R3 is not a register property, so it will be seen as a token description
  655. and the effect is that R3 will have its reference count decremented.
  656. .NH 4
  657. Code
  658. .PP
  659. Code to be generated is specified as a list of items of the following kind:
  660. .IP 1)
  661. a string in double quotes ("This is a string").
  662. .br
  663. This is copied to the codefile and a newline ( \en ) is appended.
  664. Inside the string all normal C string conventions are allowed,
  665. and substitutions can be made of the following sorts.
  666. .RS
  667. .IP a)
  668. $1, $2 etc.
  669. These are the operands of the corresponding EM instructions
  670. and are printed according to their type.
  671. To put a real '$' inside the string it must be doubled ('$$').
  672. .IP b)
  673. %[1], %[2.reg], %[b.1] etc.
  674. These have their obvious meaning.
  675. If they describe a complete token ( %[1] )
  676. the printformat for the token is used.
  677. If they stand for a basic term in an expression
  678. they will be printed according to their type.
  679. To put a real '%' inside the string it must be doubled ('%%').
  680. .IP c)
  681. %( arbitrary expression %).
  682. This allows inclusion of arbitrary expressions inside strings.
  683. Usually not needed very often,
  684. so that the awkward notation is not too bad.
  685. Note that %(%[1]%) is equivalent to %[1].
  686. .RE
  687. .IP 2)
  688. a move() call.
  689. This has the following syntax:
  690. .DS
  691. move(token description, token description)
  692. .DE
  693. Moves are handled specially since that enables the code generator
  694. to keep track of register contents.
  695. Example:
  696. .DS
  697. move(R3,{REGOFF2,LB,$1})
  698. .DE
  699. will generate code to move R3 to $1(r5) except when
  700. R3 already was a copy of $1(r5).
  701. Then the code will be omitted.
  702. The rules describing how to move things to each other
  703. can be found in the MOVES section described below.
  704. .IP 3)
  705. an erase() call.
  706. This has the following syntax:
  707. .DS
  708. erase(register expression)
  709. .DE
  710. This tells the code generator that the register mentioned no longer has any
  711. useful value.
  712. This is
  713. .I necessary
  714. after code in the table has changed the contents of registers.
  715. For example, after an add to a register the register must be erased,
  716. because the contents do no longer match any token.
  717. .IP 4)
  718. For machines that have condition codes,
  719. alas most of them do,
  720. there are provisions to remember condition code setting
  721. and prevent needless testing.
  722. To set the condition code to a token put in the code the following call:
  723. .DS
  724. test(token)
  725. .DE
  726. where token can be all of the standard forms that can also be used in move().
  727. This will generate a test if the condition codes
  728. were not already set to that token.
  729. It is also possible to tell
  730. .I cg
  731. that a certain operation, like a preceding add
  732. has set the condition codes to some token with the call
  733. .DS
  734. setcc(token)
  735. .DE
  736. So a sequence of a setcc and a test on the same token will generate
  737. no code.
  738. Another allowed call within the code is
  739. .DS
  740. samecc
  741. .DE
  742. which tells the code generator that condition codes were unaffected
  743. in this rule.
  744. If no setcc or samecc has been given the default is
  745. .DS
  746. nocc
  747. .DE
  748. when a piece of code contained strings,
  749. which tells the code generator that the condition codes
  750. have no useful value any more.
  751. .NH 3
  752. Stack replacement
  753. .PP
  754. The stack replacement is a possibly empty list of items to be pushed onto
  755. the fakestack. Three kinds of items are possible:
  756. .IP 1)
  757. An item of the form %[1]. This will push the stacktoken mentioned back
  758. onto the stack unchanged.
  759. .IP 2)
  760. A register expression. This will push the register mentioned
  761. onto the fakestack.
  762. .IP 3)
  763. An item of the form { REGOFF2,%[1.reg],$1 }.
  764. This generates a token with tokenidentifier REGOFF2 and attributes
  765. in order of declaration.
  766. .PP
  767. All tokens matched by the stack pattern at the beginning of the code rule
  768. are first removed and their registers deallocated.
  769. Items are pushed in the order of appearance.
  770. This means that the last item will be on the top of the
  771. stack after the push.
  772. So if the stack pattern contained two token expressions
  773. and you want to push them back unchanged,
  774. you have to specify as stack replacement
  775. .DS
  776. %[2] %[1]
  777. .DE
  778. and not the other way around.
  779. .NH 3
  780. EM replacement
  781. .PP
  782. In exceptional cases it might be useful to leave part of an empattern
  783. undone.
  784. For example, a \fBsdl\fP instruction might be split into two \fBstl\fP instructions
  785. when there is no 4-byte quantity on the stack. The emreplacement part allows
  786. one to express this.
  787. Example:
  788. .DS
  789. \fBstl\fP $1 \fBstl\fP $1+2
  790. .DE
  791. The instructions are inserted in the stream so that they can match
  792. the first part of a pattern in the next step.
  793. Note that since the code generator traverses the EM instructions in a strict
  794. linear fashion,
  795. it is impossible to let the EM replacement match later parts of a pattern.
  796. So if there is a pattern
  797. .DS
  798. \fBloc\fP \fBstl\fP $1==0
  799. .DE
  800. and the input is
  801. .DS
  802. \fBloc\fP 0 \fBsdl\fP 4
  803. .DE
  804. the \fBloc\fP\ 0 will be processed first,
  805. then the \fBsdl\fP might be split into two \fBstl\fP's but the pattern
  806. cannot match now.
  807. .NH 3
  808. Cost
  809. .PP
  810. The cost field can be specified when there is more than one
  811. code rule with the same empattern.
  812. If the code generator has a choice between two possibilities
  813. to generate code it will choose the cheapest according to
  814. the cost field.
  815. The cost for a code generation is the sum of the costs
  816. of all the coercions needed, plus the cost for freeing
  817. registers plus the cost of the code rule itself.
  818. .PP
  819. The format of the costfield is
  820. .DS
  821. ( nbytes, time ) or
  822. ( nbytes, time ) + %[\fIi\fP]
  823. .DE
  824. with time in the metric desired, like nanoseconds or states.
  825. See constants section above.
  826. The %[\fIi\fP] in the second example is used for adding the cost of a certain
  827. address mode used in the code generated.
  828. This can of course be repeated if desired.
  829. The cost of the address mode must then be specified in the token definition
  830. section.
  831. .NH 3
  832. Examples
  833. .PP
  834. A list of examples for the PDP-11 is given here.
  835. Far from being complete it gives examples of most kinds
  836. of instructions.
  837. .DS L
  838. \fBadi\fP $1==2 | SREG,SOURCE2 |
  839. "add %[2],%[1]" erase(%[1]) setcc(%[1])
  840. | %[1] | | (2,450) + %[2]
  841. \&... | SOURCE2,SREG |
  842. "add %[1],%[2]" erase(%[2]) setcc(%[2])
  843. | %[2] | | (2,450) + %[1]
  844. .DE
  845. is an example of the use of the `...' construct
  846. and shows how to place erase() and setcc() calls.
  847. .DS L
  848. \fBdvi\fP $1==2 | SOURCE2,SPAIRSIGNED |
  849. "div %[1],%[2]" erase(%[2])
  850. | %[2.regeven] | |
  851. \fBcmi\fP \fBtgt\fP $1==2 | SOURCE2,SOURCE2 | allocate(REG={CONST,0})
  852. "cmp %[2],%[1];ble 1f;inc %[a];1:" erase(%[a])
  853. | %[a] | |
  854. \fBcal\fP | STACK |
  855. "jsr pc,$1"
  856. | | |
  857. \fBlol\fP | | | { REGOFF2, LB, $1 } | |
  858. \fBstl\fP | SOURCE2 |
  859. remove(REGOFF2,%[off]==$1)
  860. move(%[1],{REGOFF2,LB,$1})
  861. | | |
  862. | SOURCE2 |
  863. allocate(%[1],REGPAIR)
  864. move(%[1],%[a.2])
  865. test(%[a.2])
  866. "sxt %[a.even]" | { PAIRSIGNED, %[a.1], %[a.2] }| |
  867. .DE
  868. This coercion shows how to use the move and test calls.
  869. At first you might think that the testcall is unnecessary,
  870. since the move will have set the condition codes,
  871. but the move may never have been executed
  872. if the register already contained the value,
  873. in which case it is necessary to do the test.
  874. If the move was executed the test will be omitted.
  875. .DS L
  876. | SOURCE2 | allocate(%[1],REG=%[1]) | %[a] | |
  877. \fBsdl\fP | SOURCE2 | | %[1] | \fBstl\fP $1 \fBstl\fP $1+2 |
  878. \fBexg\fP $1==2 | SOURCE2 SOURCE2 | | %[1] %[2] | |
  879. .DE
  880. This last example again shows the difference in the order
  881. of the stack pattern and the stack replacement.
  882. .NH 2
  883. Move code rules
  884. .PP
  885. When issuing a move() call as described above or a register allocation
  886. with initialization, the code generator has to know which
  887. instruction to use for the move.
  888. The code will of course only be generated if it cannot be omitted.
  889. This is listed in the move section of the tables by giving a list
  890. of tuples:
  891. .DS
  892. ( source, destination, codepart [ , costfield ] )
  893. .DE
  894. where the square brackets mean the costfield is optional.
  895. Example for the PDP-11
  896. .DS
  897. MOVES:
  898. ( CONST %[off]==0 , SOURCE2, "clr %[2]" )
  899. ( SOURCE2, SOURCE2, "mov %[1],%[2]" )
  900. .DE
  901. The moves are scanned from top to bottom,
  902. so the first one that matches will be chosen.
  903. .NH 2
  904. Test code rules
  905. .PP
  906. When issuing a test() call as described above,
  907. the code generator has to know which instruction
  908. to use for the test.
  909. The code will only be generated if the condition codes
  910. were not already set to the token.
  911. This is listed in the test section of the tables by giving
  912. a list of tuples:
  913. .DS
  914. ( source, codepart [ , costfield ] )
  915. .DE
  916. Example for the PDP-11
  917. .DS
  918. TESTS:
  919. ( SOURCE2, "tst %[1]")
  920. ( DREG, "tstf %[1]\encfcc")
  921. .DE
  922. The tests are scanned from top to bottom,
  923. so the first one that matches will be chosen.
  924. .NH 2
  925. Stacking code rules.
  926. .PP
  927. When the code generator has to stack a token it must know
  928. which code to use.
  929. Since it must at all times be possible to empty the fakestack
  930. even when no registers are free,
  931. it is mandatory that all
  932. tokens used must have a rule attached for stacking them
  933. without using a scratch register.
  934. Since however this might be clumsy and
  935. a register might in practice be available
  936. it is also possible to give rules
  937. which use a register.
  938. On the Intel 8086 for example,
  939. there is no instruction to push a constant without using a register,
  940. and the code needed to do it without, must use global data
  941. and as such is very complicated and wasteful of memory and time.
  942. It can therefore be left to be used in extreme cases,
  943. while in general the constant is pushed through a register.
  944. The stacking rules are listed in the stack section of the table as a list
  945. of tuples:
  946. .DS
  947. (source, [ register property ] , codepart [ , costfield ] )
  948. .DE
  949. Example for the Intel 8086:
  950. .DS
  951. STACKS:
  952. (CONST, REG, move(%[1],%[a]) "push %[a]")
  953. (REG ,, "push %[1]")
  954. .DE
  955. .NH 1
  956. The files mach.h and mach.c
  957. .PP
  958. The table writer must also supply two files containing
  959. machine dependent declarations and C code.
  960. These files are mach.h and mach.c.
  961. .NH 2
  962. Types in the code generator
  963. .PP
  964. Three different types of integer coexist in the code generator
  965. and their range depends on the machine at hand.
  966. The type 'int' is used for things like labelcounters that won't require
  967. more than 16 bits precision.
  968. The type 'word' is used among others to assemble datawords and
  969. is of type 'long' if EM_WSIZE>2.
  970. The type 'full' is used for addresses and is of type 'long' if
  971. EM_WSIZE>2 or EM_PSIZE>2.
  972. .PP
  973. In macro and function definitions in later paragraphs implicit typing
  974. will be used for parameters, that is parameters starting with an 's'
  975. will be of type string, and the letters 'i','w','f' will stand for
  976. int, word and full respectively.
  977. .NH 2
  978. Global variables to work with
  979. .PP
  980. Some global variables are present in the code generator
  981. that can be manipulated by the routines in mach.h and mach.c.
  982. .LP
  983. The declarations are:
  984. .DS L
  985. .ta 20
  986. FILE *codefile; /* code is emitted on this stream */
  987. word part_word; /* words to be output are put together here */
  988. int part_size; /* number of bytes already put in part_word */
  989. char str[]; /* Last string read in */
  990. long argval; /* Last int read and kept */
  991. .DE
  992. .NH 2
  993. Macros in mach.h
  994. .PP
  995. In the file mach.h a collection of macros is defined that have
  996. to do with formatting of assembly code for the machine at hand.
  997. Some of these macros can of course be left undefined in which case the
  998. macro calls are left in the source and will be treated as
  999. function calls.
  1000. These functions can then be defined in \fImach.c\fR.
  1001. .PP
  1002. The macros to be defined are:
  1003. .IP ex_ap(s) 16
  1004. Must print the magic incantations that will mark the symbol \fI\fR
  1005. to be exported to other modules.
  1006. This is the translation of the EM \fBexa\fP and \fBexp\fP instructions.
  1007. .IP in_ap(s)
  1008. Same to import the symbol.
  1009. Translation of \fBina\fP and \fBinp\fP.
  1010. .IP newplb(s)
  1011. Must print the definition of procedure label \fIs\fR.
  1012. If left undefined the newilb() macro is used instead.
  1013. .IP newilb(s)
  1014. Must print the definition of instruction label \fIs\fR.
  1015. .IP newdlb(s)
  1016. Must print the definition of data label \fIs\fR.
  1017. .IP dlbdlb(s1,s2)
  1018. Must define data label
  1019. .I s1
  1020. to be equal to
  1021. .I s2 .
  1022. .IP newlbss(s,f)
  1023. Must declare a piece of memory initialized to BSS_INIT(see below)
  1024. of length
  1025. .I f
  1026. and with label
  1027. .I s .
  1028. .IP cst_fmt
  1029. Format to be used when converting constant arguments of
  1030. EM instructions to string.
  1031. Argument to be formatted will be 'full'.
  1032. .IP off_fmt
  1033. Format to be used for integer part of label+constant,
  1034. argument will be 'full'.
  1035. .IP fmt_ilb(ip,il,s)
  1036. Must use the numbers
  1037. .I ip
  1038. and
  1039. .I il
  1040. which are a procedure number
  1041. and a label number respectively and copy a string to
  1042. .I s
  1043. that must be unique for that combination.
  1044. This procedure is optional, if it is not given ilb_fmt
  1045. must be defined as below.
  1046. .IP ilb_fmt
  1047. Format to be used for creation of unique instruction labels.
  1048. Arguments will be a unique procedure number (int) and the label
  1049. number (int).
  1050. .IP dlb_fmt
  1051. Format to be used for printing numeric data labels.
  1052. Argument will be 'int'.
  1053. .IP hol_fmt
  1054. Format to be used for generation of labels for
  1055. space generated by a
  1056. .B hol
  1057. pseudo.
  1058. Argument will be 'int'.
  1059. .IP hol_off
  1060. Format to be used for printing of the address of an element in
  1061. .B hol
  1062. space.
  1063. Arguments will be the offset in the
  1064. .B hol
  1065. block (word) and the number of the
  1066. .B hol
  1067. (int).
  1068. .IP con_cst(w)
  1069. Must generate output that will assemble into one machineword.
  1070. .IP con_ilb(s)
  1071. Must generate output that will put the address of the instruction label
  1072. into the datastream.
  1073. .IP con_dlb(s)
  1074. Must generate output that will put the address of the data label
  1075. into the datastream.
  1076. .IP fmt_id(sf,st)
  1077. Must take the string in
  1078. .I sf
  1079. which is a nonnumeric global label, and transform it into a copy made to
  1080. .I st
  1081. which will not collide with reserved assembler words and system labels.
  1082. This procedure is optional, if it is not given the id_first macro is used
  1083. as defined below.
  1084. .IP id_first
  1085. Must be a character.
  1086. This is prepended to all nonnumeric global labels if their length
  1087. is shorter than the maximum allowed(currently 8) or if they already
  1088. start with that character.
  1089. This is to avoid conflicts of user labels with system labels.
  1090. .IP BSS_INIT
  1091. Must be a constant.
  1092. This is the value filled in all the words not initialized explicitly.
  1093. This is loader and system dependent.
  1094. If omitted no initialization is assumed.
  1095. .NH 3
  1096. Example mach.h for the PDP-11
  1097. .DS L
  1098. .ta 8 16 24 32 40 48 56
  1099. #define ex_ap(y) fprintf(codefile,"\et.globl %s\en",y)
  1100. #define in_ap(y) /* nothing */
  1101. #define newplb(x) fprintf(codefile,"%s:\en",x)
  1102. #define newilb(x) fprintf(codefile,"%s:\en",x)
  1103. #define newdlb(x) fprintf(codefile,"%s:\en",x)
  1104. #define dlbdlb(x,y) fprintf(codefile,"%s=%s\en",x,y)
  1105. #define newlbss(l,x) fprintf(codefile,"%s:.=.+%d.\en",l,x);
  1106. #define cst_fmt "$%d."
  1107. #define off_fmt "%d."
  1108. #define ilb_fmt "I%02x%x"
  1109. #define dlb_fmt "_%d"
  1110. #define hol_fmt "hol%d"
  1111. #define hol_off "%d.+hol%d"
  1112. #define con_cst(x) fprintf(codefile,"%d.\en",x)
  1113. #define con_ilb(x) fprintf(codefile,"%s\en",x)
  1114. #define con_dlb(x) fprintf(codefile,"%s\en",x)
  1115. #define id_first '_'
  1116. #define BSS_INIT 0
  1117. .DE
  1118. .NH 2
  1119. Functions in mach.c
  1120. .PP
  1121. In mach.c some functions must be supplied,
  1122. mostly manipulating data resulting from pseudoinstructions.
  1123. The specifications are given here,
  1124. implicit typing of parameters as above.
  1125. .IP con_part(isz,word) 20
  1126. This function must manipulate the globals
  1127. part_word and part_size to append the isz bytes
  1128. contained in word to the output stream.
  1129. If part_word is full, i.e. part_size==EM_WSIZE
  1130. the function part_flush() may be called to empty the buffer.
  1131. This is the function that must go through the trouble of
  1132. doing byte order in words correct.
  1133. .IP con_mult(w_size)
  1134. This function must take the string str[] and create an integer
  1135. from the string of size w_size and generate code to assemble global
  1136. data for that integer.
  1137. Only the sizes for which arithmetic is implemented need be
  1138. handled,
  1139. so if you didn't implement 200-byte integer division
  1140. you don't have to implement 200-byte integer global data.
  1141. Here one must take care of word order in long integers.
  1142. .IP con_float()
  1143. This function must generate code to assemble a floating
  1144. point number of which the size is contained in argval
  1145. and the ASCII representation in str[].
  1146. .IP prolog(f_nlocals)
  1147. This function is called at the start of every procedure.
  1148. Function prolog code must be generated,
  1149. and room made for local variables for a total of f_nlocals bytes.
  1150. .IP mes(w_mesno)
  1151. This function is called when a
  1152. .B mes
  1153. pseudo is seen that is not handled by the machine independent part.
  1154. Example below shows all you probably have to know about that.
  1155. .IP segname[]
  1156. This is not a function,
  1157. but an array of four strings.
  1158. These strings are put out whenever the code generator
  1159. switches segments.
  1160. Segments are SEGTXT, SEGCON, SEGROM and SEGBSS in that order.
  1161. .NH 3
  1162. Example mach.c for the PDP-11
  1163. .PP
  1164. As an example of the sort of code expected,
  1165. the mach.c for the PDP-11 is presented here.
  1166. .DS L
  1167. .ta 8 16 24 32 40 48 56 64
  1168. /*
  1169. * machine dependent back end routines for the PDP-11
  1170. */
  1171. con_part(sz,w) register sz; word w; {
  1172. while (part_size % sz)
  1173. part_size++;
  1174. if (part_size == EM_WSIZE)
  1175. part_flush();
  1176. if (sz == 1) {
  1177. w &= 0xFF;
  1178. if (part_size)
  1179. w <<= 8;
  1180. part_word |= w;
  1181. } else {
  1182. assert(sz == 2);
  1183. part_word = w;
  1184. }
  1185. part_size += sz;
  1186. }
  1187. con_mult(sz) word sz; {
  1188. long l;
  1189. if (sz != 4)
  1190. fatal("bad icon/ucon size");
  1191. l = atol(str);
  1192. fprintf(codefile,"\et%o;%o\en",(int)(l>>16),(int)l);
  1193. }
  1194. con_float() {
  1195. double f;
  1196. register short *p,i;
  1197. /*
  1198. * This code is correct only when the code generator is
  1199. * run on a PDP-11 or VAX-11 since it assumes native
  1200. * floating point format is PDP-11 format.
  1201. */
  1202. if (argval != 4 && argval != 8)
  1203. fatal("bad fcon size");
  1204. f = atof(str);
  1205. p = (short *) &f;
  1206. i = *p++;
  1207. if (argval == 8) {
  1208. fprintf(codefile,"\et%o;%o;",i,*p++);
  1209. i = *p++;
  1210. }
  1211. fprintf(codefile,"\et%o;%o\en",i,*p++);
  1212. }
  1213. prolog(nlocals) full nlocals; {
  1214. fprintf(codefile,"mov r5,-(sp)\enmov sp,r5\en");
  1215. if (nlocals == 0)
  1216. return;
  1217. if (nlocals == 2)
  1218. fprintf(codefile,"tst -(sp)\en");
  1219. else
  1220. fprintf(codefile,"sub $%d.,sp\en",nlocals);
  1221. }
  1222. mes(type) word type; {
  1223. int argt ;
  1224. switch ( (int)type ) {
  1225. case ms_ext :
  1226. for (;;) {
  1227. switch ( argt=getarg(
  1228. ptyp(sp_cend)|ptyp(sp_pnam)|sym_ptyp) ) {
  1229. case sp_cend :
  1230. return ;
  1231. default:
  1232. strarg(argt) ;
  1233. fprintf(codefile,".globl %s\en",argstr) ;
  1234. break ;
  1235. }
  1236. }
  1237. default :
  1238. while ( getarg(any_ptyp) != sp_cend ) ;
  1239. break ;
  1240. }
  1241. }
  1242. char *segname[] = {
  1243. ".text", /* SEGTXT */
  1244. ".data", /* SEGCON */
  1245. ".data", /* SEGROM */
  1246. ".bss" /* SEGBSS */
  1247. };
  1248. .DE
  1249. .NH 1
  1250. Coercions
  1251. .PP
  1252. A central part in code generation is taken by the
  1253. .I coercions .
  1254. It is the responsibility of the table writer to provide
  1255. all necessary coercions so that code generation can continue.
  1256. The very minimal set of coercions are
  1257. the coercions to unstack every token expression,
  1258. in combination with the rules to stack every token.
  1259. .PP
  1260. If these are present the code generator can always make the necessary
  1261. transformations by stacking and unstacking.
  1262. Of course for codequality it is usually best to provide extra coercions
  1263. to prevent this stacking to take place.
  1264. .I Cg
  1265. discriminates three types of coercions:
  1266. .IP 1)
  1267. Unstacking coercions.
  1268. This category can use the allocate() call in its code.
  1269. .IP 2)
  1270. Splitting coercions, these are the coercions that split
  1271. larger tokens into smaller ones.
  1272. .IP 3)
  1273. Transforming coercions, these are the coercions that transform
  1274. a token into another one of the same size.
  1275. This category can use the allocate() call in its code.
  1276. .PP
  1277. When a stack configuration does not match the stack pattern
  1278. .I coercions
  1279. are searched for in the following order:
  1280. .IP 1)
  1281. First tokens are split if necessary to get their sizes right.
  1282. .IP 2)
  1283. Then transforming coercions are found that will make the pattern match.
  1284. .IP 3)
  1285. Finally if the stack pattern is longer than the fakestack contents
  1286. unstacking coercions will be used to fill up the pattern.
  1287. .PP
  1288. At any point, when coercions are missing so code generation could not
  1289. continue, the offending tokens are stacked.
  1290. .NH 1
  1291. Internal workings of the code generator.
  1292. .NH 2
  1293. Description of tables.c and tables.h contents
  1294. .PP
  1295. In this section the intermediate files will be described
  1296. that are produced by
  1297. .I cgg
  1298. and compiled with machine independent code to produce a code generator.
  1299. .NH 3
  1300. Tables.c
  1301. .PP
  1302. Tables.c contains a large number of initialized array's of all sorts.
  1303. Description of each follows:
  1304. .br
  1305. .in 1i
  1306. .ti -0.5i
  1307. byte code rules[]
  1308. .br
  1309. Pseudo code interpreted by the code generator.
  1310. Always starts with some opcode followed by operands depending
  1311. on the opcode.
  1312. Integers in this table are between 0 and 32767 and have a one byte
  1313. encoding if between 0 and 127.
  1314. .ti -0.5i
  1315. char stregclass[]
  1316. .br
  1317. Number of computed static register class per register.
  1318. Two registers are in the same class if they have the same properties
  1319. and don't share a common subregister.
  1320. .ti -0.5i
  1321. struct reginfo machregs[]
  1322. .br
  1323. Info per register.
  1324. Initialized with representation string, size,
  1325. members of the register and set of registers affected when this
  1326. one is changed.
  1327. Also contains room for runtime information,
  1328. like contents and reference count.
  1329. .ti -0.5i
  1330. tkdef_t tokens[]
  1331. .br
  1332. Information per tokentype.
  1333. Initialized with size, cost, type of operands and formatstring.
  1334. .ti -0.5i
  1335. node_t enodes[]
  1336. .br
  1337. List of triples representing expressions for the code generator.
  1338. .ti -0.5i
  1339. string code strings[]
  1340. .br
  1341. List of strings.
  1342. All strings are put in a list and checked for duplication,
  1343. so only one copy per string will reside here.
  1344. .ti -0.5i
  1345. set_t machsets[]
  1346. .br
  1347. List of token expression sets.
  1348. Bit 0 of the set is used for the SCRATCH property of registers,
  1349. bit 1 upto NREG are for the corresponding registers
  1350. and bit NREG+1 upto the end are for corresponding tokens.
  1351. .ti -0.5i
  1352. inst_t tokeninstances[]
  1353. .br
  1354. List of descriptions for building tokens.
  1355. Contains type of rule for building one,
  1356. plus operands depending on the type.
  1357. .ti -0.5i
  1358. move_t moves[]
  1359. .br
  1360. List of move rules.
  1361. Contains token expressions for source and destination
  1362. plus cost and index for code rule.
  1363. .ti -0.5i
  1364. byte pattern[]
  1365. .br
  1366. EM patterns.
  1367. This is structured internally as chains of patterns,
  1368. each chain pointed at by pathash[].
  1369. After each pattern the list of possible code rules is given.
  1370. .ti -0.5i
  1371. int pathash[256]
  1372. .br
  1373. Indices into pattern[] for all patterns with a certain low order
  1374. byte of the hashing function.
  1375. .ti -0.5i
  1376. c1_t c1coercs[]
  1377. .br
  1378. List of rules to stack tokens.
  1379. Contains token expressions,
  1380. register needed,
  1381. cost
  1382. and code rule.
  1383. .ti -0.5i
  1384. c2_t c2coercs[]
  1385. .br
  1386. List of splitting coercions.
  1387. Token expressions,
  1388. split factor,
  1389. replacements
  1390. and code rule.
  1391. .ti -0.5i
  1392. c3_t c3coercs[]
  1393. .br
  1394. List of one to one coercions.
  1395. Token expressions,
  1396. register needed,
  1397. replacement
  1398. and code rule.
  1399. .ti -0.5i
  1400. struct reginfo **reglist[]
  1401. .br
  1402. List of lists of pointers to register information.
  1403. For every property the list is here
  1404. to find the registers corresponding to it.
  1405. .in 0
  1406. .NH 3
  1407. tables.h
  1408. .PP
  1409. In tables.h various derived constants for the tables are
  1410. given.
  1411. They are then used to determine array sizes in the actual code generator,
  1412. plus loop termination in some cases.
  1413. .NH 2
  1414. Other important data structures
  1415. .PP
  1416. During code generation some other data structures are used
  1417. and here is a short description of some of the important ones.
  1418. .PP
  1419. Tokens are kept in the code generator as a struct consisting of
  1420. one integer
  1421. .I t_token
  1422. which is -1 if the token is a register,
  1423. and the number of the token otherwise,
  1424. plus an array of
  1425. .I TOKENSIZE
  1426. unions
  1427. .I t_att
  1428. of which the first is the register number in case of a register.
  1429. .PP
  1430. The fakestack is an array of these tokens,
  1431. there is a global variable
  1432. .I stackheight .
  1433. .PP
  1434. The results of expressions are kept in a struct
  1435. .I result
  1436. with elements
  1437. .I e_typ ,
  1438. giving the type of the expression:
  1439. .I EV_INT ,
  1440. .I EV_REG
  1441. or
  1442. .I EV_STR ,
  1443. and a union
  1444. .I e_v
  1445. which contains the real result.
  1446. .NH 2
  1447. A tour through the sources
  1448. .NH 3
  1449. codegen.c
  1450. .PP
  1451. The file codegen.c contains one large function consisting
  1452. of one giant switch statement.
  1453. It is the interpreter for the code generator pseudo code
  1454. as contained in code rules[].
  1455. This function can call itself recursively when doing lookahead.
  1456. Arguments are:
  1457. .IP codep 10
  1458. Pointer into code rules, pseudo program counter.
  1459. .IP ply
  1460. Number of EM pattern lookahead allowed.
  1461. .IP toplevel
  1462. Boolean telling whether this is the toplevel codegen() or
  1463. a deeper incarnation.
  1464. .IP costlimit
  1465. A cutoff value to limit searches.
  1466. If the cost crosses costlimit the incarnation can terminate.
  1467. .IP forced
  1468. A register number if nonzero.
  1469. This is used inside coercions to force the allocate() call to allocate
  1470. a register determined by earlier lookahead.
  1471. .PP
  1472. The instructions inplemented in the switch:
  1473. .NH 4
  1474. DO_NEXTEM
  1475. .PP
  1476. Matches the next EM pattern and does lookahead if necessary to find the best
  1477. code rule associated with this pattern.
  1478. Heuristics are used to determine best code rule when possible.
  1479. This is done by calling the distance() function.
  1480. .NH 4
  1481. DO_COERC
  1482. .PP
  1483. This sets the code generator in the state to do a from stack coercion.
  1484. .NH 4
  1485. DO_XMATCH
  1486. .PP
  1487. This is done when a match no longer has to be checked.
  1488. Used when the nocoercions: trick is used in the table.
  1489. .NH 4
  1490. DO_MATCH
  1491. .PP
  1492. This is the big one inside this function.
  1493. It has the task to transform the contents of the current
  1494. fakestack to match the pattern given after it.
  1495. .PP
  1496. Since the code generator does not know combining coercions,
  1497. i.e. there is no way to make a big token out of two smaller ones,
  1498. the first thing done is to stack every token that is too small.
  1499. After that all tokens too big are split if possible to the right size.
  1500. .PP
  1501. Next the coercions are sought that would transform tokens in place to
  1502. the right one, plus the coercions that would pop tokens of the stack.
  1503. Each of those might need a register, so a list of registers is generated
  1504. and at the end of looking for coercions the function
  1505. .I tuples()
  1506. is called to generate the list of all possible \fIn\fP-tuples,
  1507. where
  1508. .I n
  1509. equals the number of registers needed.
  1510. .PP
  1511. Lookahead is now performed if the number of tuples is greater than one.
  1512. If no possibility is found within the costlimit,
  1513. the fakestack is made smaller by pushing the bottom token,
  1514. and this process is repeated until either a way is found or
  1515. the fakestack is completely empty and there is still no way
  1516. to make the match.
  1517. .PP
  1518. If there is a way the corresponding coercions are executed
  1519. and the code is finished.
  1520. .NH 4
  1521. DO_REMOVE
  1522. .PP
  1523. Here the remove() call is executed, all tokens matched by the
  1524. token expression plus boolean expression are pushed.
  1525. In the current implementation there is no attempt to move those
  1526. tokens to registers, but that is a possible future extension.
  1527. .NH 4
  1528. DO_DEALLOCATE
  1529. .PP
  1530. This one temporarily decrements by one the reference count of all registers
  1531. contained in the token given as argument.
  1532. .NH 4
  1533. DO_REALLOCATE
  1534. .PP
  1535. Here all temporary deallocates are made undone.
  1536. .NH 4
  1537. DO_ALLOCATE
  1538. .PP
  1539. This is the part that allocates a register and decides which one to use.
  1540. If the
  1541. .I forced
  1542. argument was given its task is simple,
  1543. otherwise some work must be done.
  1544. First the list of possible registers is scanned,
  1545. all free registers noted and it is noted whether any of those
  1546. registers is already
  1547. containing the initialization.
  1548. If no registers are available some fakestack token is stacked and the
  1549. process is repeated.
  1550. .PP
  1551. After that if an exact match was found,
  1552. the list of registers is reduced to one register matching exactly
  1553. out of every register class.
  1554. Now lookahead is performed if necessary and the register chosen.
  1555. If an initialization was given the corresponding move is performed,
  1556. otherwise the register is marked empty.
  1557. .NH 4
  1558. DO_LOUTPUT
  1559. .PP
  1560. This prints a string and an expression.
  1561. Only done on toplevel.
  1562. .NH 4
  1563. DO_ROUTPUT
  1564. .PP
  1565. Prints a string and a new line.
  1566. Only on toplevel.
  1567. .NH 4
  1568. DO_MOVE
  1569. .PP
  1570. Calls the move() function in the code generator to implement the move()
  1571. function in the table.
  1572. .NH 4
  1573. DO_ERASE
  1574. .PP
  1575. Marks the register that is its argument as empty.
  1576. .NH 4
  1577. DO_TOKREPLACE
  1578. .PP
  1579. This is the token replacement part.
  1580. It is also called if there is no token replacement because it has
  1581. some other functions as well.
  1582. .PP
  1583. First the tokens that will be pushed on the fakestack are computed
  1584. and stored in a temporary array.
  1585. Then the tokens that were matched in this rule are popped
  1586. and their embedded registers have their reference count
  1587. decremented.
  1588. After that the replacement tokens are pushed.
  1589. .PP
  1590. Finally all registers allocated in this rule have their reference count
  1591. decremented.
  1592. If they were not pushed on the fakestack they will be available again
  1593. in the next code rule.
  1594. .NH 4
  1595. DO_EMREPLACE
  1596. .PP
  1597. Places replacement EM instructions back into the instruction stream.
  1598. .NH 4
  1599. DO_COST
  1600. .PP
  1601. Accounts for cost as given in the code rule.
  1602. .NH 4
  1603. DO_RETURN
  1604. .PP
  1605. Returns from this level of codegen().
  1606. Is used at the end of coercions,
  1607. move rules etc..
  1608. .NH 3
  1609. compute.c
  1610. .PP
  1611. This module computes the various expressions as given
  1612. in the enodes[] array.
  1613. Nothing very special happens here,
  1614. it is just a recursive function computing leaves
  1615. of expressions and applying the operator.
  1616. .NH 3
  1617. equiv.c
  1618. .PP
  1619. In this module the tuples() function is implemented.
  1620. It is given the number of registers needed and
  1621. a list of register lists and it constructs a list of tuples
  1622. where the \fIn\fP'th register comes from the \fIn\fP'th list.
  1623. Before the list is constructed however
  1624. the dynamic register classes are computed.
  1625. Two registers are in the same dynamic class if they are in the
  1626. same static class and their contents is the same.
  1627. .PP
  1628. After that the permute() recursive function is called to
  1629. generate the list of tuples.
  1630. After construction a generated tuple is added to the list
  1631. if it is not already pairwise in the same class
  1632. or if the register relations are not the same,
  1633. i.e. if the first and second register share a common
  1634. subregister in one tuple and not in the other they are considered different.
  1635. .NH 3
  1636. fillem.c
  1637. .PP
  1638. This is the routine that does the reading of EM instructions
  1639. and the handling of pseudos.
  1640. The mach.c module provided by the table writer is included
  1641. at the end of this module.
  1642. The routine fillemlines() is called by nextem() at toplevel
  1643. to make sure there are enough instruction to match.
  1644. It fills the EM instruction buffer up to 5 places from the end to
  1645. keep room for EM replacement instructions,
  1646. or up to a pseudo.
  1647. .PP
  1648. The dopseudo() function performs the function of the pseudo last
  1649. encountered.
  1650. If the pseudo is a
  1651. .B rom
  1652. the corresponding label is saved with the contents of the
  1653. .B rom
  1654. to be available to the code generator later.
  1655. The rest of the routines are small service routines for either
  1656. input or data output.
  1657. .NH 3
  1658. gencode.c
  1659. .PP
  1660. This module contains routines called by codegen() to generate the real
  1661. code to the codefile.
  1662. The function gencode() gets a string as argument and copies it to codefile
  1663. while processing certain embedded control characters implementing
  1664. the $2 and [1.reg] escapes.
  1665. The function genexpr() prints the expression given as argument.
  1666. It is used to implement the %(\ expr\ %) escape.
  1667. The prtoken() function interprets the tokenformat as given in
  1668. the tokens[] array.
  1669. .NH 3
  1670. glosym.c
  1671. .PP
  1672. This module maintains a list of global symbols that have a
  1673. .B rom
  1674. pseudo associated.
  1675. There are functions to enter a symbol and to find a symbol.
  1676. .NH 3
  1677. main.c
  1678. .PP
  1679. Main routine of the code generator.
  1680. Processes arguments and flags.
  1681. Flags available are:
  1682. .IP -d
  1683. Sets debug mode if the code generator was not compiled with
  1684. the NDEBUG macro defined.
  1685. Debug mode gives very long output on stderr indicating
  1686. all steps of the code generation process including nesting
  1687. of the codegen() function.
  1688. .IP -p\fIn\fP
  1689. Sets the lookahead depth to
  1690. .I n ,
  1691. the
  1692. .I p
  1693. stands for ply,
  1694. a well known word in chess playing programs.
  1695. .IP -w\fIn\fP
  1696. Sets the weight percentage for size in the cost function to
  1697. .I n
  1698. percent.
  1699. Uses Euclides algorithm to simplify rationals.
  1700. .NH 3
  1701. move.c
  1702. .PP
  1703. Function to implement the move() pseudo function in the tables,
  1704. register initialization and the setcc and test pseudo functions.
  1705. First tests are made to try to prevent the move from really happening.
  1706. The condition code register is treated special here.
  1707. After that, if there is an after that,
  1708. the move rule is found and the code executed.
  1709. .NH 3
  1710. nextem.c
  1711. .PP
  1712. The entry point of this module is nextem().
  1713. It hashes the next three EM instructions,
  1714. and uses the low order byte of the hash
  1715. as an index into the array pathash[],
  1716. to find a chain of patterns in the array
  1717. pattern[],
  1718. that are all tried for a match.
  1719. .PP
  1720. The function trypat() does most of the work
  1721. checking patterns.
  1722. When a pattern is found to match all instructions
  1723. the operands of the instruction are placed into the dollar[] array.
  1724. Then the boolean expression is tried.
  1725. If it matches the function can return,
  1726. leaving the operands still in the dollar[] array,
  1727. so later in the code rule they can still be used.
  1728. .NH 3
  1729. reg.c
  1730. .PP
  1731. Collection of routines to handle registers.
  1732. Reference count routines are here,
  1733. chrefcount() and getrefcount(),
  1734. plus routines to erase a single register or all of them,
  1735. erasereg() and cleanregs().
  1736. .PP
  1737. If NDEBUG hasn't been defined, here is also the routine that checks
  1738. if the reference count kept with the register information is in
  1739. agreement with the number of times it occurs on the fakestack.
  1740. .NH 3
  1741. salloc.c
  1742. .PP
  1743. Module for string allocation and garbage collection.
  1744. Contains entry points myalloc(),
  1745. a routine calling malloc() and checking whether room is left,
  1746. myfree(), just free(),
  1747. popstr() a function called from state.c to free all strings
  1748. made since the last saved status.
  1749. Furthermore there is salloc() which has the size of the string as parameter
  1750. and returns a pointer to the allocated space,
  1751. while keeping a copy of the pointer for garbage allocation purposes.
  1752. .PP
  1753. The function garbage_collect is called from codegen() at toplevel
  1754. every now and then,
  1755. and checks all places where strings may reside to mark strings
  1756. as being in use.
  1757. Strings not in use are returned to the pool of free space.
  1758. .NH 3
  1759. state.c
  1760. .PP
  1761. Set of routines called to save current status,
  1762. restore a previous saved state and to free the room
  1763. occupied by a saved state.
  1764. A list of structs is kept here to save the state.
  1765. If this is not done,
  1766. small allocates will take space
  1767. from the holes big enough for state saves,
  1768. and as a result every new state save will need a new struct.
  1769. The code generator runs out of room very rapidly under these conditions.
  1770. .NH 3
  1771. subr.c
  1772. .PP
  1773. Random set of leftover routines.
  1774. .NH 4
  1775. match
  1776. .PP
  1777. Computes whether a certain token matches a certain token expression.
  1778. Just computes a bitnumber according to the algorithm explained with
  1779. machsets[],
  1780. and tests the bit and the boolean expression if it is there.
  1781. .NH 4
  1782. instance,cinstance
  1783. .PP
  1784. These two functions compute a token from a description.
  1785. They differ very slight, cinstance() is used to compute
  1786. the result of a coercion in a certain context
  1787. and therefore has more arguments, which it uses instead of
  1788. the global information instance() works on.
  1789. .NH 4
  1790. eqtoken
  1791. .PP
  1792. eqtoken computes whether two tokens can be considered identical.
  1793. Used to check register contents during moves mainly.
  1794. .NH 4
  1795. distance
  1796. .PP
  1797. This is the heuristic function that computes a distance from
  1798. the current fakestack contents to the token pattern in the table.
  1799. It likes exact matches most, then matches where at least the sizes are correct
  1800. and if the sizes are not correct it likes too large sizes more than too
  1801. small, since splitting a token is easier than combining one.
  1802. .NH 4
  1803. split
  1804. .PP
  1805. This function tries to find a splitting coercion
  1806. and executes it immediately when found.
  1807. The fakestack is shuffled thoroughly when this happens,
  1808. so pieces below the token that must be split are saved first.
  1809. .NH 4
  1810. docoerc
  1811. .PP
  1812. This function executes a coercion that was found.
  1813. The same shuffling is done, so the top of the stack is again saved.
  1814. .NH 4
  1815. stackupto
  1816. .PP
  1817. This function gets a pointer into the fakestack and must stack
  1818. every token including the one pointed at up to the bottom of the fakestack.
  1819. The first stacking rule possible is used,
  1820. so rules using registers must come first.
  1821. .NH 4
  1822. findcoerc
  1823. .PP
  1824. Looks for a one to one coercion, if found it returns a pointer
  1825. to it and leaves a list of possible registers to use in the global
  1826. variable curreglist.
  1827. This is used by codegen().
  1828. .NH 3
  1829. var.c
  1830. .PP
  1831. Global variables used by more than one module.
  1832. External definitions are in extern.h.