perloptree.pod 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. =head1 NAME
  2. perloptree - The Perl op tree
  3. =head1 DESCRIPTION
  4. Various material about the internal Perl compilation representation
  5. during parsing and optimization, before the actual execution
  6. begins, represented as C<B> objects, the B<"B" op tree>.
  7. The well-known L<perlguts>.pod focuses more on the internal
  8. representation of the variables, but not so on the structure, the
  9. sequence and the optimization of the basic operations, the ops.
  10. And we have L<perlhack>.pod, which shows e.g. ways to hack into
  11. the op tree structure within the debugger. It focuses on getting
  12. people to start patching and hacking on the CORE, not
  13. understanding or writing compiler backends or optimizations,
  14. which the op tree mainly is used for.
  15. =head1 Brief Summary
  16. The brief summary is very well described in the
  17. L<"Compiled-code"/perlguts#Compiled-code> section of L<perlguts> and
  18. at the top of F<op.c>.
  19. When Perl parses the source code (via Yacc C<perly.y>), the so-called
  20. op tree, a tree of basic perl OP structs pointing to simple
  21. C<pp_>I<opname> functions, is generated bottom-up. Those C<pp_>
  22. functions - "PP Code" (for "Push / Pop Code") - have the same uniform
  23. API as the XS functions, all arguments and return values are
  24. transported on the stack. For example, an C<OP_CONST> op points to
  25. the C<pp_const()> function and to an C<SV> containing the constant
  26. value. When C<pp_const()> is executed, its job is to push that C<SV>
  27. onto the stack.
  28. OPs are created by the C<newFOO()> functions, which are called
  29. from the parser (in F<perly.y>) as the code is parsed. For
  30. example the Perl code C<$a + $b * $c> would cause the equivalent
  31. of the following to be called (oversimplifying a bit):
  32. newBINOP(OP_ADD, flags,
  33. newSVREF($a),
  34. newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
  35. )
  36. See also L<perlhack#Op Trees>
  37. The simpliest type of an op structure is C<OP>, a L</BASEOP>: this
  38. has no children. Unary operators, L</UNOP>s, have one child, and
  39. this is pointed to by the C<op_first> field. Binary operators
  40. (L</BINOP>s) have not only an C<op_first> field but also an
  41. C<op_last> field. The most complex type of op is a L</LISTOP>,
  42. which has any number of children. In this case, the first child
  43. is pointed to by C<op_first> and the last child by
  44. C<op_last>. The children in between can be found by iteratively
  45. following the C<op_sibling> pointer from the first child to the
  46. last.
  47. There are also two other op types: a L</"PMOP"> holds a regular
  48. expression, and has no children, and a L</"LOOP"> may or may not
  49. have children. If the C<op_sibling> field is non-zero, it behaves
  50. like a C<LISTOP>. To complicate matters, if an C<UNOP> is
  51. actually a null op after optimization (see L</"Compile pass 2:
  52. context propagation"> below) it will still have children in
  53. accordance with its former type.
  54. The beautiful thing about the op tree representation is that it
  55. is a strict 1:1 mapping to the actual source code, which is
  56. proven by the L<B::Deparse> module, which generates readable
  57. source for the current op tree. Well, almost.
  58. =head1 The Compiler
  59. Perl's compiler is essentially a 3-pass compiler with interleaved
  60. phases:
  61. 1. A bottom-up pass
  62. 2. A top-down pass
  63. 3. An execution-order pass
  64. =head2 Compile pass 1: check routines and constant folding
  65. The bottom-up pass is represented by all the C<"newOP"> routines
  66. and the C<ck_> routines. The bottom-upness is actually driven by
  67. F<yacc>. So at the point that a C<ck_> routine fires, we have no
  68. idea what the context is, either upward in the syntax tree, or
  69. either forward or backward in the execution order. The bottom-up
  70. parser builds that part of the execution order it knows about,
  71. but if you follow the "next" links around, you'll find it's
  72. actually a closed loop through the top level node.
  73. So when creating the ops in the first step, still bottom-up, for
  74. each op a check function (C<ck_ ()>) is called, which which
  75. theroretically may destructively modify the whole tree, but
  76. because it knows almost nothing, it mostly just nullifies the
  77. current op. Or it might set the L</op_next> pointer. See
  78. L</"Check Functions"> for more.
  79. Also, the subsequent constant folding routine C<fold_constants()>
  80. may fold certain arithmetic op sequences. See L</"Constant Folding">
  81. for more.
  82. =head2 Compile pass 2: context propagation
  83. The context determines the type of the return value. When a
  84. context for a part of compile tree is known, it is propagated
  85. down through the tree. At this time the context can have 5 values
  86. (instead of 2 for runtime context): C<void>, C<boolean>,
  87. C<scalar>, C<list>, and C<lvalue>. In contrast with the pass 1
  88. this pass is processed from top to bottom: a node's context
  89. determines the context for its children.
  90. Whenever the bottom-up parser gets to a node that supplies
  91. context to its components, it invokes that portion of the
  92. top-down pass that applies to that part of the subtree (and marks
  93. the top node as processed, so if a node further up supplies
  94. context, it doesn't have to take the plunge again). As a
  95. particular subcase of this, as the new node is built, it takes
  96. all the closed execution loops of its subcomponents and links
  97. them into a new closed loop for the higher level node. But it's
  98. still not the real execution order.
  99. I<Todo: Sample where this context flag is stored>
  100. Additional context-dependent optimizations are performed at this
  101. time. Since at this moment the compile tree contains back-references
  102. (via "thread" pointers), nodes cannot be C<free()>d now. To allow
  103. optimized-away nodes at this stage, such nodes are C<null()>ified
  104. instead of C<free()>'ing (i.e. their type is changed to C<OP_NULL>).
  105. =head2 Compile pass 3: peephole optimization
  106. The actual execution order is not known till we get a grammar
  107. reduction to a top-level unit like a subroutine or file that will
  108. be called by "name" rather than via a "next" pointer. At that
  109. point, we can call into peep() to do that code's portion of the
  110. 3rd pass. It has to be recursive, but it's recursive on basic
  111. blocks, not on tree nodes.
  112. So finally, when the full parse tree is generated, the "peephole
  113. optimizer" C<peep()> is running. This pass is neither top-down
  114. or bottom-up, but in the execution order (with additional
  115. complications for conditionals).
  116. This examines each op in the tree and attempts to determine "local"
  117. optimizations by "thinking ahead" one or two ops and seeing if
  118. multiple operations can be combined into one (by nullifying and
  119. re-ordering the next pointers).
  120. It also checks for lexical issues such as the effect of C<use
  121. strict> on bareword constants. Note that since the last walk the
  122. early sibling pointers for recursive (bottom-up) meta-inspection
  123. are useless, the final exec order is guaranteed by the next and
  124. flags fields.
  125. =head1 basic vs exec order
  126. The highly recursive Yacc parser generates the initial op tree in
  127. B<basic> order. To save memory and run-time the final execution
  128. order of the ops in sequential order is not copied around, just
  129. the next pointers are rehooked in C<Perl_linklist()> to the
  130. so-called B<exec> order. So the exec walk through the
  131. linked-list of ops is not too cache-friendly.
  132. In detail C<Perl_linklist()> traverses the op tree, and sets
  133. op-next pointers to give the execution order for that op
  134. tree. op-sibling pointers are rarely unneeded after that.
  135. Walkers can run in "basic" or "exec" order. "basic" is useful
  136. for the memory layout, it contains the history, "exec" is more
  137. useful to understand the logic and program flow. The
  138. L</B::Bytecode> section has an extensive example about the order.
  139. =head1 OP Structure and Inheritance
  140. The basic C<struct op> looks basically like
  141. C<{ OP* op_next, OP* op_sibling, OP* op_ppaddr, ..., int op_flags, int op_private } OP;>
  142. See L</BASEOP> below.
  143. Each op is defined in size, arguments, return values, class and
  144. more in the F<opcode.pl> table. (See L</"OP Class Declarations in
  145. opcode.pl"> below.)
  146. The class of an OP determines its size and the number of
  147. children. But the number and type of arguments is not so easy to
  148. declare as in C. F<opcode.pl> tries to declare some XS-prototype
  149. like arguments, but in lisp we would say most ops are "special"
  150. functions, context-dependent, with special parsing and precedence rules.
  151. F<B.pm> L<http://search.cpan.org/perldoc?B> contains these
  152. classes and inheritance:
  153. @B::OP::ISA = 'B::OBJECT';
  154. @B::UNOP::ISA = 'B::OP';
  155. @B::BINOP::ISA = 'B::UNOP';
  156. @B::LOGOP::ISA = 'B::UNOP';
  157. @B::LISTOP::ISA = 'B::BINOP';
  158. @B::SVOP::ISA = 'B::OP';
  159. @B::PADOP::ISA = 'B::OP';
  160. @B::PVOP::ISA = 'B::OP';
  161. @B::LOOP::ISA = 'B::LISTOP';
  162. @B::PMOP::ISA = 'B::LISTOP';
  163. @B::COP::ISA = 'B::OP';
  164. @B::SPECIAL::ISA = 'B::OBJECT';
  165. @B::optype = qw(OP UNOP BINOP LOGOP LISTOP PMOP SVOP PADOP PVOP LOOP COP);
  166. I<TODO: ascii graph from perlguts>
  167. F<op.h> L<http://search.cpan.org/src/JESSE/perl-5.12.1/op.h>
  168. contains all the gory details. Let's check it out:
  169. =head2 OP Class Declarations in opcode.pl
  170. The full list of op declarations is defined as C<DATA> in
  171. F<opcode.pl>. It defines the class, the name, some flags, and
  172. the argument types, the so-called "operands". C<make regen> (via
  173. F<regen.pl>) recreates out of this DATA table the files
  174. F<opcode.h>, F<opnames.h>, F<pp_proto.h> and F<pp.sym>.
  175. The class signifiers in F<opcode.pl> are:
  176. baseop - 0 unop - 1 binop - 2
  177. logop - | listop - @ pmop - /
  178. padop/svop - $ padop - # (unused) loop - {
  179. baseop/unop - % loopexop - } filestatop - -
  180. pvop/svop - " cop - ;
  181. Other options within F<opcode.pl> are:
  182. needs stack mark - m
  183. needs constant folding - f
  184. produces a scalar - s
  185. produces an integer - i
  186. needs a target - t
  187. target can be in a pad - T
  188. has a corresponding integer version - I
  189. has side effects - d
  190. uses $_ if no argument given - u
  191. Values for the operands are:
  192. scalar - S list - L array - A
  193. hash - H sub (CV) - C file - F
  194. socket - Fs filetest - F- reference - R
  195. "?" denotes an optional operand.
  196. =head2 BASEOP
  197. All op classes have a single character signifier for easier
  198. definition in F<opcode.pl>. The BASEOP class signifier is B<0>,
  199. for no children.
  200. Below are the BASEOP fields, which reflect the object C<B::OP>,
  201. since Perl 5.10. These are shared for all op classes. The parts
  202. after C<op_type> and before C<op_flags> changed during history.
  203. =over
  204. =item op_next
  205. Pointer to next op to execute after this one.
  206. Top level pre-grafted op points to first op, but this is replaced
  207. when op is grafted in, when this op will point to the real next
  208. op, and the new parent takes over role of remembering the
  209. starting op. I<Now, who wrote this prose? Anyway, that is why it
  210. is called guts.>
  211. =item op_sibling
  212. Pointer to connect the children's list.
  213. The first child is L</op_first>, the last is L</op_last>, and the
  214. children in between are interconnected by op_sibling. This is at
  215. run-time only used for L</LISTOP>s.
  216. So why is it in the BASEOP struct carried around for every op?
  217. Because of the complicated Yacc parsing and later optimization
  218. order as explained in L<"Compile pass 1: check routines and
  219. constant folding"> the L</op_next> pointers are not enough, so
  220. op_sibling's are required. The final and fast execution order by
  221. just following the op_next chain is expensive to calculate.
  222. See
  223. http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2006-09/msg00082.html
  224. for a 20% space-reduction patch to get rid of it at run-time.
  225. =item op_ppaddr
  226. Pointer to current ppcode's function.
  227. The so called "opcode".
  228. =item op_madprop
  229. Pointer to the MADPROP struct. Only with -DMAD, and since
  230. 5.10. See L</MAD> (Misc Attribute Decoration) below.
  231. =item op_targ
  232. PADOFFSET to "unnamed" op targets/GVs/constants, wasting no
  233. SV. Has for some op's also a different meaning.
  234. =item op_type
  235. The type of the operation.
  236. Since 5.10 we have the next five fields added, which replace
  237. C<U16 op_seq>.
  238. =item op_opt
  239. "optimized"
  240. Whether or not the op has been optimised by the peephole optimiser.
  241. See the comments in C<S_clear_yystack()> in F<perly.c> for more
  242. details on the following three flags. They are just for freeing
  243. temporary ops on the stack. But we might have statically
  244. allocated op in the data segment, esp. with the perl compiler's
  245. L<B::C> module. Then we are not allowed to free those static
  246. ops. For a short time, from 5.9.0 until 5.9.4, until the B::C
  247. module was removed from CORE, we had another field here for this
  248. reason: B<op_static>. On 1 it didn't free the static op. Before
  249. 5.9.0 the L</op_seq> field was used with the magic value B<-1> to
  250. indicate a static op, not to be freed. Note: Trying to free a
  251. static struct is considered harmful.
  252. =item op_latefree
  253. Tell C<op_free()> to clear this op (and free any kids) but not
  254. yet deallocate the struct. This means that the op may be safely
  255. C<op_free()>d multiple times.
  256. On static ops you just set this to B<1> and after the first
  257. C<op_free()> the C<op_latefreed> is automatically set and further
  258. C<op_free()> called are just ignored.
  259. =item op_latefreed
  260. If 1, an C<op_latefree> op has been C<op_free()>d.
  261. =item op_attached
  262. This op (sub)tree has been attached to the CV C<PL_compcv> so it
  263. doesn't need to be free'd.
  264. =item op_spare
  265. Three spare bits in this bitfield above. At least they survived 5.10.
  266. Those last two fields have been in all perls:
  267. =item op_flags
  268. Flags common to all operations.
  269. See C<OPf_*> in F<op.h>, or more verbose in L<B::Flags> or F<dump.c>
  270. =item op_private
  271. Flags peculiar to a particular operation (BUT, by default, set to
  272. the number of children until the operation is privatized by a
  273. check routine, which may or may not check number of children).
  274. This flag is normally used to hold op specific context hints,
  275. such as C<HINT_INTEGER>. This flag is directly attached to each
  276. relevant op in the subtree of the context. Note that there's no
  277. general context or class pointer for each op, a typical
  278. functional language usually holds this in the ops arguments. So
  279. we are limited to max 32 lexical pragma hints or less. See
  280. L</Lexical Pragmas>.
  281. =back
  282. The exact op.h L</BASEOP> history for the parts after C<op_type> and
  283. before C<op_flags> is:
  284. <=5.8: U16 op_seq;
  285. 5.9.4: unsigned op_opt:1; unsigned op_static:1; unsigned op_spare:5;
  286. >=5.10: unsigned op_opt:1; unsigned op_latefree:1; unsigned op_latefreed:1;
  287. unsigned op_attached:1; unsigned op_spare:3;
  288. The L</BASEOP> class signifier is B<0>, for no children.
  289. The full list of all BASEOP's is:
  290. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /0$/' opcode.pl
  291. null null operation ck_null 0
  292. stub stub ck_null 0
  293. pushmark pushmark ck_null s0
  294. wantarray wantarray ck_null is0
  295. padsv private variable ck_null ds0
  296. padav private array ck_null d0
  297. padhv private hash ck_null d0
  298. padany private value ck_null d0
  299. sassign scalar assignment ck_sassign s0
  300. unstack iteration finalizer ck_null s0
  301. enter block entry ck_null 0
  302. iter foreach loop iterator ck_null 0
  303. break break ck_null 0
  304. continue continue ck_null 0
  305. fork fork ck_null ist0
  306. wait wait ck_null isT0
  307. getppid getppid ck_null isT0
  308. time time ck_null isT0
  309. tms times ck_null 0
  310. ghostent gethostent ck_null 0
  311. gnetent getnetent ck_null 0
  312. gprotoent getprotoent ck_null 0
  313. gservent getservent ck_null 0
  314. ehostent endhostent ck_null is0
  315. enetent endnetent ck_null is0
  316. eprotoent endprotoent ck_null is0
  317. eservent endservent ck_null is0
  318. gpwent getpwent ck_null 0
  319. spwent setpwent ck_null is0
  320. epwent endpwent ck_null is0
  321. ggrent getgrent ck_null 0
  322. sgrent setgrent ck_null is0
  323. egrent endgrent ck_null is0
  324. getlogin getlogin ck_null st0
  325. custom unknown custom operator ck_null 0
  326. =head3 null
  327. null ops are skipped during the runloop, and are created by the peephole optimizer.
  328. =head2 UNOP
  329. The unary op class signifier is B<1>, for one child, pointed to
  330. by C<op_first>.
  331. struct unop {
  332. BASEOP
  333. OP * op_first;
  334. }
  335. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /1$/' opcode.pl
  336. rv2gv ref-to-glob cast ck_rvconst ds1
  337. rv2sv scalar dereference ck_rvconst ds1
  338. av2arylen array length ck_null is1
  339. rv2cv subroutine dereference ck_rvconst d1
  340. refgen reference constructor ck_spair m1 L
  341. srefgen single ref constructor ck_null fs1 S
  342. regcmaybe regexp internal guard ck_fun s1 S
  343. regcreset regexp internal reset ck_fun s1 S
  344. preinc preincrement (++) ck_lfun dIs1 S
  345. i_preinc integer preincrement (++) ck_lfun dis1 S
  346. predec predecrement (--) ck_lfun dIs1 S
  347. i_predec integer predecrement (--) ck_lfun dis1 S
  348. postinc postincrement (++) ck_lfun dIst1 S
  349. i_postinc integer postincrement (++) ck_lfun disT1 S
  350. postdec postdecrement (--) ck_lfun dIst1 S
  351. i_postdec integer postdecrement (--) ck_lfun disT1 S
  352. negate negation (-) ck_null Ifst1 S
  353. i_negate integer negation (-) ck_null ifsT1 S
  354. not not ck_null ifs1 S
  355. complement 1's complement (~) ck_bitop fst1 S
  356. rv2av array dereference ck_rvconst dt1
  357. rv2hv hash dereference ck_rvconst dt1
  358. flip range (or flip) ck_null 1 S S
  359. flop range (or flop) ck_null 1
  360. method method lookup ck_method d1
  361. entersub subroutine entry ck_subr dmt1 L
  362. leavesub subroutine exit ck_null 1
  363. leavesublv lvalue subroutine return ck_null 1
  364. leavegiven leave given block ck_null 1
  365. leavewhen leave when block ck_null 1
  366. leavewrite write exit ck_null 1
  367. dofile do "file" ck_fun d1 S
  368. leaveeval eval "string" exit ck_null 1 S
  369. #evalonce eval constant string ck_null d1 S
  370. =head2 BINOP
  371. The BINOP class signifier is B<2>, for two children, pointed to by
  372. C<op_first> and C<op_last>.
  373. struct binop {
  374. BASEOP
  375. OP * op_first;
  376. OP * op_last;
  377. }
  378. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /2$/' opcode.pl
  379. gelem glob elem ck_null d2 S S
  380. aassign list assignment ck_null t2 L L
  381. pow exponentiation (**) ck_null fsT2 S S
  382. multiply multiplication (*) ck_null IfsT2 S S
  383. i_multiply integer multiplication (*) ck_null ifsT2 S S
  384. divide division (/) ck_null IfsT2 S S
  385. i_divide integer division (/) ck_null ifsT2 S S
  386. modulo modulus (%) ck_null IifsT2 S S
  387. i_modulo integer modulus (%) ck_null ifsT2 S S
  388. repeat repeat (x) ck_repeat mt2 L S
  389. add addition (+) ck_null IfsT2 S S
  390. i_add integer addition (+) ck_null ifsT2 S S
  391. subtract subtraction (-) ck_null IfsT2 S S
  392. i_subtract integer subtraction (-) ck_null ifsT2 S S
  393. concat concatenation (.) or string ck_concat fsT2 S S
  394. left_shift left bitshift (<<) ck_bitop fsT2 S S
  395. right_shift right bitshift (>>) ck_bitop fsT2 S S
  396. lt numeric lt (<) ck_null Iifs2 S S
  397. i_lt integer lt (<) ck_null ifs2 S S
  398. gt numeric gt (>) ck_null Iifs2 S S
  399. i_gt integer gt (>) ck_null ifs2 S S
  400. le numeric le (<=) ck_null Iifs2 S S
  401. i_le integer le (<=) ck_null ifs2 S S
  402. ge numeric ge (>=) ck_null Iifs2 S S
  403. i_ge integer ge (>=) ck_null ifs2 S S
  404. eq numeric eq (==) ck_null Iifs2 S S
  405. i_eq integer eq (==) ck_null ifs2 S S
  406. ne numeric ne (!=) ck_null Iifs2 S S
  407. i_ne integer ne (!=) ck_null ifs2 S S
  408. ncmp numeric comparison (<=>)ck_null Iifst2 S S
  409. i_ncmp integer comparison (<=>)ck_null ifst2 S S
  410. slt string lt ck_null ifs2 S S
  411. sgt string gt ck_null ifs2 S S
  412. sle string le ck_null ifs2 S S
  413. sge string ge ck_null ifs2 S S
  414. seq string eq ck_null ifs2 S S
  415. sne string ne ck_null ifs2 S S
  416. scmp string comparison (cmp) ck_null ifst2 S S
  417. bit_and bitwise and (&) ck_bitop fst2 S S
  418. bit_xor bitwise xor (^) ck_bitop fst2 S S
  419. bit_or bitwise or (|) ck_bitop fst2 S S
  420. smartmatch smart match ck_smartmatch s2
  421. aelem array element ck_null s2 A S
  422. helem hash element ck_null s2 H S
  423. lslice list slice ck_null 2 H L L
  424. xor logical xor ck_null fs2 S S
  425. leaveloop loop exit ck_null 2
  426. =head2 LOGOP
  427. The LOGOP class signifier is B<|>.
  428. A LOGOP has the same structure as a L</BINOP>, two children, just the
  429. second field has another name C<op_other> instead of C<op_last>.
  430. But as you see on the list below, the two arguments as above are optional and
  431. not strictly required.
  432. struct logop {
  433. BASEOP
  434. OP * op_first;
  435. OP * op_other;
  436. };
  437. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /\|$/' opcode.pl
  438. regcomp regexp compilation ck_null s| S
  439. substcont substitution iterator ck_null dis|
  440. grepwhile grep iterator ck_null dt|
  441. mapwhile map iterator ck_null dt|
  442. range flipflop ck_null | S S
  443. and logical and (&&) ck_null |
  444. or logical or (||) ck_null |
  445. dor defined or (//) ck_null |
  446. cond_expr conditional expression ck_null d|
  447. andassign logical and assignment (&&=) ck_null s|
  448. orassign logical or assignment (||=) ck_null s|
  449. dorassign defined or assignment (//=) ck_null s|
  450. entergiven given() ck_null d|
  451. enterwhen when() ck_null d|
  452. entertry eval {block} ck_null |
  453. once once ck_null |
  454. =head3 and
  455. Checks for falseness on the first argument on the stack.
  456. If false, returns immediately, keeping the false value on the stack.
  457. If true pops the stack, and returns the op at C<op_other>.
  458. Note: B<and> is also used for a simple B<if> without B<else>/B<elsif>.
  459. The general B<if> is done with L<cond_expr>.
  460. =head3 cond_expr
  461. Checks for trueness on the first argument on the stack.
  462. If true returns the op at C<op_other>, if false C<op_next>.
  463. Note: A simple B<if> without else is done by L<and>.
  464. =head2 LISTOP
  465. The LISTOP class signifier is B<@>.
  466. struct listop {
  467. BASEOP
  468. OP * op_first;
  469. OP * op_last;
  470. };
  471. This is most complex type, it may have any number of children. The
  472. first child is pointed to by C<op_first> and the last child by
  473. C<op_last>. The children in between can be found by iteratively
  474. following the C<op_sibling> pointer from the first child to the last.
  475. At all 99 ops from 366 are LISTOP's. This is the least
  476. restrictive format, that's why.
  477. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /\@$/' opcode.pl
  478. bless bless ck_fun s@ S S?
  479. glob glob ck_glob t@ S?
  480. stringify string ck_fun fsT@ S
  481. atan2 atan2 ck_fun fsT@ S S
  482. substr substr ck_substr st@ S S S? S?
  483. vec vec ck_fun ist@ S S S
  484. index index ck_index isT@ S S S?
  485. rindex rindex ck_index isT@ S S S?
  486. sprintf sprintf ck_fun fmst@ S L
  487. formline formline ck_fun ms@ S L
  488. crypt crypt ck_fun fsT@ S S
  489. aslice array slice ck_null m@ A L
  490. hslice hash slice ck_null m@ H L
  491. unpack unpack ck_unpack @ S S?
  492. pack pack ck_fun mst@ S L
  493. split split ck_split t@ S S S
  494. join join or string ck_join mst@ S L
  495. list list ck_null m@ L
  496. anonlist anonymous list ([]) ck_fun ms@ L
  497. anonhash anonymous hash ({}) ck_fun ms@ L
  498. splice splice ck_fun m@ A S? S? L
  499. ... and so on, until
  500. syscall syscall ck_fun imst@ S L
  501. =head2 PMOP
  502. The PMOP "pattern matching" class signifier is B</> for matching.
  503. It inherits from the L</LISTOP>.
  504. The internal struct changed completely with 5.10, as the
  505. underlying engine. Starting with 5.11 the PMOP can even hold
  506. native L<"REGEX"/perlguts#REGEX> objects, not just SV's. So you
  507. have to use the C<PM> macros to stay compatible.
  508. Below is the current C<struct pmop>. You will not like it.
  509. struct pmop {
  510. BASEOP
  511. OP * op_first;
  512. OP * op_last;
  513. #ifdef USE_ITHREADS
  514. IV op_pmoffset;
  515. #else
  516. REGEXP * op_pmregexp; /* compiled expression */
  517. #endif
  518. U32 op_pmflags;
  519. union {
  520. OP * op_pmreplroot; /* For OP_SUBST */
  521. #ifdef USE_ITHREADS
  522. PADOFFSET op_pmtargetoff; /* For OP_PUSHRE */
  523. #else
  524. GV * op_pmtargetgv;
  525. #endif
  526. } op_pmreplrootu;
  527. union {
  528. OP * op_pmreplstart; /* Only used in OP_SUBST */
  529. #ifdef USE_ITHREADS
  530. char * op_pmstashpv; /* Only used in OP_MATCH, with PMf_ONCE set */
  531. #else
  532. HV * op_pmstash;
  533. #endif
  534. } op_pmstashstartu;
  535. };
  536. Before we had no union, but a C<op_pmnext>, which never worked.
  537. Maybe because of the typo in the comment.
  538. The old struct (up to 5.8.x) was as simple as:
  539. struct pmop {
  540. BASEOP
  541. OP * op_first;
  542. OP * op_last;
  543. U32 op_children;
  544. OP * op_pmreplroot;
  545. OP * op_pmreplstart;
  546. PMOP * op_pmnext; /* list of all scanpats */
  547. REGEXP * op_pmregexp; /* compiled expression */
  548. U16 op_pmflags;
  549. U16 op_pmpermflags;
  550. U8 op_pmdynflags;
  551. }
  552. So C<op_pmnext>, C<op_pmpermflags> and C<op_pmdynflags> are gone.
  553. The C<op_pmflags> are not the whole deal, there's also C<op_pmregexp.extflags>
  554. - interestingly called C<B::PMOP::reflags> in B - for the new features.
  555. This is btw. the only inconsistency in the B mapping.
  556. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /\/$/' opcode.pl
  557. pushre push regexp ck_null d/
  558. match pattern match (m//) ck_match d/
  559. qr pattern quote (qr//) ck_match s/
  560. subst substitution (s///) ck_match dis/ S
  561. =head2 SVOP
  562. The SVOP class is very special, and can even change dynamically.
  563. Whole SV's are costly and are now just used as GV or RV.
  564. The SVOP has no special signifier, as there are different subclasses.
  565. See L</"SVOP_OR_PADOP">, L</"PVOP_OR_SVOP"> and L</"FILESTATOP">.
  566. A SVOP holds a SV and is in case of an FILESTATOP the GV for the
  567. filehandle argument, and in case of C<trans> (a L</PVOP>) with utf8 a
  568. reference to a swash (i.e., an RV pointing to an HV).
  569. struct svop {
  570. BASEOP
  571. SV * op_sv;
  572. };
  573. Most old SVOP's were changed to L</PADOP>'s when threading was introduced, to
  574. privatize the global SV area to thread-local scratchpads.
  575. =head3 SVOP_OR_PADOP
  576. The op C<aelemfast> is either a L<PADOP> with threading and a simple L<SVOP> without.
  577. This is thanksfully known at compile-time.
  578. aelemfast constant array element ck_null s$ A S
  579. =head3 PVOP_OR_SVOP
  580. The only op here is C<trans>, where the class is dynamically defined,
  581. dependent on the utf8 settings in the L</op_private> hints.
  582. case OA_PVOP_OR_SVOP:
  583. return (o->op_private & (OPpTRANS_TO_UTF|OPpTRANS_FROM_UTF))
  584. ? OPc_SVOP : OPc_PVOP;
  585. trans transliteration (tr///) ck_null is" S
  586. Character translations (C<tr///>) are usually a L<PVOP>, keeping a pointer
  587. to a table of shorts used to look up translations. Under utf8,
  588. however, a simple table isn't practical; instead, the OP is an L</SVOP>,
  589. and the SV is a reference to a B<swash>, i.e. a RV pointing to an HV.
  590. =head2 PADOP
  591. The PADOP class signifier is B<$> for temp. scalars.
  592. A new C<PADOP> creates a new temporary scratchpad, an PADLIST array.
  593. C<padop->op_padix = pad_alloc(type, SVs_PADTMP);>
  594. C<SVs_PADTMP> are targets/GVs/constants with undef names.
  595. A C<PADLIST> scratchpad is a special context stack, a array-of-array data structure
  596. attached to a CV (i.e. a sub), to store lexical variables and opcode temporary and
  597. per-thread values. See L<perlguts/Scratchpads>.
  598. Only my/our variable (C<SVs_PADMY>/C<SVs_PADOUR>) slots get valid names.
  599. The rest are op targets/GVs/constants which are statically allocated
  600. or resolved at compile time. These don't have names by which they
  601. can be looked up from Perl code at run time through eval "" like
  602. my/our variables can be. Since they can't be looked up by "name"
  603. but only by their index allocated at compile time (which is usually
  604. in C<op_targ>), wasting a name SV for them doesn't make sense.
  605. struct padop {
  606. BASEOP
  607. PADOFFSET op_padix;
  608. };
  609. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /\$$/' opcode.pl
  610. const constant item ck_svconst s$
  611. gvsv scalar variable ck_null ds$
  612. gv glob value ck_null ds$
  613. anoncode anonymous subroutine ck_anoncode $
  614. rcatline append I/O operator ck_null t$
  615. aelemfast constant array element ck_null s$ A S
  616. method_named method with known name ck_null d$
  617. hintseval eval hints ck_svconst s$
  618. =head2 PVOP
  619. This is a simple unary op, holding a string.
  620. The only PVOP is C<trans> op for L<tr///>.
  621. See above at L</PVOP_OR_SVOP> for the dynamic nature of trans with utf8.
  622. The PVOP class signifier is C<"> for strings.
  623. struct pvop {
  624. BASEOP
  625. char * op_pv;
  626. };
  627. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /\"$/' opcode.pl
  628. trans transliteration (tr///) ck_match is" S
  629. =head2 LOOP
  630. The LOOP class signifier is B<{>.
  631. It inherits from the L</LISTOP>.
  632. struct loop {
  633. BASEOP
  634. OP * op_first;
  635. OP * op_last;
  636. OP * op_redoop;
  637. OP * op_nextop;
  638. OP * op_lastop;
  639. };
  640. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /\{$/' opcode.pl
  641. enteriter foreach loop entry ck_null d{
  642. enterloop loop entry ck_null d{
  643. =head2 COP
  644. The C<struct cop>, the "Control OP", changed recently a lot, as the L</BASEOP>.
  645. Remember from perlguts what a COP is? Got you. A COP is nowhere described.
  646. I would have naively called it "Context OP", but not "Control OP". So why?
  647. We have a global C<PL_curcop> and then we have threads. So it cannot be global
  648. anymore. A COP can be said as helper context for debugging and error information
  649. to store away file and line information. But since perl is a file-based
  650. compiler, not block-based, also file based pragmata and hints are stored in the
  651. COP. So we have for every source file a seperate COP. COP's are mostly not
  652. really block level contexts, just file and line information. The block level
  653. contexts are not controlled via COP's, but global C<Cx> structs.
  654. F<cop.h> says:
  655. Control ops (cops) are one of the two ops OP_NEXTSTATE and OP_DBSTATE
  656. that (loosely speaking) are separate statements. They hold
  657. information for lexical state and error reporting. At run time, C<PL_curcop> is set
  658. to point to the most recently executed cop, and thus can be used to determine
  659. our file-level current state.
  660. But we need block context, eval context, subroutine context, loop context, and
  661. even format context. All these are seperate structs defined in F<cop.h>.
  662. So the COPs are not really that important, as the actual C<Cx> context structs
  663. are. Just the C<CopSTASH> is, the current package symbol table hash ("stash").
  664. Another famous COP is C<PL_compiling>, which sets the temporary compilation
  665. environment.
  666. struct cop {
  667. BASEOP
  668. line_t cop_line; /* line # of this command */
  669. char * cop_label; /* label for this construct */
  670. #ifdef USE_ITHREADS
  671. char * cop_stashpv; /* package line was compiled in */
  672. char * cop_file; /* file name the following line # is from */
  673. #else
  674. HV * cop_stash; /* package line was compiled in */
  675. GV * cop_filegv; /* file the following line # is from */
  676. #endif
  677. U32 cop_hints; /* hints bits from pragmata */
  678. U32 cop_seq; /* parse sequence number */
  679. /* Beware. mg.c and warnings.pl assume the type of this is STRLEN *: */
  680. STRLEN * cop_warnings; /* lexical warnings bitmask */
  681. /* compile time state of %^H. See the comment in op.c for how this is
  682. used to recreate a hash to return from caller. */
  683. struct refcounted_he * cop_hints_hash;
  684. };
  685. The COP class signifier is B<;> and there are only two:
  686. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /;$/' opcode.pl
  687. nextstate next statement ck_null s;
  688. dbstate debug next statement ck_null s;
  689. C<NEXTSTATE> is replaced by C<DBSTATE> when you call perl with -d, the
  690. debugger. You can even patch the C<NEXTSTATE> ops at runtime to
  691. C<DBSTATE> as done in the module C<Enbugger>.
  692. For a short time there used to be three. C<SETSTATE> was
  693. added 1999 (pre Perl 5.6.0) to track linenumbers correctly
  694. in optimized blocks, disabled 1999 with change 4309 for Perl
  695. 5.6.0, and removed with 5edb5b2abb at Perl 5.10.1.
  696. =head2 BASEOP_OR_UNOP
  697. BASEOP_OR_UNOP has the class signifier B<%>. As the name says, it may
  698. be a L</BASEOP> or L</UNOP>, it may have an optional L</op_first> field.
  699. The list of B<%> ops is quite large, it has 84 ops.
  700. Some of them are e.g.
  701. $ perl -F"/\cI+/" -ane 'print if $F[3] =~ /%$/' opcode.pl
  702. ...
  703. quotemeta quotemeta ck_fun fstu% S?
  704. aeach each on array ck_each % A
  705. akeys keys on array ck_each t% A
  706. avalues values on array ck_each t% A
  707. each each ck_each % H
  708. values values ck_each t% H
  709. keys keys ck_each t% H
  710. delete delete ck_delete % S
  711. exists exists ck_exists is% S
  712. pop pop ck_shift s% A?
  713. shift shift ck_shift s% A?
  714. caller caller ck_fun t% S?
  715. reset symbol reset ck_fun is% S?
  716. exit exit ck_exit ds% S?
  717. ...
  718. =head2 FILESTATOP
  719. A FILESTATOP may be a L</UNOP>, L</PADOP>, L</BASEOP> or L</SVOP>.
  720. It has the class signifier B<->.
  721. The file stat OPs are created via UNI(OP_foo) in toke.c but use the
  722. C<OPf_REF> flag to distinguish between OP types instead of the usual
  723. C<OPf_SPECIAL> flag. As usual, if C<OPf_KIDS> is set, then we return
  724. C<OPc_UNOP> so that C<walkoptree> can find our children. If C<OPf_KIDS> is not
  725. set then we check C<OPf_REF>. Without C<OPf_REF> set (no argument to the
  726. operator) it's an OP; with C<OPf_REF> set it's an SVOP (and the field C<op_sv> is the
  727. GV for the filehandle argument).
  728. case OA_FILESTATOP:
  729. return ((o->op_flags & OPf_KIDS) ? OPc_UNOP :
  730. #ifdef USE_ITHREADS
  731. (o->op_flags & OPf_REF) ? OPc_PADOP : OPc_BASEOP);
  732. #else
  733. (o->op_flags & OPf_REF) ? OPc_SVOP : OPc_BASEOP);
  734. #endif
  735. lstat lstat ck_ftst u- F
  736. stat stat ck_ftst u- F
  737. ftrread -R ck_ftst isu- F-+
  738. ftrwrite -W ck_ftst isu- F-+
  739. ftrexec -X ck_ftst isu- F-+
  740. fteread -r ck_ftst isu- F-+
  741. ftewrite -w ck_ftst isu- F-+
  742. fteexec -x ck_ftst isu- F-+
  743. ftis -e ck_ftst isu- F-
  744. ftsize -s ck_ftst istu- F-
  745. ftmtime -M ck_ftst stu- F-
  746. ftatime -A ck_ftst stu- F-
  747. ftctime -C ck_ftst stu- F-
  748. ftrowned -O ck_ftst isu- F-
  749. fteowned -o ck_ftst isu- F-
  750. ftzero -z ck_ftst isu- F-
  751. ftsock -S ck_ftst isu- F-
  752. ftchr -c ck_ftst isu- F-
  753. ftblk -b ck_ftst isu- F-
  754. ftfile -f ck_ftst isu- F-
  755. ftdir -d ck_ftst isu- F-
  756. ftpipe -p ck_ftst isu- F-
  757. ftsuid -u ck_ftst isu- F-
  758. ftsgid -g ck_ftst isu- F-
  759. ftsvtx -k ck_ftst isu- F-
  760. ftlink -l ck_ftst isu- F-
  761. fttty -t ck_ftst is- F-
  762. fttext -T ck_ftst isu- F-
  763. ftbinary -B ck_ftst isu- F-
  764. =head2 LOOPEXOP
  765. A LOOPEXOP is almost a L<BASEOP_OR_UNOP>. It may be a L</UNOP> if stacked or
  766. L</BASEOP> if special or L</PVOP> else.
  767. C<next>, C<last>, C<redo>, C<dump> and C<goto> use C<OPf_SPECIAL> to indicate that a
  768. label was omitted (in which case it's a L</BASEOP>) or else a term was
  769. seen. In this last case, all except goto are definitely L</PVOP> but
  770. goto is either a PVOP (with an ordinary constant label), an L</UNOP>
  771. with C<OPf_STACKED> (with a non-constant non-sub) or an L</UNOP> for
  772. C<OP_REFGEN> (with C<goto &sub>) in which case C<OPf_STACKED> also seems to
  773. get set.
  774. ...
  775. =head2 OP Definition Example
  776. Let's take a simple example for a opcode definition in F<opcode.pl>:
  777. left_shift left bitshift (<<) ck_bitop fsT2 S S
  778. The op C<left_shift> has a check function C<ck_bitop> (normally most ops
  779. have no check function, just C<ck_null>), and the options C<fsT2>.
  780. The last two C<S S> describe the type of the two required operands:
  781. SV or scalar. This is similar to XS protoypes.
  782. The last C<2> in the options C<fsT2> denotes the class BINOP, with
  783. two args on the stack.
  784. Every binop takes two args and this produces one scalar, see the C<s> flag.
  785. The other remaining flags are C<f> and C<T>.
  786. C<f> tells the compiler in the first pass to call C<fold_constants()>
  787. on this op. See L</"Compile pass 1: check routines and constant folding">
  788. If both args are constant, the result is constant also and the op will
  789. be nullified.
  790. Now let's inspect the simple definition of this op in F<pp.c>.
  791. C<pp_left_shift> is the C<op_ppaddr>, the function pointer, for every
  792. left_shift op.
  793. PP(pp_left_shift)
  794. {
  795. dVAR; dSP; dATARGET; tryAMAGICbin(lshift,opASSIGN);
  796. {
  797. const IV shift = POPi;
  798. if (PL_op->op_private & HINT_INTEGER) {
  799. const IV i = TOPi;
  800. SETi(i << shift);
  801. }
  802. else {
  803. const UV u = TOPu;
  804. SETu(u << shift);
  805. }
  806. RETURN;
  807. }
  808. }
  809. The first IV arg is pop'ed from the stack, the second arg is left on the stack (C<TOPi>/C<TOPu>),
  810. because it is used as the return value. (I<Todo: explain the opASSIGN magic check.>)
  811. One IV or UV is produced, dependent on C<HINT_INTEGER>, set by the C<use integer> pragma.
  812. So it has a special signed/unsigned integer behaviour, which is not defined in the opcode
  813. declaration, because the API is indifferent on this, and it is also independent on the
  814. argument type. The result, if IV or UV, is entirely context dependent at compile-time
  815. ( C<use integer at BEGIN> ) or run-time ( C<$^H |= 1> ), and only stored in the op.
  816. What is left is the C<T> flag, "target can be a pad". This is a useful optimization technique.
  817. This is checked in the macro C<dATARGET>
  818. C<SV *targ = (PL_op->op_flags & OPf_STACKED ? sp[-1] : PAD_SV(PL_op->op_targ));>
  819. C<OPf_STACKED> means "Some arg is arriving on the stack." (see F<op.h>)
  820. So this reads, if the op contains C<OPf_STACKED>, the magic C<targ> ("target argument")
  821. is simply on the stack, but if not, the C<op_targ> points to a SV on a private scratchpad.
  822. "target can be a pad", voila.
  823. For reference see L<perlguts/"Putting a C value on Perl stack">.
  824. =head2 Check Functions
  825. They are defined in F<op.c> and not in F<pp.c>, because they belong tightly to the
  826. ops and newOP definition, and not to the actual pp_ opcode. That's why
  827. the actual F<op.c> file is bigger than F<pp.c> where the real gore for each op begins.
  828. The name of each op's check function is defined in F<opcodes.pl>, as shown above.
  829. The C<ck_null> check function is the most common.
  830. $ perl -F"/\cI+/" -ane 'print $F[2],"\n" if $F[2] =~ /ck_null/' opcode.pl|wc -l
  831. 128
  832. But we do have a lot of those check functions.
  833. $ perl -F"/\cI+/" -ane 'print $F[2],"\n" if $F[2] =~ /ck_/' opcode.pl|sort -u|wc -l
  834. 43
  835. B<When are they called, how do they look like, what do they do.>
  836. The macro CHECKOP(type,o) used to call the ck_ function has a little bit of
  837. common logic.
  838. #define CHECKOP(type,o) \
  839. ((PL_op_mask && PL_op_mask[type]) \
  840. ? ( op_free((OP*)o), \
  841. Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]), \
  842. (OP*)0 ) \
  843. : CALL_FPTR(PL_check[type])(aTHX_ (OP*)o))
  844. So when a global B<PL_op_mask> is fitting to the type the OP is nullified at once.
  845. If not, the type specific check function with the help of F<opcodes.pl> generating
  846. the C<PL_check> array in F<opnames.h> is called.
  847. =head2 Constant Folding
  848. In theory pretty easy. If all op's arguments in a sequence are constant and the
  849. op is sideffect free ("purely functional"), replace the op sequence with an
  850. constant op as result.
  851. We do it like this: We define the C<f> flag in F<opcodes.pl>, which tells the
  852. compiler in the first pass to call C<fold_constants()> on this op. See
  853. L<"Compile pass 1: check routines and constant folding"> above. If all args are
  854. constant, the result is constant also and the op sequence will be replaced by
  855. the constant.
  856. But take care, every C<f> op must be sideeffect free.
  857. E.g. our C<newUNOP()> calls at the end:
  858. return fold_constants((OP *) unop);
  859. OA_FOLDCONST ...
  860. =head2 Lexical Pragmas
  861. To implement user lexical pragmas, there needs to be a way at run time to get
  862. the compile time state of `%^H` for that block. Storing `%^H` in every
  863. block (or even COP) would be very expensive, so a different approach is
  864. taken. The (running) state of C<%^H> is serialised into a tree of HE-like
  865. structs. Stores into C<%^H> are chained onto the current leaf as a struct
  866. refcounted_he * with the key and the value. Deletes from C<%^H> are saved
  867. with a value of C<PL_sv_placeholder>. The state of C<%^H> at any point can be
  868. turned back into a regular HV by walking back up the tree from that point's
  869. leaf, ignoring any key you've already seen (placeholder or not), storing
  870. the rest into the HV structure, then removing the placeholders. Hence
  871. memory is only used to store the C<%^H> deltas from the enclosing COP, rather
  872. than the entire C<%^H> on each COP.
  873. To cause actions on C<%^H> to write out the serialisation records, it has
  874. magic type 'H'. This magic (itself) does nothing, but its presence causes
  875. the values to gain magic type 'h', which has entries for set and clear.
  876. C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
  877. record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
  878. saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
  879. it will be correctly restored when any inner compiling scope is exited.
  880. =head1 Examples
  881. =head2 Call a subroutine
  882. subname(args...) =>
  883. pushmark
  884. args ...
  885. gv => subname
  886. entersub
  887. =head2 Call a method
  888. Here we have several combinations to define the package and the method name, either
  889. compile-time (static as constant string), or dynamic as B<GV> (for the method name) or
  890. B<PADSV> (package name).
  891. B<method_named> holds the method name as C<sv> if known at compile time.
  892. If not B<gv> (of the name) and B<method> is used.
  893. The package name is at the top of the stack.
  894. A call stack is added with B<pushmark>.
  895. 1. Static compile time package ("class") and method:
  896. Class->subname(args...) =>
  897. pushmark
  898. const => PV "Class"
  899. args ...
  900. method_named => PV "subname"
  901. entersub
  902. 2. Run-time package ("object") and compile-time method:
  903. $obj->meth(args...) =>
  904. pushmark
  905. padsv => GV *packagename
  906. args ...
  907. method_named => PV "meth"
  908. entersub
  909. 3. Run-time package and run-time method:
  910. $obj->$meth(args...) =>
  911. pushmark
  912. padsv => GV *packagename
  913. args ...
  914. gvsv => GV *meth
  915. method
  916. entersub
  917. 4. Compile-time package ("class") and run-time method:
  918. Class->$meth(args...) =>
  919. pushmark
  920. const => PV "Class"
  921. args ...
  922. gvsv => GV *meth
  923. method
  924. entersub
  925. =head1 Hooks
  926. =head2 Special execution blocks BEGIN, CHECK, UNITCHECK, INIT, END
  927. Perl keeps special arrays of subroutines that are executed at the
  928. beginning and at the end of a running Perl program and its program
  929. units. These subroutines correspond to the special code blocks:
  930. C<BEGIN>, C<CHECK>, C<UNITCHECK>, C<INIT> and C<END>. (See basics at
  931. L<perlmod/basics>.)
  932. Such arrays belong to Perl's internals that you're not supposed to
  933. see. Entries in these arrays get consumed by the interpreter as it
  934. enters distinct compilation phases, triggered by statements like
  935. C<require>, C<use>, C<do>, C<eval>, etc. To play as safest as
  936. possible, the only allowed operations are to add entries to the start
  937. and to the end of these arrays.
  938. BEGIN, UNITCHECK and INIT are FIFO (first-in, first-out) blocks while
  939. CHECK and END are LIFO (last-in, first-out).
  940. L<Devel::Hook> allows adding code the start or end of these
  941. blocks. L<Manip::END> even tries to remove certain entries.
  942. =head3 The BEGIN block
  943. A special array of code at C<PL_beginav>, that is executed before
  944. C<main_start>, the first op, which is defined be called C<ENTER>.
  945. E.g. C<use module;> adds its require and importer code into the BEGIN
  946. block.
  947. =head3 The CHECK block
  948. The B compiler starting block at C<PL_checkav>. This hooks int the
  949. check function which is executed for every op created in bottom-up,
  950. basic order.
  951. =head3 The UNITCHECK block
  952. A new block since Perl 5.10 at C<PL_unitcheckav> runs right after the
  953. CHECK block, to seperate possible B compilation hooks from other
  954. checks.
  955. =head3 The INIT block
  956. At C<PL_initav>.
  957. =head3 The END block
  958. At C<PL_endav>.
  959. L<Manip::END> started to mess around with this block.
  960. The array contains an C<undef> for each block that has been
  961. encountered. It's not really an C<undef> though, it's a kind of raw
  962. coderef that's not wrapped in a scalar ref. This leads to funky error
  963. messages like C<Bizarre copy of CODE in sassign> when you try to assign
  964. one of these values to another variable. See L<Manip::END> how to
  965. manipulate these values array.
  966. =head2 B and O module. The perl compiler.
  967. Malcom Beattie's B modules hooked into the early op tree stages to
  968. represent the internal ops as perl objects and added the perl compiler
  969. backends. See L<B> and L<perlcompile>.
  970. The three main compiler backends are still B<Bytecode>, B<C> and B<CC>.
  971. I<Todo: Describe B's object representation a little bit deeper, its
  972. CHECK hook, its internal transformers for Bytecode (asm and vars) and
  973. C (the sections).>
  974. =head2 MAD
  975. MAD stands for "Misc Attributed Data".
  976. Larry Wall worked on a new MAD compiler backend outside of the B
  977. approach, dumping the internal op tree representation as B<XML> or
  978. B<YAML>, not as tree of perl B objects.
  979. The idea is that all the information needed to recreate the original source is
  980. stored in the op tree. To do this the tokens for the ops are associated with ops,
  981. these madprops are a list of key-value pairs, where the key is a character as
  982. listed at the end of F<op.h>, the value normally is a string, but it might also be
  983. a op, as in the case of a optimized op ('O'). Special for the whitespace key '_'
  984. (whitespace before) and '#' (whitespace after), which indicate the whitespace or
  985. comment before/after the previous key-value pair.
  986. Also when things normally compiled out, like a BEGIN block, which normally do
  987. not results in any ops, instead create a NULLOP with madprops used to recreate
  988. the object.
  989. I<Is there any documentation on this?>
  990. Why this awful XML and not the rich tree of perl objects?
  991. Well there's an advantage.
  992. The MAD XML can be seen as some kind of XML Storable/Freeze of the B
  993. op tree, and can be therefore converted outside of the CHECK block,
  994. which means you can easier debug the conversion (= compilation)
  995. process. To debug the CHECK block in the B backends you have to
  996. use the L<B::Debugger> B<Od> or B<Od_o> modules, which defer the
  997. CHECK to INIT. Debugging the highly recursive data is not easy,
  998. and often problems can not be reproduced in the B debugger because
  999. the B debugger influences the optree.
  1000. B<kurila> L<http://search.cpan.org/dist/kurila/> uses MAD to convert
  1001. Perl 5 source to the kurila dialect.
  1002. To convert a file 'source.pm' from Perl 5.10 to Kurila you need to do:
  1003. kurilapath=/usr/src/perl/kurila-1.9
  1004. bleadpath=/usr/src/perl/blead
  1005. cd $kurilapath
  1006. madfrom='perl-5.10' madto='kurila-1.9' \
  1007. madconvert="/usr/bin/perl $kurilapath/mad/p5kurila.pl" \
  1008. madpath="$bleadpath/mad" \
  1009. mad/convert /path/to/source.pm
  1010. B<PPI> L<http://search.cpan.org/dist/PPI/>, a Perl 5 source level parser not
  1011. related to the op tree at all, could also have been used for that.
  1012. =head2 Pluggable runops
  1013. The compile tree is executed by one of two existing runops functions, in F<run.c>
  1014. or in F<dump.c>. C<Perl_runops_debug> is used with C<DEBUGGING> and the faster
  1015. C<Perl_runops_standard> is used otherwise (See below in L</"Walkers">). For fine
  1016. control over the execution of the compile tree it is possible to provide your
  1017. own runops function.
  1018. It's probably best to copy one of the existing runops functions and
  1019. change it to suit your needs. Then, in the C<BOOT> section of your XS
  1020. file, add the line:
  1021. PL_runops = my_runops;
  1022. This function should be as efficient as possible to keep your programs
  1023. running as fast as possible. See L<Jit> for an even faster just-in-time
  1024. compilation runloop.
  1025. =head3 Walkers or runops
  1026. The standard op tree B<walker> or B<runops> is as simple as this fast
  1027. C<Perl_runops_standard()> in (F<run.c>). It starts with C<main_start> and walks
  1028. the C<op_next> chain until the end. No need to check other fields, strictly
  1029. linear through the tree.
  1030. int
  1031. Perl_runops_standard(pTHX)
  1032. {
  1033. dVAR;
  1034. while ((PL_op = CALL_FPTR(PL_op->op_ppaddr)(aTHX))) {
  1035. PERL_ASYNC_CHECK(); /* until 5.13.2 */
  1036. }
  1037. TAINT_NOT;
  1038. return 0;
  1039. }
  1040. To inspect the op tree within a perl program, you can also hook C<PL_runops> (see
  1041. above at L</"Pluggable runops">) to your own perl walker (see e.g. L<B::Utils>
  1042. for various useful walkers), but you cannot modify the tree from within the B
  1043. accessors, only via XS. Or via L<B::Generate> as explained in Simon Cozen's
  1044. "Hacking the Optree for Fun..." L<http://www.perl.com/pub/a/2002/05/07/optree.html>.
  1045. I<Todo: Show the other runloops, and esp. the B:Utils ones.>
  1046. I<Todo: Describe the dumper, the debugging and more extended walkers.>
  1047. =head1 SEE ALSO
  1048. =head2 Internal and external modifications
  1049. See the short description of the internal optimizer in the "Brief Summary".
  1050. I<Todo: Describe the exported variables and functions which can be
  1051. hooked, besides simply adding code to the blocks.>
  1052. Via L</"Pluggable runops"> you can provide your own walker function, as it
  1053. is done in most B modules. Best see L<B::Utils>.
  1054. You may also create custom ops at runtime (well, strictly speaking at
  1055. compile-time) via L<B::Generate>.
  1056. =head2 Modules
  1057. The most important op tree module is L<B::Concise> by Stephen McCamant.
  1058. L<B::Utils> provides abstract-enough op tree grep's and walkers with
  1059. callbacks from the perl level.
  1060. L<Devel::Hook> allows adding perl hooks into the BEGIN, CHECK,
  1061. UNITCHECK, INIT blocks.
  1062. L<Devel::TypeCheck> tries to verify possible static typing for
  1063. expressions and variables, a pretty hard problem for compilers,
  1064. esp. with such dynamic and untyped variables as Perl 5.
  1065. Reini Urban maintains the interactive op tree debugger L<B::Debugger>,
  1066. the Compiler suite (B::C, B::CC, B::Bytecode), L<B::Generate> and
  1067. is working on L<Jit>.
  1068. =head2 Various Articles
  1069. The best source of information is the source. It is very well documented.
  1070. There are some pod files from talks and workshops in F<ramblings/>.
  1071. From YAPC EU 2010 there is a good screencast at L<http://vimeo.com/14058377>.
  1072. Simon Cozens has posted the course material to NetThink's
  1073. L<http://books.simon-cozens.org/index.php/Perl_5_Internals#The_Lexer_and_the_Parser>
  1074. training course. This is the currently best available description on
  1075. that subject.
  1076. "Hacking the Optree for Fun..." at
  1077. L<http://www.perl.com/pub/a/2002/05/07/optree.html> is the next step by
  1078. Simon Cozens.
  1079. Scott Walters added more details at L<http://perldesignpatterns.com/?PerlAssembly>
  1080. Joshua ben Jore wrote a 50 minute presentation on "Perl 5
  1081. VM guts" at L<http://diotalevi.isa-geek.net/~josh/Presentations/Perl%205%20VM/>
  1082. focusing on the op tree for SPUG, the Seattle Perl User's Group.
  1083. Eric Wilhelm wrote a brief tour through the perl compiler backends for
  1084. the impatient refactorerer. The perl_guts_tour as mp3
  1085. L<http://scratchcomputing.com/developers/perl_guts_tour.html> or as
  1086. pdf L<http://scratchcomputing.com/developers/perl_guts_tour.pdf>
  1087. This text was created in this wiki article:
  1088. L<http://www.perlfoundation.org/perl5/index.cgi?optree_guts>
  1089. The with B::C released version should be more actual.
  1090. =head1 Conclusion
  1091. So this is about 30% of the basic op tree information so far. Not speaking about
  1092. the guts. Simon Cozens and Scott Walters have more 30%, in the source are more
  1093. 10% to copy&paste, and in the compilers and run-time information is the rest. I
  1094. hope with the help of some hackers we'll get it done, so that some people will
  1095. begin poking around in the B backends. And write the wonderful new C<dump>/C<undump>
  1096. functionality (which actually worked in the early years on Solaris) to
  1097. save-image and load-image at runtime as in LISP, analyse and optimize the
  1098. output, output PIR (parrot code), emit LLVM or another JIT optimized code or
  1099. even write assemblers. I have a simple one at home. :)
  1100. Written 2008 on the perl5 wiki with socialtext and pod in parallel
  1101. by Reini Urban, CPAN ID C<rurban>.