Debian Codegraph @

generic/tclAssembly.c

raw
1 /*
2 * tclAssembly.c --
3 *
4 * Assembler for Tcl bytecodes.
5 *
6 * This file contains the procedures that convert Tcl Assembly Language (TAL)
7 * to a sequence of bytecode instructions for the Tcl execution engine.
8 *
9 * Copyright (c) 2010 Ozgur Dogan Ugurlu.
10 * Copyright (c) 2010 Kevin B. Kenny.
11 *
12 * See the file "license.terms" for information on usage and redistribution of
13 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 */
15
16 /*-
17 *- THINGS TO DO:
18 *- More instructions:
19 *- done - alternate exit point (affects stack and exception range checking)
20 *- break and continue - if exception ranges can be sorted out.
21 *- foreach_start4, foreach_step4
22 *- returnImm, returnStk
23 *- expandStart, expandStkTop, invokeExpanded, expandDrop
24 *- dictFirst, dictNext, dictDone
25 *- dictUpdateStart, dictUpdateEnd
26 *- jumpTable testing
27 *- syntax (?)
28 *- returnCodeBranch
29 *- tclooNext, tclooNextClass
30 */
31
32 #include "tclInt.h"
33 #include "tclCompile.h"
34 #include "tclOOInt.h"
35
36 /*
37 * Structure that represents a range of instructions in the bytecode.
38 */
39
40 typedef struct CodeRange {
41 int startOffset; /* Start offset in the bytecode array */
42 int endOffset; /* End offset in the bytecode array */
43 } CodeRange;
44
45 /*
46 * State identified for a basic block's catch context.
47 */
48
49 typedef enum BasicBlockCatchState {
50 BBCS_UNKNOWN = 0, /* Catch context has not yet been identified */
51 BBCS_NONE, /* Block is outside of any catch */
52 BBCS_INCATCH, /* Block is within a catch context */
53 BBCS_CAUGHT /* Block is within a catch context and
54 * may be executed after an exception fires */
55 } BasicBlockCatchState;
56
57 /*
58 * Structure that defines a basic block - a linear sequence of bytecode
59 * instructions with no jumps in or out (including not changing the
60 * state of any exception range).
61 */
62
63 typedef struct BasicBlock {
64 int originalStartOffset; /* Instruction offset before JUMP1s were
65 * substituted with JUMP4's */
66 int startOffset; /* Instruction offset of the start of the
67 * block */
68 int startLine; /* Line number in the input script of the
69 * instruction at the start of the block */
70 int jumpOffset; /* Bytecode offset of the 'jump' instruction
71 * that ends the block, or -1 if there is no
72 * jump. */
73 int jumpLine; /* Line number in the input script of the
74 * 'jump' instruction that ends the block, or
75 * -1 if there is no jump */
76 struct BasicBlock* prevPtr; /* Immediate predecessor of this block */
77 struct BasicBlock* predecessor;
78 /* Predecessor of this block in the spanning
79 * tree */
80 struct BasicBlock* successor1;
81 /* BasicBlock structure of the following
82 * block: NULL at the end of the bytecode
83 * sequence. */
84 Tcl_Obj* jumpTarget; /* Jump target label if the jump target is
85 * unresolved */
86 int initialStackDepth; /* Absolute stack depth on entry */
87 int minStackDepth; /* Low-water relative stack depth */
88 int maxStackDepth; /* High-water relative stack depth */
89 int finalStackDepth; /* Relative stack depth on exit */
90 enum BasicBlockCatchState catchState;
91 /* State of the block for 'catch' analysis */
92 int catchDepth; /* Number of nested catches in which the basic
93 * block appears */
94 struct BasicBlock* enclosingCatch;
95 /* BasicBlock structure of the last startCatch
96 * executed on a path to this block, or NULL
97 * if there is no enclosing catch */
98 int foreignExceptionBase; /* Base index of foreign exceptions */
99 int foreignExceptionCount; /* Count of foreign exceptions */
100 ExceptionRange* foreignExceptions;
101 /* ExceptionRange structures for exception
102 * ranges belonging to embedded scripts and
103 * expressions in this block */
104 JumptableInfo* jtPtr; /* Jump table at the end of this basic block */
105 int flags; /* Boolean flags */
106 } BasicBlock;
107
108 /*
109 * Flags that pertain to a basic block.
110 */
111
112 enum BasicBlockFlags {
113 BB_VISITED = (1 << 0), /* Block has been visited in the current
114 * traversal */
115 BB_FALLTHRU = (1 << 1), /* Control may pass from this block to a
116 * successor */
117 BB_JUMP1 = (1 << 2), /* Basic block ends with a 1-byte-offset jump
118 * and may need expansion */
119 BB_JUMPTABLE = (1 << 3), /* Basic block ends with a jump table */
120 BB_BEGINCATCH = (1 << 4), /* Block ends with a 'beginCatch' instruction,
121 * marking it as the start of a 'catch'
122 * sequence. The 'jumpTarget' is the exception
123 * exit from the catch block. */
124 BB_ENDCATCH = (1 << 5) /* Block ends with an 'endCatch' instruction,
125 * unwinding the catch from the exception
126 * stack. */
127 };
128
129 /*
130 * Source instruction type recognized by the assembler.
131 */
132
133 typedef enum TalInstType {
134 ASSEM_1BYTE, /* Fixed arity, 1-byte instruction */
135 ASSEM_BEGIN_CATCH, /* Begin catch: one 4-byte jump offset to be
136 * converted to appropriate exception
137 * ranges */
138 ASSEM_BOOL, /* One Boolean operand */
139 ASSEM_BOOL_LVT4, /* One Boolean, one 4-byte LVT ref. */
140 ASSEM_CLOCK_READ, /* 1-byte unsigned-integer case number, in the
141 * range 0-3 */
142 ASSEM_CONCAT1, /* 1-byte unsigned-integer operand count, must
143 * be strictly positive, consumes N, produces
144 * 1 */
145 ASSEM_DICT_GET, /* 'dict get' and related - consumes N+1
146 * operands, produces 1, N > 0 */
147 ASSEM_DICT_SET, /* specifies key count and LVT index, consumes
148 * N+1 operands, produces 1, N > 0 */
149 ASSEM_DICT_UNSET, /* specifies key count and LVT index, consumes
150 * N operands, produces 1, N > 0 */
151 ASSEM_END_CATCH, /* End catch. No args. Exception range popped
152 * from stack and stack pointer restored. */
153 ASSEM_EVAL, /* 'eval' - evaluate a constant script (by
154 * compiling it in line with the assembly
155 * code! I love Tcl!) */
156 ASSEM_INDEX, /* 4 byte operand, integer or end-integer */
157 ASSEM_INVOKE, /* 1- or 4-byte operand count, must be
158 * strictly positive, consumes N, produces
159 * 1. */
160 ASSEM_JUMP, /* Jump instructions */
161 ASSEM_JUMP4, /* Jump instructions forcing a 4-byte offset */
162 ASSEM_JUMPTABLE, /* Jumptable (switch -exact) */
163 ASSEM_LABEL, /* The assembly directive that defines a
164 * label */
165 ASSEM_LINDEX_MULTI, /* 4-byte operand count, must be strictly
166 * positive, consumes N, produces 1 */
167 ASSEM_LIST, /* 4-byte operand count, must be nonnegative,
168 * consumses N, produces 1 */
169 ASSEM_LSET_FLAT, /* 4-byte operand count, must be >= 3,
170 * consumes N, produces 1 */
171 ASSEM_LVT, /* One operand that references a local
172 * variable */
173 ASSEM_LVT1, /* One 1-byte operand that references a local
174 * variable */
175 ASSEM_LVT1_SINT1, /* One 1-byte operand that references a local
176 * variable, one signed-integer 1-byte
177 * operand */
178 ASSEM_LVT4, /* One 4-byte operand that references a local
179 * variable */
180 ASSEM_OVER, /* OVER: 4-byte operand count, consumes N+1,
181 * produces N+2 */
182 ASSEM_PUSH, /* one literal operand */
183 ASSEM_REGEXP, /* One Boolean operand, but weird mapping to
184 * call flags */
185 ASSEM_REVERSE, /* REVERSE: 4-byte operand count, consumes N,
186 * produces N */
187 ASSEM_SINT1, /* One 1-byte signed-integer operand
188 * (INCR_STK_IMM) */
189 ASSEM_SINT4_LVT4 /* Signed 4-byte integer operand followed by
190 * LVT entry. Fixed arity */
191 } TalInstType;
192
193 /*
194 * Description of an instruction recognized by the assembler.
195 */
196
197 typedef struct TalInstDesc {
198 const char *name; /* Name of instruction. */
199 TalInstType instType; /* The type of instruction */
200 int tclInstCode; /* Instruction code. For instructions having
201 * 1- and 4-byte variables, tclInstCode is
202 * ((1byte)<<8) || (4byte) */
203 int operandsConsumed; /* Number of operands consumed by the
204 * operation, or INT_MIN if the operation is
205 * variadic */
206 int operandsProduced; /* Number of operands produced by the
207 * operation. If negative, the operation has a
208 * net stack effect of -1-operandsProduced */
209 } TalInstDesc;
210
211 /*
212 * Structure that holds the state of the assembler while generating code.
213 */
214
215 typedef struct AssemblyEnv {
216 CompileEnv* envPtr; /* Compilation environment being used for code
217 * generation */
218 Tcl_Parse* parsePtr; /* Parse of the current line of source */
219 Tcl_HashTable labelHash; /* Hash table whose keys are labels and whose
220 * values are 'label' objects storing the code
221 * offsets of the labels. */
222 int cmdLine; /* Current line number within the assembly
223 * code */
224 int* clNext; /* Invisible continuation line for
225 * [info frame] */
226 BasicBlock* head_bb; /* First basic block in the code */
227 BasicBlock* curr_bb; /* Current basic block */
228 int maxDepth; /* Maximum stack depth encountered */
229 int curCatchDepth; /* Current depth of catches */
230 int maxCatchDepth; /* Maximum depth of catches encountered */
231 int flags; /* Compilation flags (TCL_EVAL_DIRECT) */
232 } AssemblyEnv;
233
234 /*
235 * Static functions defined in this file.
236 */
237
238 static void AddBasicBlockRangeToErrorInfo(AssemblyEnv*,
239 BasicBlock*);
240 static BasicBlock * AllocBB(AssemblyEnv*);
241 static int AssembleOneLine(AssemblyEnv* envPtr);
242 static void BBAdjustStackDepth(BasicBlock* bbPtr, int consumed,
243 int produced);
244 static void BBUpdateStackReqs(BasicBlock* bbPtr, int tblIdx,
245 int count);
246 static void BBEmitInstInt1(AssemblyEnv* assemEnvPtr, int tblIdx,
247 int opnd, int count);
248 static void BBEmitInstInt4(AssemblyEnv* assemEnvPtr, int tblIdx,
249 int opnd, int count);
250 static void BBEmitInst1or4(AssemblyEnv* assemEnvPtr, int tblIdx,
251 int param, int count);
252 static void BBEmitOpcode(AssemblyEnv* assemEnvPtr, int tblIdx,
253 int count);
254 static int BuildExceptionRanges(AssemblyEnv* assemEnvPtr);
255 static int CalculateJumpRelocations(AssemblyEnv*, int*);
256 static int CheckForUnclosedCatches(AssemblyEnv*);
257 static int CheckForThrowInWrongContext(AssemblyEnv*);
258 static int CheckNonThrowingBlock(AssemblyEnv*, BasicBlock*);
259 static int BytecodeMightThrow(unsigned char);
260 static int CheckJumpTableLabels(AssemblyEnv*, BasicBlock*);
261 static int CheckNamespaceQualifiers(Tcl_Interp*, const char*,
262 int);
263 static int CheckNonNegative(Tcl_Interp*, int);
264 static int CheckOneByte(Tcl_Interp*, int);
265 static int CheckSignedOneByte(Tcl_Interp*, int);
266 static int CheckStack(AssemblyEnv*);
267 static int CheckStrictlyPositive(Tcl_Interp*, int);
268 static ByteCode * CompileAssembleObj(Tcl_Interp *interp,
269 Tcl_Obj *objPtr);
270 static void CompileEmbeddedScript(AssemblyEnv*, Tcl_Token*,
271 const TalInstDesc*);
272 static int DefineLabel(AssemblyEnv* envPtr, const char* label);
273 static void DeleteMirrorJumpTable(JumptableInfo* jtPtr);
274 static Tcl_DupInternalRepProc DupAssembleCodeInternalRep;
275 static void FillInJumpOffsets(AssemblyEnv*);
276 static int CreateMirrorJumpTable(AssemblyEnv* assemEnvPtr,
277 Tcl_Obj* jumpTable);
278 static int FindLocalVar(AssemblyEnv* envPtr,
279 Tcl_Token** tokenPtrPtr);
280 static int FinishAssembly(AssemblyEnv*);
281 static Tcl_FreeInternalRepProc FreeAssembleCodeInternalRep;
282 static void FreeAssemblyEnv(AssemblyEnv*);
283 static int GetBooleanOperand(AssemblyEnv*, Tcl_Token**, int*);
284 static int GetListIndexOperand(AssemblyEnv*, Tcl_Token**, int*);
285 static int GetIntegerOperand(AssemblyEnv*, Tcl_Token**, int*);
286 static int GetNextOperand(AssemblyEnv*, Tcl_Token**, Tcl_Obj**);
287 static void LookForFreshCatches(BasicBlock*, BasicBlock**);
288 static void MoveCodeForJumps(AssemblyEnv*, int);
289 static void MoveExceptionRangesToBasicBlock(AssemblyEnv*, int);
290 static AssemblyEnv* NewAssemblyEnv(CompileEnv*, int);
291 static int ProcessCatches(AssemblyEnv*);
292 static int ProcessCatchesInBasicBlock(AssemblyEnv*, BasicBlock*,
293 BasicBlock*, enum BasicBlockCatchState, int);
294 static void ResetVisitedBasicBlocks(AssemblyEnv*);
295 static void ResolveJumpTableTargets(AssemblyEnv*, BasicBlock*);
296 static void ReportUndefinedLabel(AssemblyEnv*, BasicBlock*,
297 Tcl_Obj*);
298 static void RestoreEmbeddedExceptionRanges(AssemblyEnv*);
299 static int StackCheckBasicBlock(AssemblyEnv*, BasicBlock *,
300 BasicBlock *, int);
301 static BasicBlock* StartBasicBlock(AssemblyEnv*, int fallthrough,
302 Tcl_Obj* jumpLabel);
303 /* static int AdvanceIp(const unsigned char *pc); */
304 static int StackCheckBasicBlock(AssemblyEnv*, BasicBlock *,
305 BasicBlock *, int);
306 static int StackCheckExit(AssemblyEnv*);
307 static void StackFreshCatches(AssemblyEnv*, BasicBlock*, int,
308 BasicBlock**, int*);
309 static void SyncStackDepth(AssemblyEnv*);
310 static int TclAssembleCode(CompileEnv* envPtr, const char* code,
311 int codeLen, int flags);
312 static void UnstackExpiredCatches(CompileEnv*, BasicBlock*, int,
313 BasicBlock**, int*);
314
315 /*
316 * Tcl_ObjType that describes bytecode emitted by the assembler.
317 */
318
319 static const Tcl_ObjType assembleCodeType = {
320 "assemblecode",
321 FreeAssembleCodeInternalRep, /* freeIntRepProc */
322 DupAssembleCodeInternalRep, /* dupIntRepProc */
323 NULL, /* updateStringProc */
324 NULL /* setFromAnyProc */
325 };
326
327 /*
328 * Source instructions recognized in the Tcl Assembly Language (TAL)
329 */
330
331 static const TalInstDesc TalInstructionTable[] = {
332 /* PUSH must be first, see the code near the end of TclAssembleCode */
333 {"push", ASSEM_PUSH, (INST_PUSH1<<8
334 | INST_PUSH4), 0, 1},
335
336 {"add", ASSEM_1BYTE, INST_ADD, 2, 1},
337 {"append", ASSEM_LVT, (INST_APPEND_SCALAR1<<8
338 | INST_APPEND_SCALAR4),1, 1},
339 {"appendArray", ASSEM_LVT, (INST_APPEND_ARRAY1<<8
340 | INST_APPEND_ARRAY4), 2, 1},
341 {"appendArrayStk", ASSEM_1BYTE, INST_APPEND_ARRAY_STK, 3, 1},
342 {"appendStk", ASSEM_1BYTE, INST_APPEND_STK, 2, 1},
343 {"arrayExistsImm", ASSEM_LVT4, INST_ARRAY_EXISTS_IMM, 0, 1},
344 {"arrayExistsStk", ASSEM_1BYTE, INST_ARRAY_EXISTS_STK, 1, 1},
345 {"arrayMakeImm", ASSEM_LVT4, INST_ARRAY_MAKE_IMM, 0, 0},
346 {"arrayMakeStk", ASSEM_1BYTE, INST_ARRAY_MAKE_STK, 1, 0},
347 {"beginCatch", ASSEM_BEGIN_CATCH,
348 INST_BEGIN_CATCH4, 0, 0},
349 {"bitand", ASSEM_1BYTE, INST_BITAND, 2, 1},
350 {"bitnot", ASSEM_1BYTE, INST_BITNOT, 1, 1},
351 {"bitor", ASSEM_1BYTE, INST_BITOR, 2, 1},
352 {"bitxor", ASSEM_1BYTE, INST_BITXOR, 2, 1},
353 {"clockRead", ASSEM_CLOCK_READ, INST_CLOCK_READ, 0, 1},
354 {"concat", ASSEM_CONCAT1, INST_STR_CONCAT1, INT_MIN,1},
355 {"concatStk", ASSEM_LIST, INST_CONCAT_STK, INT_MIN,1},
356 {"coroName", ASSEM_1BYTE, INST_COROUTINE_NAME, 0, 1},
357 {"currentNamespace",ASSEM_1BYTE, INST_NS_CURRENT, 0, 1},
358 {"dictAppend", ASSEM_LVT4, INST_DICT_APPEND, 2, 1},
359 {"dictExists", ASSEM_DICT_GET, INST_DICT_EXISTS, INT_MIN,1},
360 {"dictExpand", ASSEM_1BYTE, INST_DICT_EXPAND, 3, 1},
361 {"dictGet", ASSEM_DICT_GET, INST_DICT_GET, INT_MIN,1},
362 {"dictIncrImm", ASSEM_SINT4_LVT4,
363 INST_DICT_INCR_IMM, 1, 1},
364 {"dictLappend", ASSEM_LVT4, INST_DICT_LAPPEND, 2, 1},
365 {"dictRecombineStk",ASSEM_1BYTE, INST_DICT_RECOMBINE_STK,3, 0},
366 {"dictRecombineImm",ASSEM_LVT4, INST_DICT_RECOMBINE_IMM,2, 0},
367 {"dictSet", ASSEM_DICT_SET, INST_DICT_SET, INT_MIN,1},
368 {"dictUnset", ASSEM_DICT_UNSET,
369 INST_DICT_UNSET, INT_MIN,1},
370 {"div", ASSEM_1BYTE, INST_DIV, 2, 1},
371 {"dup", ASSEM_1BYTE, INST_DUP, 1, 2},
372 {"endCatch", ASSEM_END_CATCH,INST_END_CATCH, 0, 0},
373 {"eq", ASSEM_1BYTE, INST_EQ, 2, 1},
374 {"eval", ASSEM_EVAL, INST_EVAL_STK, 1, 1},
375 {"evalStk", ASSEM_1BYTE, INST_EVAL_STK, 1, 1},
376 {"exist", ASSEM_LVT4, INST_EXIST_SCALAR, 0, 1},
377 {"existArray", ASSEM_LVT4, INST_EXIST_ARRAY, 1, 1},
378 {"existArrayStk", ASSEM_1BYTE, INST_EXIST_ARRAY_STK, 2, 1},
379 {"existStk", ASSEM_1BYTE, INST_EXIST_STK, 1, 1},
380 {"expon", ASSEM_1BYTE, INST_EXPON, 2, 1},
381 {"expr", ASSEM_EVAL, INST_EXPR_STK, 1, 1},
382 {"exprStk", ASSEM_1BYTE, INST_EXPR_STK, 1, 1},
383 {"ge", ASSEM_1BYTE, INST_GE, 2, 1},
384 {"gt", ASSEM_1BYTE, INST_GT, 2, 1},
385 {"incr", ASSEM_LVT1, INST_INCR_SCALAR1, 1, 1},
386 {"incrArray", ASSEM_LVT1, INST_INCR_ARRAY1, 2, 1},
387 {"incrArrayImm", ASSEM_LVT1_SINT1,
388 INST_INCR_ARRAY1_IMM, 1, 1},
389 {"incrArrayStk", ASSEM_1BYTE, INST_INCR_ARRAY_STK, 3, 1},
390 {"incrArrayStkImm", ASSEM_SINT1, INST_INCR_ARRAY_STK_IMM,2, 1},
391 {"incrImm", ASSEM_LVT1_SINT1,
392 INST_INCR_SCALAR1_IMM, 0, 1},
393 {"incrStk", ASSEM_1BYTE, INST_INCR_STK, 2, 1},
394 {"incrStkImm", ASSEM_SINT1, INST_INCR_STK_IMM, 1, 1},
395 {"infoLevelArgs", ASSEM_1BYTE, INST_INFO_LEVEL_ARGS, 1, 1},
396 {"infoLevelNumber", ASSEM_1BYTE, INST_INFO_LEVEL_NUM, 0, 1},
397 {"invokeStk", ASSEM_INVOKE, (INST_INVOKE_STK1 << 8
398 | INST_INVOKE_STK4), INT_MIN,1},
399 {"jump", ASSEM_JUMP, INST_JUMP1, 0, 0},
400 {"jump4", ASSEM_JUMP4, INST_JUMP4, 0, 0},
401 {"jumpFalse", ASSEM_JUMP, INST_JUMP_FALSE1, 1, 0},
402 {"jumpFalse4", ASSEM_JUMP4, INST_JUMP_FALSE4, 1, 0},
403 {"jumpTable", ASSEM_JUMPTABLE,INST_JUMP_TABLE, 1, 0},
404 {"jumpTrue", ASSEM_JUMP, INST_JUMP_TRUE1, 1, 0},
405 {"jumpTrue4", ASSEM_JUMP4, INST_JUMP_TRUE4, 1, 0},
406 {"label", ASSEM_LABEL, 0, 0, 0},
407 {"land", ASSEM_1BYTE, INST_LAND, 2, 1},
408 {"lappend", ASSEM_LVT, (INST_LAPPEND_SCALAR1<<8
409 | INST_LAPPEND_SCALAR4),
410 1, 1},
411 {"lappendArray", ASSEM_LVT, (INST_LAPPEND_ARRAY1<<8
412 | INST_LAPPEND_ARRAY4),2, 1},
413 {"lappendArrayStk", ASSEM_1BYTE, INST_LAPPEND_ARRAY_STK, 3, 1},
414 {"lappendList", ASSEM_LVT4, INST_LAPPEND_LIST, 1, 1},
415 {"lappendListArray",ASSEM_LVT4, INST_LAPPEND_LIST_ARRAY,2, 1},
416 {"lappendListArrayStk", ASSEM_1BYTE,INST_LAPPEND_LIST_ARRAY_STK, 3, 1},
417 {"lappendListStk", ASSEM_1BYTE, INST_LAPPEND_LIST_STK, 2, 1},
418 {"lappendStk", ASSEM_1BYTE, INST_LAPPEND_STK, 2, 1},
419 {"le", ASSEM_1BYTE, INST_LE, 2, 1},
420 {"lindexMulti", ASSEM_LINDEX_MULTI,
421 INST_LIST_INDEX_MULTI, INT_MIN,1},
422 {"list", ASSEM_LIST, INST_LIST, INT_MIN,1},
423 {"listConcat", ASSEM_1BYTE, INST_LIST_CONCAT, 2, 1},
424 {"listIn", ASSEM_1BYTE, INST_LIST_IN, 2, 1},
425 {"listIndex", ASSEM_1BYTE, INST_LIST_INDEX, 2, 1},
426 {"listIndexImm", ASSEM_INDEX, INST_LIST_INDEX_IMM, 1, 1},
427 {"listLength", ASSEM_1BYTE, INST_LIST_LENGTH, 1, 1},
428 {"listNotIn", ASSEM_1BYTE, INST_LIST_NOT_IN, 2, 1},
429 {"load", ASSEM_LVT, (INST_LOAD_SCALAR1 << 8
430 | INST_LOAD_SCALAR4), 0, 1},
431 {"loadArray", ASSEM_LVT, (INST_LOAD_ARRAY1<<8
432 | INST_LOAD_ARRAY4), 1, 1},
433 {"loadArrayStk", ASSEM_1BYTE, INST_LOAD_ARRAY_STK, 2, 1},
434 {"loadStk", ASSEM_1BYTE, INST_LOAD_STK, 1, 1},
435 {"lor", ASSEM_1BYTE, INST_LOR, 2, 1},
436 {"lsetFlat", ASSEM_LSET_FLAT,INST_LSET_FLAT, INT_MIN,1},
437 {"lsetList", ASSEM_1BYTE, INST_LSET_LIST, 3, 1},
438 {"lshift", ASSEM_1BYTE, INST_LSHIFT, 2, 1},
439 {"lt", ASSEM_1BYTE, INST_LT, 2, 1},
440 {"mod", ASSEM_1BYTE, INST_MOD, 2, 1},
441 {"mult", ASSEM_1BYTE, INST_MULT, 2, 1},
442 {"neq", ASSEM_1BYTE, INST_NEQ, 2, 1},
443 {"nop", ASSEM_1BYTE, INST_NOP, 0, 0},
444 {"not", ASSEM_1BYTE, INST_LNOT, 1, 1},
445 {"nsupvar", ASSEM_LVT4, INST_NSUPVAR, 2, 1},
446 {"numericType", ASSEM_1BYTE, INST_NUM_TYPE, 1, 1},
447 {"originCmd", ASSEM_1BYTE, INST_ORIGIN_COMMAND, 1, 1},
448 {"over", ASSEM_OVER, INST_OVER, INT_MIN,-1-1},
449 {"pop", ASSEM_1BYTE, INST_POP, 1, 0},
450 {"pushReturnCode", ASSEM_1BYTE, INST_PUSH_RETURN_CODE, 0, 1},
451 {"pushReturnOpts", ASSEM_1BYTE, INST_PUSH_RETURN_OPTIONS,
452 0, 1},
453 {"pushResult", ASSEM_1BYTE, INST_PUSH_RESULT, 0, 1},
454 {"regexp", ASSEM_REGEXP, INST_REGEXP, 2, 1},
455 {"resolveCmd", ASSEM_1BYTE, INST_RESOLVE_COMMAND, 1, 1},
456 {"reverse", ASSEM_REVERSE, INST_REVERSE, INT_MIN,-1-0},
457 {"rshift", ASSEM_1BYTE, INST_RSHIFT, 2, 1},
458 {"store", ASSEM_LVT, (INST_STORE_SCALAR1<<8
459 | INST_STORE_SCALAR4), 1, 1},
460 {"storeArray", ASSEM_LVT, (INST_STORE_ARRAY1<<8
461 | INST_STORE_ARRAY4), 2, 1},
462 {"storeArrayStk", ASSEM_1BYTE, INST_STORE_ARRAY_STK, 3, 1},
463 {"storeStk", ASSEM_1BYTE, INST_STORE_STK, 2, 1},
464 {"strcaseLower", ASSEM_1BYTE, INST_STR_LOWER, 1, 1},
465 {"strcaseTitle", ASSEM_1BYTE, INST_STR_TITLE, 1, 1},
466 {"strcaseUpper", ASSEM_1BYTE, INST_STR_UPPER, 1, 1},
467 {"strcmp", ASSEM_1BYTE, INST_STR_CMP, 2, 1},
468 {"strcat", ASSEM_CONCAT1, INST_STR_CONCAT1, INT_MIN,1},
469 {"streq", ASSEM_1BYTE, INST_STR_EQ, 2, 1},
470 {"strfind", ASSEM_1BYTE, INST_STR_FIND, 2, 1},
471 {"strindex", ASSEM_1BYTE, INST_STR_INDEX, 2, 1},
472 {"strlen", ASSEM_1BYTE, INST_STR_LEN, 1, 1},
473 {"strmap", ASSEM_1BYTE, INST_STR_MAP, 3, 1},
474 {"strmatch", ASSEM_BOOL, INST_STR_MATCH, 2, 1},
475 {"strneq", ASSEM_1BYTE, INST_STR_NEQ, 2, 1},
476 {"strrange", ASSEM_1BYTE, INST_STR_RANGE, 3, 1},
477 {"strreplace", ASSEM_1BYTE, INST_STR_REPLACE, 4, 1},
478 {"strrfind", ASSEM_1BYTE, INST_STR_FIND_LAST, 2, 1},
479 {"strtrim", ASSEM_1BYTE, INST_STR_TRIM, 2, 1},
480 {"strtrimLeft", ASSEM_1BYTE, INST_STR_TRIM_LEFT, 2, 1},
481 {"strtrimRight", ASSEM_1BYTE, INST_STR_TRIM_RIGHT, 2, 1},
482 {"sub", ASSEM_1BYTE, INST_SUB, 2, 1},
483 {"tclooClass", ASSEM_1BYTE, INST_TCLOO_CLASS, 1, 1},
484 {"tclooIsObject", ASSEM_1BYTE, INST_TCLOO_IS_OBJECT, 1, 1},
485 {"tclooNamespace", ASSEM_1BYTE, INST_TCLOO_NS, 1, 1},
486 {"tclooSelf", ASSEM_1BYTE, INST_TCLOO_SELF, 0, 1},
487 {"tryCvtToBoolean", ASSEM_1BYTE, INST_TRY_CVT_TO_BOOLEAN,1, 2},
488 {"tryCvtToNumeric", ASSEM_1BYTE, INST_TRY_CVT_TO_NUMERIC,1, 1},
489 {"uminus", ASSEM_1BYTE, INST_UMINUS, 1, 1},
490 {"unset", ASSEM_BOOL_LVT4,INST_UNSET_SCALAR, 0, 0},
491 {"unsetArray", ASSEM_BOOL_LVT4,INST_UNSET_ARRAY, 1, 0},
492 {"unsetArrayStk", ASSEM_BOOL, INST_UNSET_ARRAY_STK, 2, 0},
493 {"unsetStk", ASSEM_BOOL, INST_UNSET_STK, 1, 0},
494 {"uplus", ASSEM_1BYTE, INST_UPLUS, 1, 1},
495 {"upvar", ASSEM_LVT4, INST_UPVAR, 2, 1},
496 {"variable", ASSEM_LVT4, INST_VARIABLE, 1, 0},
497 {"verifyDict", ASSEM_1BYTE, INST_DICT_VERIFY, 1, 0},
498 {"yield", ASSEM_1BYTE, INST_YIELD, 1, 1},
499 {NULL, ASSEM_1BYTE, 0, 0, 0}
500 };
501
502 /*
503 * List of instructions that cannot throw an exception under any
504 * circumstances. These instructions are the ones that are permissible after
505 * an exception is caught but before the corresponding exception range is
506 * popped from the stack.
507 * The instructions must be in ascending order by numeric operation code.
508 */
509
510 static const unsigned char NonThrowingByteCodes[] = {
511 INST_PUSH1, INST_PUSH4, INST_POP, INST_DUP, /* 1-4 */
512 INST_JUMP1, INST_JUMP4, /* 34-35 */
513 INST_END_CATCH, INST_PUSH_RESULT, INST_PUSH_RETURN_CODE, /* 70-72 */
514 INST_STR_EQ, INST_STR_NEQ, INST_STR_CMP, INST_STR_LEN, /* 73-76 */
515 INST_LIST, /* 79 */
516 INST_OVER, /* 95 */
517 INST_PUSH_RETURN_OPTIONS, /* 108 */
518 INST_REVERSE, /* 126 */
519 INST_NOP, /* 132 */
520 INST_STR_MAP, /* 143 */
521 INST_STR_FIND, /* 144 */
522 INST_COROUTINE_NAME, /* 149 */
523 INST_NS_CURRENT, /* 151 */
524 INST_INFO_LEVEL_NUM, /* 152 */
525 INST_RESOLVE_COMMAND, /* 154 */
526 INST_STR_TRIM, INST_STR_TRIM_LEFT, INST_STR_TRIM_RIGHT, /* 166-168 */
527 INST_CONCAT_STK, /* 169 */
528 INST_STR_UPPER, INST_STR_LOWER, INST_STR_TITLE, /* 170-172 */
529 INST_NUM_TYPE /* 180 */
530 };
531
532 /*
533 * Helper macros.
534 */
535
536 #if defined(TCL_DEBUG_ASSEMBLY) && defined(__GNUC__) && __GNUC__ > 2
537 #define DEBUG_PRINT(...) fprintf(stderr, ##__VA_ARGS__);fflush(stderr)
538 #elif defined(__GNUC__) && __GNUC__ > 2
539 #define DEBUG_PRINT(...) /* nothing */
540 #else
541 #define DEBUG_PRINT /* nothing */
542 #endif
543
544 /*
545 *-----------------------------------------------------------------------------
546 *
547 * BBAdjustStackDepth --
548 *
549 * When an opcode is emitted, adjusts the stack information in the basic
550 * block to reflect the number of operands produced and consumed.
551 *
552 * Results:
553 * None.
554 *
555 * Side effects:
556 * Updates minimum, maximum and final stack requirements in the basic
557 * block.
558 *
559 *-----------------------------------------------------------------------------
560 */
561
562 static void
563 BBAdjustStackDepth(
564 BasicBlock *bbPtr, /* Structure describing the basic block */
565 int consumed, /* Count of operands consumed by the
566 * operation */
567 int produced) /* Count of operands produced by the
568 * operation */
569 {
570 int depth = bbPtr->finalStackDepth;
571
572 depth -= consumed;
573 if (depth < bbPtr->minStackDepth) {
574 bbPtr->minStackDepth = depth;
575 }
576 depth += produced;
577 if (depth > bbPtr->maxStackDepth) {
578 bbPtr->maxStackDepth = depth;
579 }
580 bbPtr->finalStackDepth = depth;
581 }
582
583 /*
584 *-----------------------------------------------------------------------------
585 *
586 * BBUpdateStackReqs --
587 *
588 * Updates the stack requirements of a basic block, given the opcode
589 * being emitted and an operand count.
590 *
591 * Results:
592 * None.
593 *
594 * Side effects:
595 * Updates min, max and final stack requirements in the basic block.
596 *
597 * Notes:
598 * This function must not be called for instructions such as REVERSE and
599 * OVER that are variadic but do not consume all their operands. Instead,
600 * BBAdjustStackDepth should be called directly.
601 *
602 * count should be provided only for variadic operations. For operations
603 * with known arity, count should be 0.
604 *
605 *-----------------------------------------------------------------------------
606 */
607
608 static void
609 BBUpdateStackReqs(
610 BasicBlock* bbPtr, /* Structure describing the basic block */
611 int tblIdx, /* Index in TalInstructionTable of the
612 * operation being assembled */
613 int count) /* Count of operands for variadic insts */
614 {
615 int consumed = TalInstructionTable[tblIdx].operandsConsumed;
616 int produced = TalInstructionTable[tblIdx].operandsProduced;
617
618 if (consumed == INT_MIN) {
619 /*
620 * The instruction is variadic; it consumes 'count' operands.
621 */
622
623 consumed = count;
624 }
625 if (produced < 0) {
626 /*
627 * The instruction leaves some of its variadic operands on the stack,
628 * with net stack effect of '-1-produced'
629 */
630
631 produced = consumed - produced - 1;
632 }
633 BBAdjustStackDepth(bbPtr, consumed, produced);
634 }
635
636 /*
637 *-----------------------------------------------------------------------------
638 *
639 * BBEmitOpcode, BBEmitInstInt1, BBEmitInstInt4 --
640 *
641 * Emit the opcode part of an instruction, or the entirety of an
642 * instruction with a 1- or 4-byte operand, and adjust stack
643 * requirements.
644 *
645 * Results:
646 * None.
647 *
648 * Side effects:
649 * Stores instruction and operand in the operand stream, and adjusts the
650 * stack.
651 *
652 *-----------------------------------------------------------------------------
653 */
654
655 static void
656 BBEmitOpcode(
657 AssemblyEnv* assemEnvPtr, /* Assembly environment */
658 int tblIdx, /* Table index in TalInstructionTable of op */
659 int count) /* Operand count for variadic ops */
660 {
661 CompileEnv* envPtr = assemEnvPtr->envPtr;
662 /* Compilation environment */
663 BasicBlock* bbPtr = assemEnvPtr->curr_bb;
664 /* Current basic block */
665 int op = TalInstructionTable[tblIdx].tclInstCode & 0xFF;
666
667 /*
668 * If this is the first instruction in a basic block, record its line
669 * number.
670 */
671
672 if (bbPtr->startOffset == envPtr->codeNext - envPtr->codeStart) {
673 bbPtr->startLine = assemEnvPtr->cmdLine;
674 }
675
676 TclEmitInt1(op, envPtr);
677 TclUpdateAtCmdStart(op, envPtr);
678 BBUpdateStackReqs(bbPtr, tblIdx, count);
679 }
680
681 static void
682 BBEmitInstInt1(
683 AssemblyEnv* assemEnvPtr, /* Assembly environment */
684 int tblIdx, /* Index in TalInstructionTable of op */
685 int opnd, /* 1-byte operand */
686 int count) /* Operand count for variadic ops */
687 {
688 BBEmitOpcode(assemEnvPtr, tblIdx, count);
689 TclEmitInt1(opnd, assemEnvPtr->envPtr);
690 }
691
692 static void
693 BBEmitInstInt4(
694 AssemblyEnv* assemEnvPtr, /* Assembly environment */
695 int tblIdx, /* Index in TalInstructionTable of op */
696 int opnd, /* 4-byte operand */
697 int count) /* Operand count for variadic ops */
698 {
699 BBEmitOpcode(assemEnvPtr, tblIdx, count);
700 TclEmitInt4(opnd, assemEnvPtr->envPtr);
701 }
702
703 /*
704 *-----------------------------------------------------------------------------
705 *
706 * BBEmitInst1or4 --
707 *
708 * Emits a 1- or 4-byte operation according to the magnitude of the
709 * operand.
710 *
711 *-----------------------------------------------------------------------------
712 */
713
714 static void
715 BBEmitInst1or4(
716 AssemblyEnv* assemEnvPtr, /* Assembly environment */
717 int tblIdx, /* Index in TalInstructionTable of op */
718 int param, /* Variable-length parameter */
719 int count) /* Arity if variadic */
720 {
721 CompileEnv* envPtr = assemEnvPtr->envPtr;
722 /* Compilation environment */
723 BasicBlock* bbPtr = assemEnvPtr->curr_bb;
724 /* Current basic block */
725 int op = TalInstructionTable[tblIdx].tclInstCode;
726
727 if (param <= 0xFF) {
728 op >>= 8;
729 } else {
730 op &= 0xFF;
731 }
732 TclEmitInt1(op, envPtr);
733 if (param <= 0xFF) {
734 TclEmitInt1(param, envPtr);
735 } else {
736 TclEmitInt4(param, envPtr);
737 }
738 TclUpdateAtCmdStart(op, envPtr);
739 BBUpdateStackReqs(bbPtr, tblIdx, count);
740 }
741
742 /*
743 *-----------------------------------------------------------------------------
744 *
745 * Tcl_AssembleObjCmd, TclNRAssembleObjCmd --
746 *
747 * Direct evaluation path for tcl::unsupported::assemble
748 *
749 * Results:
750 * Returns a standard Tcl result.
751 *
752 * Side effects:
753 * Assembles the code in objv[1], and executes it, so side effects
754 * include whatever the code does.
755 *
756 *-----------------------------------------------------------------------------
757 */
758
759 int
760 Tcl_AssembleObjCmd(
761 void *clientData, /* clientData */
762 Tcl_Interp *interp, /* Current interpreter. */
763 int objc, /* Number of arguments. */
764 Tcl_Obj *const objv[]) /* Argument objects. */
765 {
766 /*
767 * Boilerplate - make sure that there is an NRE trampoline on the C stack
768 * because there needs to be one in place to execute bytecode.
769 */
770
771 return Tcl_NRCallObjProc(interp, TclNRAssembleObjCmd, clientData, objc, objv);
772 }
773
774 int
775 TclNRAssembleObjCmd(
776 void *dummy, /* Not used. */
777 Tcl_Interp *interp, /* Current interpreter. */
778 int objc, /* Number of arguments. */
779 Tcl_Obj *const objv[]) /* Argument objects. */
780 {
781 ByteCode *codePtr; /* Pointer to the bytecode to execute */
782 Tcl_Obj* backtrace; /* Object where extra error information is
783 * constructed. */
784
785 (void)dummy;
786 if (objc != 2) {
787 Tcl_WrongNumArgs(interp, 1, objv, "bytecodeList");
788 return TCL_ERROR;
789 }
790
791 /*
792 * Assemble the source to bytecode.
793 */
794
795 codePtr = CompileAssembleObj(interp, objv[1]);
796
797 /*
798 * On failure, report error line.
799 */
800
801 if (codePtr == NULL) {
802 Tcl_AddErrorInfo(interp, "\n (\"");
803 Tcl_AppendObjToErrorInfo(interp, objv[0]);
804 Tcl_AddErrorInfo(interp, "\" body, line ");
805 TclNewIntObj(backtrace, Tcl_GetErrorLine(interp));
806 Tcl_AppendObjToErrorInfo(interp, backtrace);
807 Tcl_AddErrorInfo(interp, ")");
808 return TCL_ERROR;
809 }
810
811 /*
812 * Use NRE to evaluate the bytecode from the trampoline.
813 */
814
815 return TclNRExecuteByteCode(interp, codePtr);
816 }
817
818 /*
819 *-----------------------------------------------------------------------------
820 *
821 * CompileAssembleObj --
822 *
823 * Sets up and assembles Tcl bytecode for the direct-execution path in
824 * the Tcl bytecode assembler.
825 *
826 * Results:
827 * Returns a pointer to the assembled code. Returns NULL if the assembly
828 * fails for any reason, with an appropriate error message in the
829 * interpreter.
830 *
831 *-----------------------------------------------------------------------------
832 */
833
834 static ByteCode *
835 CompileAssembleObj(
836 Tcl_Interp *interp, /* Tcl interpreter */
837 Tcl_Obj *objPtr) /* Source code to assemble */
838 {
839 Interp *iPtr = (Interp *) interp;
840 /* Internals of the interpreter */
841 CompileEnv compEnv; /* Compilation environment structure */
842 ByteCode *codePtr = NULL;
843 /* Bytecode resulting from the assembly */
844 Namespace* namespacePtr; /* Namespace in which variable and command
845 * names in the bytecode resolve */
846 int status; /* Status return from Tcl_AssembleCode */
847 const char* source; /* String representation of the source code */
848 int sourceLen; /* Length of the source code in bytes */
849
850 /*
851 * Get the expression ByteCode from the object. If it exists, make sure it
852 * is valid in the current context.
853 */
854
855 if (objPtr->typePtr == &assembleCodeType) {
856 namespacePtr = iPtr->varFramePtr->nsPtr;
857 codePtr = (ByteCode *)objPtr->internalRep.twoPtrValue.ptr1;
858 if (((Interp *) *codePtr->interpHandle == iPtr)
859 && (codePtr->compileEpoch == iPtr->compileEpoch)
860 && (codePtr->nsPtr == namespacePtr)
861 && (codePtr->nsEpoch == namespacePtr->resolverEpoch)
862 && (codePtr->localCachePtr
863 == iPtr->varFramePtr->localCachePtr)) {
864 return codePtr;
865 }
866
867 /*
868 * Not valid, so free it and regenerate.
869 */
870
871 FreeAssembleCodeInternalRep(objPtr);
872 }
873
874 /*
875 * Set up the compilation environment, and assemble the code.
876 */
877
878 source = TclGetStringFromObj(objPtr, &sourceLen);
879 TclInitCompileEnv(interp, &compEnv, source, sourceLen, NULL, 0);
880 status = TclAssembleCode(&compEnv, source, sourceLen, TCL_EVAL_DIRECT);
881 if (status != TCL_OK) {
882 /*
883 * Assembly failed. Clean up and report the error.
884 */
885 TclFreeCompileEnv(&compEnv);
886 return NULL;
887 }
888
889 /*
890 * Add a "done" instruction as the last instruction and change the object
891 * into a ByteCode object. Ownership of the literal objects and aux data
892 * items is given to the ByteCode object.
893 */
894
895 TclEmitOpcode(INST_DONE, &compEnv);
896 TclInitByteCodeObj(objPtr, &compEnv);
897 objPtr->typePtr = &assembleCodeType;
898 TclFreeCompileEnv(&compEnv);
899
900 /*
901 * Record the local variable context to which the bytecode pertains
902 */
903
904 codePtr = (ByteCode *)objPtr->internalRep.twoPtrValue.ptr1;
905 if (iPtr->varFramePtr->localCachePtr) {
906 codePtr->localCachePtr = iPtr->varFramePtr->localCachePtr;
907 codePtr->localCachePtr->refCount++;
908 }
909
910 /*
911 * Report on what the assembler did.
912 */
913
914 TclDebugPrintByteCodeObj(objPtr);
915
916 return codePtr;
917 }
918
919 /*
920 *-----------------------------------------------------------------------------
921 *
922 * TclCompileAssembleCmd --
923 *
924 * Compilation procedure for the '::tcl::unsupported::assemble' command.
925 *
926 * Results:
927 * Returns a standard Tcl result.
928 *
929 * Side effects:
930 * Puts the result of assembling the code into the bytecode stream in
931 * 'compileEnv'.
932 *
933 * This procedure makes sure that the command has a single arg, which is
934 * constant. If that condition is met, the procedure calls TclAssembleCode to
935 * produce bytecode for the given assembly code, and returns any error
936 * resulting from the assembly.
937 *
938 *-----------------------------------------------------------------------------
939 */
940
941 int
942 TclCompileAssembleCmd(
943 Tcl_Interp *interp, /* Used for error reporting. */
944 Tcl_Parse *parsePtr, /* Points to a parse structure for the command
945 * created by Tcl_ParseCommand. */
946 Command *cmdPtr, /* Points to definition of command being
947 * compiled. */
948 CompileEnv *envPtr) /* Holds resulting instructions. */
949 {
950 Tcl_Token *tokenPtr; /* Token in the input script */
951
952 int numCommands = envPtr->numCommands;
953 int offset = envPtr->codeNext - envPtr->codeStart;
954 int depth = envPtr->currStackDepth;
955 (void)cmdPtr;
956 /*
957 * Make sure that the command has a single arg that is a simple word.
958 */
959
960 if (parsePtr->numWords != 2) {
961 return TCL_ERROR;
962 }
963 tokenPtr = TokenAfter(parsePtr->tokenPtr);
964 if (tokenPtr->type != TCL_TOKEN_SIMPLE_WORD) {
965 return TCL_ERROR;
966 }
967
968 /*
969 * Compile the code and convert any error from the compilation into
970 * bytecode reporting the error;
971 */
972
973 if (TCL_ERROR == TclAssembleCode(envPtr, tokenPtr[1].start,
974 tokenPtr[1].size, TCL_EVAL_DIRECT)) {
975
976 Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf(
977 "\n (\"%.*s\" body, line %d)",
978 parsePtr->tokenPtr->size, parsePtr->tokenPtr->start,
979 Tcl_GetErrorLine(interp)));
980 envPtr->numCommands = numCommands;
981 envPtr->codeNext = envPtr->codeStart + offset;
982 envPtr->currStackDepth = depth;
983 TclCompileSyntaxError(interp, envPtr);
984 }
985 return TCL_OK;
986 }
987
988 /*
989 *-----------------------------------------------------------------------------
990 *
991 * TclAssembleCode --
992 *
993 * Take a list of instructions in a Tcl_Obj, and assemble them to Tcl
994 * bytecodes
995 *
996 * Results:
997 * Returns TCL_OK on success, TCL_ERROR on failure. If 'flags' includes
998 * TCL_EVAL_DIRECT, places an error message in the interpreter result.
999 *
1000 * Side effects:
1001 * Adds byte codes to the compile environment, and updates the
1002 * environment's stack depth.
1003 *
1004 *-----------------------------------------------------------------------------
1005 */
1006
1007 static int
1008 TclAssembleCode(
1009 CompileEnv *envPtr, /* Compilation environment that is to receive
1010 * the generated bytecode */
1011 const char* codePtr, /* Assembly-language code to be processed */
1012 int codeLen, /* Length of the code */
1013 int flags) /* OR'ed combination of flags */
1014 {
1015 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
1016 /* Tcl interpreter */
1017 /*
1018 * Walk through the assembly script using the Tcl parser. Each 'command'
1019 * will be an instruction or assembly directive.
1020 */
1021
1022 const char* instPtr = codePtr;
1023 /* Where to start looking for a line of code */
1024 const char* nextPtr; /* Pointer to the end of the line of code */
1025 int bytesLeft = codeLen; /* Number of bytes of source code remaining to
1026 * be parsed */
1027 int status; /* Tcl status return */
1028 AssemblyEnv* assemEnvPtr = NewAssemblyEnv(envPtr, flags);
1029 Tcl_Parse* parsePtr = assemEnvPtr->parsePtr;
1030
1031 do {
1032 /*
1033 * Parse out one command line from the assembly script.
1034 */
1035
1036 status = Tcl_ParseCommand(interp, instPtr, bytesLeft, 0, parsePtr);
1037
1038 /*
1039 * Report errors in the parse.
1040 */
1041
1042 if (status != TCL_OK) {
1043 if (flags & TCL_EVAL_DIRECT) {
1044 Tcl_LogCommandInfo(interp, codePtr, parsePtr->commandStart,
1045 parsePtr->term + 1 - parsePtr->commandStart);
1046 }
1047 FreeAssemblyEnv(assemEnvPtr);
1048 return TCL_ERROR;
1049 }
1050
1051 /*
1052 * Advance the pointers around any leading commentary.
1053 */
1054
1055 TclAdvanceLines(&assemEnvPtr->cmdLine, instPtr,
1056 parsePtr->commandStart);
1057 TclAdvanceContinuations(&assemEnvPtr->cmdLine, &assemEnvPtr->clNext,
1058 parsePtr->commandStart - envPtr->source);
1059
1060 /*
1061 * Process the line of code.
1062 */
1063
1064 if (parsePtr->numWords > 0) {
1065 int instLen = parsePtr->commandSize;
1066 /* Length in bytes of the current command */
1067
1068 if (parsePtr->term == parsePtr->commandStart + instLen - 1) {
1069 --instLen;
1070 }
1071
1072 /*
1073 * If tracing, show each line assembled as it happens.
1074 */
1075
1076 #ifdef TCL_COMPILE_DEBUG
1077 if ((tclTraceCompile >= 2) && (envPtr->procPtr == NULL)) {
1078 printf(" %4ld Assembling: ",
1079 (long)(envPtr->codeNext - envPtr->codeStart));
1080 TclPrintSource(stdout, parsePtr->commandStart,
1081 TclMin(instLen, 55));
1082 printf("\n");
1083 }
1084 #endif
1085 if (AssembleOneLine(assemEnvPtr) != TCL_OK) {
1086 if (flags & TCL_EVAL_DIRECT) {
1087 Tcl_LogCommandInfo(interp, codePtr,
1088 parsePtr->commandStart, instLen);
1089 }
1090 Tcl_FreeParse(parsePtr);
1091 FreeAssemblyEnv(assemEnvPtr);
1092 return TCL_ERROR;
1093 }
1094 }
1095
1096 /*
1097 * Advance to the next line of code.
1098 */
1099
1100 nextPtr = parsePtr->commandStart + parsePtr->commandSize;
1101 bytesLeft -= (nextPtr - instPtr);
1102 instPtr = nextPtr;
1103 TclAdvanceLines(&assemEnvPtr->cmdLine, parsePtr->commandStart,
1104 instPtr);
1105 TclAdvanceContinuations(&assemEnvPtr->cmdLine, &assemEnvPtr->clNext,
1106 instPtr - envPtr->source);
1107 Tcl_FreeParse(parsePtr);
1108 } while (bytesLeft > 0);
1109
1110 /*
1111 * Done with parsing the code.
1112 */
1113
1114 status = FinishAssembly(assemEnvPtr);
1115 FreeAssemblyEnv(assemEnvPtr);
1116 return status;
1117 }
1118
1119 /*
1120 *-----------------------------------------------------------------------------
1121 *
1122 * NewAssemblyEnv --
1123 *
1124 * Creates an environment for the assembler to run in.
1125 *
1126 * Results:
1127 * Allocates, initialises and returns an assembler environment
1128 *
1129 *-----------------------------------------------------------------------------
1130 */
1131
1132 static AssemblyEnv*
1133 NewAssemblyEnv(
1134 CompileEnv* envPtr, /* Compilation environment being used for code
1135 * generation*/
1136 int flags) /* Compilation flags (TCL_EVAL_DIRECT) */
1137 {
1138 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
1139 /* Tcl interpreter */
1140 AssemblyEnv* assemEnvPtr = (AssemblyEnv*)TclStackAlloc(interp, sizeof(AssemblyEnv));
1141 /* Assembler environment under construction */
1142 Tcl_Parse* parsePtr = (Tcl_Parse*)TclStackAlloc(interp, sizeof(Tcl_Parse));
1143 /* Parse of one line of assembly code */
1144
1145 assemEnvPtr->envPtr = envPtr;
1146 assemEnvPtr->parsePtr = parsePtr;
1147 assemEnvPtr->cmdLine = 1;
1148 assemEnvPtr->clNext = envPtr->clNext;
1149
1150 /*
1151 * Make the hashtables that store symbol resolution.
1152 */
1153
1154 Tcl_InitHashTable(&assemEnvPtr->labelHash, TCL_STRING_KEYS);
1155
1156 /*
1157 * Start the first basic block.
1158 */
1159
1160 assemEnvPtr->curr_bb = NULL;
1161 assemEnvPtr->head_bb = AllocBB(assemEnvPtr);
1162 assemEnvPtr->curr_bb = assemEnvPtr->head_bb;
1163 assemEnvPtr->head_bb->startLine = 1;
1164
1165 /*
1166 * Stash compilation flags.
1167 */
1168
1169 assemEnvPtr->flags = flags;
1170 return assemEnvPtr;
1171 }
1172
1173 /*
1174 *-----------------------------------------------------------------------------
1175 *
1176 * FreeAssemblyEnv --
1177 *
1178 * Cleans up the assembler environment when assembly is complete.
1179 *
1180 *-----------------------------------------------------------------------------
1181 */
1182
1183 static void
1184 FreeAssemblyEnv(
1185 AssemblyEnv* assemEnvPtr) /* Environment to free */
1186 {
1187 CompileEnv* envPtr = assemEnvPtr->envPtr;
1188 /* Compilation environment being used for code
1189 * generation */
1190 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
1191 /* Tcl interpreter */
1192 BasicBlock* thisBB; /* Pointer to a basic block being deleted */
1193 BasicBlock* nextBB; /* Pointer to a deleted basic block's
1194 * successor */
1195
1196 /*
1197 * Free all the basic block structures.
1198 */
1199
1200 for (thisBB = assemEnvPtr->head_bb; thisBB != NULL; thisBB = nextBB) {
1201 if (thisBB->jumpTarget != NULL) {
1202 Tcl_DecrRefCount(thisBB->jumpTarget);
1203 }
1204 if (thisBB->foreignExceptions != NULL) {
1205 ckfree(thisBB->foreignExceptions);
1206 }
1207 nextBB = thisBB->successor1;
1208 if (thisBB->jtPtr != NULL) {
1209 DeleteMirrorJumpTable(thisBB->jtPtr);
1210 thisBB->jtPtr = NULL;
1211 }
1212 ckfree(thisBB);
1213 }
1214
1215 /*
1216 * Dispose what's left.
1217 */
1218
1219 Tcl_DeleteHashTable(&assemEnvPtr->labelHash);
1220 TclStackFree(interp, assemEnvPtr->parsePtr);
1221 TclStackFree(interp, assemEnvPtr);
1222 }
1223
1224 /*
1225 *-----------------------------------------------------------------------------
1226 *
1227 * AssembleOneLine --
1228 *
1229 * Assembles a single command from an assembly language source.
1230 *
1231 * Results:
1232 * Returns TCL_ERROR with an appropriate error message if the assembly
1233 * fails. Returns TCL_OK if the assembly succeeds. Updates the assembly
1234 * environment with the state of the assembly.
1235 *
1236 *-----------------------------------------------------------------------------
1237 */
1238
1239 static int
1240 AssembleOneLine(
1241 AssemblyEnv* assemEnvPtr) /* State of the assembly */
1242 {
1243 CompileEnv* envPtr = assemEnvPtr->envPtr;
1244 /* Compilation environment being used for code
1245 * gen */
1246 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
1247 /* Tcl interpreter */
1248 Tcl_Parse* parsePtr = assemEnvPtr->parsePtr;
1249 /* Parse of the line of code */
1250 Tcl_Token* tokenPtr; /* Current token within the line of code */
1251 Tcl_Obj* instNameObj; /* Name of the instruction */
1252 int tblIdx; /* Index in TalInstructionTable of the
1253 * instruction */
1254 TalInstType instType; /* Type of the instruction */
1255 Tcl_Obj* operand1Obj = NULL;
1256 /* First operand to the instruction */
1257 const char* operand1; /* String rep of the operand */
1258 int operand1Len; /* String length of the operand */
1259 int opnd; /* Integer representation of an operand */
1260 int litIndex; /* Literal pool index of a constant */
1261 int localVar; /* LVT index of a local variable */
1262 int flags; /* Flags for a basic block */
1263 JumptableInfo* jtPtr; /* Pointer to a jumptable */
1264 int infoIndex; /* Index of the jumptable in auxdata */
1265 int status = TCL_ERROR; /* Return value from this function */
1266
1267 /*
1268 * Make sure that the instruction name is known at compile time.
1269 */
1270
1271 tokenPtr = parsePtr->tokenPtr;
1272 if (GetNextOperand(assemEnvPtr, &tokenPtr, &instNameObj) != TCL_OK) {
1273 return TCL_ERROR;
1274 }
1275
1276 /*
1277 * Look up the instruction name.
1278 */
1279
1280 if (Tcl_GetIndexFromObjStruct(interp, instNameObj,
1281 &TalInstructionTable[0].name, sizeof(TalInstDesc), "instruction",
1282 TCL_EXACT, &tblIdx) != TCL_OK) {
1283 goto cleanup;
1284 }
1285
1286 /*
1287 * Vector on the type of instruction being processed.
1288 */
1289
1290 instType = TalInstructionTable[tblIdx].instType;
1291 switch (instType) {
1292
1293 case ASSEM_PUSH:
1294 if (parsePtr->numWords != 2) {
1295 Tcl_WrongNumArgs(interp, 1, &instNameObj, "value");
1296 goto cleanup;
1297 }
1298 if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
1299 goto cleanup;
1300 }
1301 operand1 = TclGetStringFromObj(operand1Obj, &operand1Len);
1302 litIndex = TclRegisterNewLiteral(envPtr, operand1, operand1Len);
1303 BBEmitInst1or4(assemEnvPtr, tblIdx, litIndex, 0);
1304 break;
1305
1306 case ASSEM_1BYTE:
1307 if (parsePtr->numWords != 1) {
1308 Tcl_WrongNumArgs(interp, 1, &instNameObj, "");
1309 goto cleanup;
1310 }
1311 BBEmitOpcode(assemEnvPtr, tblIdx, 0);
1312 break;
1313
1314 case ASSEM_BEGIN_CATCH:
1315 /*
1316 * Emit the BEGIN_CATCH instruction with the code offset of the
1317 * exception branch target instead of the exception range index. The
1318 * correct index will be generated and inserted later, when catches
1319 * are being resolved.
1320 */
1321
1322 if (parsePtr->numWords != 2) {
1323 Tcl_WrongNumArgs(interp, 1, &instNameObj, "label");
1324 goto cleanup;
1325 }
1326 if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
1327 goto cleanup;
1328 }
1329 assemEnvPtr->curr_bb->jumpLine = assemEnvPtr->cmdLine;
1330 assemEnvPtr->curr_bb->jumpOffset = envPtr->codeNext-envPtr->codeStart;
1331 BBEmitInstInt4(assemEnvPtr, tblIdx, 0, 0);
1332 assemEnvPtr->curr_bb->flags |= BB_BEGINCATCH;
1333 StartBasicBlock(assemEnvPtr, BB_FALLTHRU, operand1Obj);
1334 break;
1335
1336 case ASSEM_BOOL:
1337 if (parsePtr->numWords != 2) {
1338 Tcl_WrongNumArgs(interp, 1, &instNameObj, "boolean");
1339 goto cleanup;
1340 }
1341 if (GetBooleanOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
1342 goto cleanup;
1343 }
1344 BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, 0);
1345 break;
1346
1347 case ASSEM_BOOL_LVT4:
1348 if (parsePtr->numWords != 3) {
1349 Tcl_WrongNumArgs(interp, 1, &instNameObj, "boolean varName");
1350 goto cleanup;
1351 }
1352 if (GetBooleanOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
1353 goto cleanup;
1354 }
1355 localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
1356 if (localVar < 0) {
1357 goto cleanup;
1358 }
1359 BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, 0);
1360 TclEmitInt4(localVar, envPtr);
1361 break;
1362
1363 case ASSEM_CLOCK_READ:
1364 if (parsePtr->numWords != 2) {
1365 Tcl_WrongNumArgs(interp, 1, &instNameObj, "imm8");
1366 goto cleanup;
1367 }
1368 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
1369 goto cleanup;
1370 }
1371 if (opnd < 0 || opnd > 3) {
1372 Tcl_SetObjResult(interp,
1373 Tcl_NewStringObj("operand must be [0..3]", -1));
1374 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "OPERAND<0,>3", (char *)NULL);
1375 goto cleanup;
1376 }
1377 BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, opnd);
1378 break;
1379
1380 case ASSEM_CONCAT1:
1381 if (parsePtr->numWords != 2) {
1382 Tcl_WrongNumArgs(interp, 1, &instNameObj, "imm8");
1383 goto cleanup;
1384 }
1385 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1386 || CheckOneByte(interp, opnd) != TCL_OK
1387 || CheckStrictlyPositive(interp, opnd) != TCL_OK) {
1388 goto cleanup;
1389 }
1390 BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, opnd);
1391 break;
1392
1393 case ASSEM_DICT_GET:
1394 if (parsePtr->numWords != 2) {
1395 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
1396 goto cleanup;
1397 }
1398 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1399 || CheckStrictlyPositive(interp, opnd) != TCL_OK) {
1400 goto cleanup;
1401 }
1402 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd+1);
1403 break;
1404
1405 case ASSEM_DICT_SET:
1406 if (parsePtr->numWords != 3) {
1407 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count varName");
1408 goto cleanup;
1409 }
1410 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1411 || CheckStrictlyPositive(interp, opnd) != TCL_OK) {
1412 goto cleanup;
1413 }
1414 localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
1415 if (localVar < 0) {
1416 goto cleanup;
1417 }
1418 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd+1);
1419 TclEmitInt4(localVar, envPtr);
1420 break;
1421
1422 case ASSEM_DICT_UNSET:
1423 if (parsePtr->numWords != 3) {
1424 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count varName");
1425 goto cleanup;
1426 }
1427 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1428 || CheckStrictlyPositive(interp, opnd) != TCL_OK) {
1429 goto cleanup;
1430 }
1431 localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
1432 if (localVar < 0) {
1433 goto cleanup;
1434 }
1435 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
1436 TclEmitInt4(localVar, envPtr);
1437 break;
1438
1439 case ASSEM_END_CATCH:
1440 if (parsePtr->numWords != 1) {
1441 Tcl_WrongNumArgs(interp, 1, &instNameObj, "");
1442 goto cleanup;
1443 }
1444 assemEnvPtr->curr_bb->flags |= BB_ENDCATCH;
1445 BBEmitOpcode(assemEnvPtr, tblIdx, 0);
1446 StartBasicBlock(assemEnvPtr, BB_FALLTHRU, NULL);
1447 break;
1448
1449 case ASSEM_EVAL:
1450 /* TODO - Refactor this stuff into a subroutine that takes the inst
1451 * code, the message ("script" or "expression") and an evaluator
1452 * callback that calls TclCompileScript or TclCompileExpr. */
1453
1454 if (parsePtr->numWords != 2) {
1455 Tcl_WrongNumArgs(interp, 1, &instNameObj,
1456 ((TalInstructionTable[tblIdx].tclInstCode
1457 == INST_EVAL_STK) ? "script" : "expression"));
1458 goto cleanup;
1459 }
1460 if (tokenPtr->type == TCL_TOKEN_SIMPLE_WORD) {
1461 CompileEmbeddedScript(assemEnvPtr, tokenPtr+1,
1462 TalInstructionTable+tblIdx);
1463 } else if (GetNextOperand(assemEnvPtr, &tokenPtr,
1464 &operand1Obj) != TCL_OK) {
1465 goto cleanup;
1466 } else {
1467 operand1 = TclGetStringFromObj(operand1Obj, &operand1Len);
1468 litIndex = TclRegisterNewLiteral(envPtr, operand1, operand1Len);
1469
1470 /*
1471 * Assumes that PUSH is the first slot!
1472 */
1473
1474 BBEmitInst1or4(assemEnvPtr, 0, litIndex, 0);
1475 BBEmitOpcode(assemEnvPtr, tblIdx, 0);
1476 }
1477 break;
1478
1479 case ASSEM_INVOKE:
1480 if (parsePtr->numWords != 2) {
1481 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
1482 goto cleanup;
1483 }
1484 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1485 || CheckStrictlyPositive(interp, opnd) != TCL_OK) {
1486 goto cleanup;
1487 }
1488
1489 BBEmitInst1or4(assemEnvPtr, tblIdx, opnd, opnd);
1490 break;
1491
1492 case ASSEM_JUMP:
1493 case ASSEM_JUMP4:
1494 if (parsePtr->numWords != 2) {
1495 Tcl_WrongNumArgs(interp, 1, &instNameObj, "label");
1496 goto cleanup;
1497 }
1498 if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
1499 goto cleanup;
1500 }
1501 assemEnvPtr->curr_bb->jumpOffset = envPtr->codeNext-envPtr->codeStart;
1502 if (instType == ASSEM_JUMP) {
1503 flags = BB_JUMP1;
1504 BBEmitInstInt1(assemEnvPtr, tblIdx, 0, 0);
1505 } else {
1506 flags = 0;
1507 BBEmitInstInt4(assemEnvPtr, tblIdx, 0, 0);
1508 }
1509
1510 /*
1511 * Start a new basic block at the instruction following the jump.
1512 */
1513
1514 assemEnvPtr->curr_bb->jumpLine = assemEnvPtr->cmdLine;
1515 if (TalInstructionTable[tblIdx].operandsConsumed != 0) {
1516 flags |= BB_FALLTHRU;
1517 }
1518 StartBasicBlock(assemEnvPtr, flags, operand1Obj);
1519 break;
1520
1521 case ASSEM_JUMPTABLE:
1522 if (parsePtr->numWords != 2) {
1523 Tcl_WrongNumArgs(interp, 1, &instNameObj, "table");
1524 goto cleanup;
1525 }
1526 if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
1527 goto cleanup;
1528 }
1529
1530 jtPtr = (JumptableInfo*)ckalloc(sizeof(JumptableInfo));
1531
1532 Tcl_InitHashTable(&jtPtr->hashTable, TCL_STRING_KEYS);
1533 assemEnvPtr->curr_bb->jumpLine = assemEnvPtr->cmdLine;
1534 assemEnvPtr->curr_bb->jumpOffset = envPtr->codeNext-envPtr->codeStart;
1535 DEBUG_PRINT("bb %p jumpLine %d jumpOffset %d\n",
1536 assemEnvPtr->curr_bb, assemEnvPtr->cmdLine,
1537 envPtr->codeNext - envPtr->codeStart);
1538
1539 infoIndex = TclCreateAuxData(jtPtr, &tclJumptableInfoType, envPtr);
1540 DEBUG_PRINT("auxdata index=%d\n", infoIndex);
1541
1542 BBEmitInstInt4(assemEnvPtr, tblIdx, infoIndex, 0);
1543 if (CreateMirrorJumpTable(assemEnvPtr, operand1Obj) != TCL_OK) {
1544 goto cleanup;
1545 }
1546 StartBasicBlock(assemEnvPtr, BB_JUMPTABLE|BB_FALLTHRU, NULL);
1547 break;
1548
1549 case ASSEM_LABEL:
1550 if (parsePtr->numWords != 2) {
1551 Tcl_WrongNumArgs(interp, 1, &instNameObj, "name");
1552 goto cleanup;
1553 }
1554 if (GetNextOperand(assemEnvPtr, &tokenPtr, &operand1Obj) != TCL_OK) {
1555 goto cleanup;
1556 }
1557
1558 /*
1559 * Add the (label_name, address) pair to the hash table.
1560 */
1561
1562 if (DefineLabel(assemEnvPtr, TclGetString(operand1Obj)) != TCL_OK) {
1563 goto cleanup;
1564 }
1565 break;
1566
1567 case ASSEM_LINDEX_MULTI:
1568 if (parsePtr->numWords != 2) {
1569 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
1570 goto cleanup;
1571 }
1572 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1573 || CheckStrictlyPositive(interp, opnd) != TCL_OK) {
1574 goto cleanup;
1575 }
1576 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
1577 break;
1578
1579 case ASSEM_LIST:
1580 if (parsePtr->numWords != 2) {
1581 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
1582 goto cleanup;
1583 }
1584 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1585 || CheckNonNegative(interp, opnd) != TCL_OK) {
1586 goto cleanup;
1587 }
1588 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
1589 break;
1590
1591 case ASSEM_INDEX:
1592 if (parsePtr->numWords != 2) {
1593 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
1594 goto cleanup;
1595 }
1596 if (GetListIndexOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
1597 goto cleanup;
1598 }
1599 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
1600 break;
1601
1602 case ASSEM_LSET_FLAT:
1603 if (parsePtr->numWords != 2) {
1604 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
1605 goto cleanup;
1606 }
1607 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
1608 goto cleanup;
1609 }
1610 if (opnd < 2) {
1611 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
1612 Tcl_SetObjResult(interp,
1613 Tcl_NewStringObj("operand must be >=2", -1));
1614 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "OPERAND>=2", (char *)NULL);
1615 }
1616 goto cleanup;
1617 }
1618 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
1619 break;
1620
1621 case ASSEM_LVT:
1622 if (parsePtr->numWords != 2) {
1623 Tcl_WrongNumArgs(interp, 1, &instNameObj, "varname");
1624 goto cleanup;
1625 }
1626 localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
1627 if (localVar < 0) {
1628 goto cleanup;
1629 }
1630 BBEmitInst1or4(assemEnvPtr, tblIdx, localVar, 0);
1631 break;
1632
1633 case ASSEM_LVT1:
1634 if (parsePtr->numWords != 2) {
1635 Tcl_WrongNumArgs(interp, 1, &instNameObj, "varname");
1636 goto cleanup;
1637 }
1638 localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
1639 if (localVar < 0 || CheckOneByte(interp, localVar)) {
1640 goto cleanup;
1641 }
1642 BBEmitInstInt1(assemEnvPtr, tblIdx, localVar, 0);
1643 break;
1644
1645 case ASSEM_LVT1_SINT1:
1646 if (parsePtr->numWords != 3) {
1647 Tcl_WrongNumArgs(interp, 1, &instNameObj, "varName imm8");
1648 goto cleanup;
1649 }
1650 localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
1651 if (localVar < 0 || CheckOneByte(interp, localVar)
1652 || GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1653 || CheckSignedOneByte(interp, opnd)) {
1654 goto cleanup;
1655 }
1656 BBEmitInstInt1(assemEnvPtr, tblIdx, localVar, 0);
1657 TclEmitInt1(opnd, envPtr);
1658 break;
1659
1660 case ASSEM_LVT4:
1661 if (parsePtr->numWords != 2) {
1662 Tcl_WrongNumArgs(interp, 1, &instNameObj, "varname");
1663 goto cleanup;
1664 }
1665 localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
1666 if (localVar < 0) {
1667 goto cleanup;
1668 }
1669 BBEmitInstInt4(assemEnvPtr, tblIdx, localVar, 0);
1670 break;
1671
1672 case ASSEM_OVER:
1673 if (parsePtr->numWords != 2) {
1674 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
1675 goto cleanup;
1676 }
1677 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1678 || CheckNonNegative(interp, opnd) != TCL_OK) {
1679 goto cleanup;
1680 }
1681 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd+1);
1682 break;
1683
1684 case ASSEM_REGEXP:
1685 if (parsePtr->numWords != 2) {
1686 Tcl_WrongNumArgs(interp, 1, &instNameObj, "boolean");
1687 goto cleanup;
1688 }
1689 if (GetBooleanOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
1690 goto cleanup;
1691 }
1692 {
1693 BBEmitInstInt1(assemEnvPtr, tblIdx, TCL_REG_ADVANCED | (opnd ? TCL_REG_NOCASE : 0), 0);
1694 }
1695 break;
1696
1697 case ASSEM_REVERSE:
1698 if (parsePtr->numWords != 2) {
1699 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count");
1700 goto cleanup;
1701 }
1702 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1703 || CheckNonNegative(interp, opnd) != TCL_OK) {
1704 goto cleanup;
1705 }
1706 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, opnd);
1707 break;
1708
1709 case ASSEM_SINT1:
1710 if (parsePtr->numWords != 2) {
1711 Tcl_WrongNumArgs(interp, 1, &instNameObj, "imm8");
1712 goto cleanup;
1713 }
1714 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK
1715 || CheckSignedOneByte(interp, opnd) != TCL_OK) {
1716 goto cleanup;
1717 }
1718 BBEmitInstInt1(assemEnvPtr, tblIdx, opnd, 0);
1719 break;
1720
1721 case ASSEM_SINT4_LVT4:
1722 if (parsePtr->numWords != 3) {
1723 Tcl_WrongNumArgs(interp, 1, &instNameObj, "count varName");
1724 goto cleanup;
1725 }
1726 if (GetIntegerOperand(assemEnvPtr, &tokenPtr, &opnd) != TCL_OK) {
1727 goto cleanup;
1728 }
1729 localVar = FindLocalVar(assemEnvPtr, &tokenPtr);
1730 if (localVar < 0) {
1731 goto cleanup;
1732 }
1733 BBEmitInstInt4(assemEnvPtr, tblIdx, opnd, 0);
1734 TclEmitInt4(localVar, envPtr);
1735 break;
1736
1737 default:
1738 Tcl_Panic("Instruction \"%s\" could not be found, can't happen\n",
1739 TclGetString(instNameObj));
1740 }
1741
1742 status = TCL_OK;
1743 cleanup:
1744 Tcl_DecrRefCount(instNameObj);
1745 if (operand1Obj) {
1746 Tcl_DecrRefCount(operand1Obj);
1747 }
1748 return status;
1749 }
1750
1751 /*
1752 *-----------------------------------------------------------------------------
1753 *
1754 * CompileEmbeddedScript --
1755 *
1756 * Compile an embedded 'eval' or 'expr' that appears in assembly code.
1757 *
1758 * This procedure is called when the 'eval' or 'expr' assembly directive is
1759 * encountered, and the argument to the directive is a simple word that
1760 * requires no substitution. The appropriate compiler (TclCompileScript or
1761 * TclCompileExpr) is invoked recursively, and emits bytecode.
1762 *
1763 * Before the compiler is invoked, the compilation environment's stack
1764 * consumption is reset to zero. Upon return from the compilation, the net
1765 * stack effect of the compilation is in the compiler env, and this stack
1766 * effect is posted to the assembler environment. The compile environment's
1767 * stack consumption is then restored to what it was before (which is actually
1768 * the state of the stack on entry to the block of assembly code).
1769 *
1770 * Any exception ranges pushed by the compilation are copied to the basic
1771 * block and removed from the compiler environment. They will be rebuilt at
1772 * the end of assembly, when the exception stack depth is actually known.
1773 *
1774 *-----------------------------------------------------------------------------
1775 */
1776
1777 static void
1778 CompileEmbeddedScript(
1779 AssemblyEnv* assemEnvPtr, /* Assembly environment */
1780 Tcl_Token* tokenPtr, /* Tcl_Token containing the script */
1781 const TalInstDesc* instPtr) /* Instruction that determines whether
1782 * the script is 'expr' or 'eval' */
1783 {
1784 CompileEnv* envPtr = assemEnvPtr->envPtr;
1785 /* Compilation environment */
1786 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
1787 /* Tcl interpreter */
1788
1789 /*
1790 * The expression or script is not only known at compile time, but
1791 * actually a "simple word". It can be compiled inline by invoking the
1792 * compiler recursively.
1793 *
1794 * Save away the stack depth and reset it before compiling the script.
1795 * We'll record the stack usage of the script in the BasicBlock, and
1796 * accumulate it together with the stack usage of the enclosing assembly
1797 * code.
1798 */
1799
1800 int savedStackDepth = envPtr->currStackDepth;
1801 int savedMaxStackDepth = envPtr->maxStackDepth;
1802 int savedExceptArrayNext = envPtr->exceptArrayNext;
1803
1804 envPtr->currStackDepth = 0;
1805 envPtr->maxStackDepth = 0;
1806
1807 StartBasicBlock(assemEnvPtr, BB_FALLTHRU, NULL);
1808 switch(instPtr->tclInstCode) {
1809 case INST_EVAL_STK:
1810 TclCompileScript(interp, tokenPtr->start, tokenPtr->size, envPtr);
1811 break;
1812 case INST_EXPR_STK:
1813 TclCompileExpr(interp, tokenPtr->start, tokenPtr->size, envPtr, 1);
1814 break;
1815 default:
1816 Tcl_Panic("no ASSEM_EVAL case for %s (%d), can't happen",
1817 instPtr->name, instPtr->tclInstCode);
1818 }
1819
1820 /*
1821 * Roll up the stack usage of the embedded block into the assembler
1822 * environment.
1823 */
1824
1825 SyncStackDepth(assemEnvPtr);
1826 envPtr->currStackDepth = savedStackDepth;
1827 envPtr->maxStackDepth = savedMaxStackDepth;
1828
1829 /*
1830 * Save any exception ranges that were pushed by the compiler; they will
1831 * need to be fixed up once the stack depth is known.
1832 */
1833
1834 MoveExceptionRangesToBasicBlock(assemEnvPtr, savedExceptArrayNext);
1835
1836 /*
1837 * Flush the current basic block.
1838 */
1839
1840 StartBasicBlock(assemEnvPtr, BB_FALLTHRU, NULL);
1841 }
1842
1843 /*
1844 *-----------------------------------------------------------------------------
1845 *
1846 * SyncStackDepth --
1847 *
1848 * Copies the stack depth from the compile environment to a basic block.
1849 *
1850 * Side effects:
1851 * Current and max stack depth in the current basic block are adjusted.
1852 *
1853 * This procedure is called on return from invoking the compiler for the
1854 * 'eval' and 'expr' operations. It adjusts the stack depth of the current
1855 * basic block to reflect the stack required by the just-compiled code.
1856 *
1857 *-----------------------------------------------------------------------------
1858 */
1859
1860 static void
1861 SyncStackDepth(
1862 AssemblyEnv* assemEnvPtr) /* Assembly environment */
1863 {
1864 CompileEnv* envPtr = assemEnvPtr->envPtr;
1865 /* Compilation environment */
1866 BasicBlock* curr_bb = assemEnvPtr->curr_bb;
1867 /* Current basic block */
1868 int maxStackDepth = curr_bb->finalStackDepth + envPtr->maxStackDepth;
1869 /* Max stack depth in the basic block */
1870
1871 if (maxStackDepth > curr_bb->maxStackDepth) {
1872 curr_bb->maxStackDepth = maxStackDepth;
1873 }
1874 curr_bb->finalStackDepth += envPtr->currStackDepth;
1875 }
1876
1877 /*
1878 *-----------------------------------------------------------------------------
1879 *
1880 * MoveExceptionRangesToBasicBlock --
1881 *
1882 * Removes exception ranges that were created by compiling an embedded
1883 * script from the CompileEnv, and stores them in the BasicBlock. They
1884 * will be reinstalled, at the correct stack depth, after control flow
1885 * analysis is complete on the assembly code.
1886 *
1887 *-----------------------------------------------------------------------------
1888 */
1889
1890 static void
1891 MoveExceptionRangesToBasicBlock(
1892 AssemblyEnv* assemEnvPtr, /* Assembly environment */
1893 int savedExceptArrayNext) /* Saved index of the end of the exception
1894 * range array */
1895 {
1896 CompileEnv* envPtr = assemEnvPtr->envPtr;
1897 /* Compilation environment */
1898 BasicBlock* curr_bb = assemEnvPtr->curr_bb;
1899 /* Current basic block */
1900 int exceptionCount = envPtr->exceptArrayNext - savedExceptArrayNext;
1901 /* Number of ranges that must be moved */
1902 int i;
1903
1904 if (exceptionCount == 0) {
1905 /* Nothing to do */
1906 return;
1907 }
1908
1909 /*
1910 * Save the exception ranges in the basic block. They will be re-added at
1911 * the conclusion of assembly; at this time, the INST_BEGIN_CATCH
1912 * instructions in the block will be adjusted from whatever range indices
1913 * they have [savedExceptArrayNext .. envPtr->exceptArrayNext) to the
1914 * indices that the exceptions acquire. The saved exception ranges are
1915 * converted to a relative nesting depth. The depth will be recomputed
1916 * once flow analysis has determined the actual stack depth of the block.
1917 */
1918
1919 DEBUG_PRINT("basic block %p has %d exceptions starting at %d\n",
1920 curr_bb, exceptionCount, savedExceptArrayNext);
1921 curr_bb->foreignExceptionBase = savedExceptArrayNext;
1922 curr_bb->foreignExceptionCount = exceptionCount;
1923 curr_bb->foreignExceptions =
1924 (ExceptionRange*)ckalloc(exceptionCount * sizeof(ExceptionRange));
1925 memcpy(curr_bb->foreignExceptions,
1926 envPtr->exceptArrayPtr + savedExceptArrayNext,
1927 exceptionCount * sizeof(ExceptionRange));
1928 for (i = 0; i < exceptionCount; ++i) {
1929 curr_bb->foreignExceptions[i].nestingLevel -= envPtr->exceptDepth;
1930 }
1931 envPtr->exceptArrayNext = savedExceptArrayNext;
1932 }
1933
1934 /*
1935 *-----------------------------------------------------------------------------
1936 *
1937 * CreateMirrorJumpTable --
1938 *
1939 * Makes a jump table with comparison values and assembly code labels.
1940 *
1941 * Results:
1942 * Returns a standard Tcl status, with an error message in the
1943 * interpreter on error.
1944 *
1945 * Side effects:
1946 * Initializes the jump table pointer in the current basic block to a
1947 * JumptableInfo. The keys in the JumptableInfo are the comparison
1948 * strings. The values, instead of being jump displacements, are
1949 * Tcl_Obj's with the code labels.
1950 */
1951
1952 static int
1953 CreateMirrorJumpTable(
1954 AssemblyEnv* assemEnvPtr, /* Assembly environment */
1955 Tcl_Obj* jumps) /* List of alternating keywords and labels */
1956 {
1957 int objc; /* Number of elements in the 'jumps' list */
1958 Tcl_Obj** objv; /* Pointers to the elements in the list */
1959 CompileEnv* envPtr = assemEnvPtr->envPtr;
1960 /* Compilation environment */
1961 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
1962 /* Tcl interpreter */
1963 BasicBlock* bbPtr = assemEnvPtr->curr_bb;
1964 /* Current basic block */
1965 JumptableInfo* jtPtr;
1966 Tcl_HashTable* jtHashPtr; /* Hashtable in the JumptableInfo */
1967 Tcl_HashEntry* hashEntry; /* Entry for a key in the hashtable */
1968 int isNew; /* Flag==1 if the key is not yet in the
1969 * table. */
1970 int i;
1971
1972 if (TclListObjGetElements(interp, jumps, &objc, &objv) != TCL_OK) {
1973 return TCL_ERROR;
1974 }
1975 if (objc % 2 != 0) {
1976 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
1977 Tcl_SetObjResult(interp, Tcl_NewStringObj(
1978 "jump table must have an even number of list elements",
1979 -1));
1980 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADJUMPTABLE", (char *)NULL);
1981 }
1982 return TCL_ERROR;
1983 }
1984
1985 /*
1986 * Allocate the jumptable.
1987 */
1988
1989 jtPtr = (JumptableInfo*)ckalloc(sizeof(JumptableInfo));
1990 jtHashPtr = &jtPtr->hashTable;
1991 Tcl_InitHashTable(jtHashPtr, TCL_STRING_KEYS);
1992
1993 /*
1994 * Fill the keys and labels into the table.
1995 */
1996
1997 DEBUG_PRINT("jump table {\n");
1998 for (i = 0; i < objc; i+=2) {
1999 DEBUG_PRINT(" %s -> %s\n", TclGetString(objv[i]),
2000 TclGetString(objv[i+1]));
2001 hashEntry = Tcl_CreateHashEntry(jtHashPtr, TclGetString(objv[i]),
2002 &isNew);
2003 if (!isNew) {
2004 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
2005 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2006 "duplicate entry in jump table for \"%s\"",
2007 TclGetString(objv[i])));
2008 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "DUPJUMPTABLEENTRY", (char *)NULL);
2009 DeleteMirrorJumpTable(jtPtr);
2010 return TCL_ERROR;
2011 }
2012 }
2013 Tcl_SetHashValue(hashEntry, objv[i+1]);
2014 Tcl_IncrRefCount(objv[i+1]);
2015 }
2016 DEBUG_PRINT("}\n");
2017
2018 /*
2019 * Put the mirror jumptable in the basic block struct.
2020 */
2021
2022 bbPtr->jtPtr = jtPtr;
2023 return TCL_OK;
2024 }
2025
2026 /*
2027 *-----------------------------------------------------------------------------
2028 *
2029 * DeleteMirrorJumpTable --
2030 *
2031 * Cleans up a jump table when the basic block is deleted.
2032 *
2033 *-----------------------------------------------------------------------------
2034 */
2035
2036 static void
2037 DeleteMirrorJumpTable(
2038 JumptableInfo* jtPtr)
2039 {
2040 Tcl_HashTable* jtHashPtr = &jtPtr->hashTable;
2041 /* Hash table pointer */
2042 Tcl_HashSearch search; /* Hash search control */
2043 Tcl_HashEntry* entry; /* Hash table entry containing a jump label */
2044 Tcl_Obj* label; /* Jump label from the hash table */
2045
2046 for (entry = Tcl_FirstHashEntry(jtHashPtr, &search);
2047 entry != NULL;
2048 entry = Tcl_NextHashEntry(&search)) {
2049 label = (Tcl_Obj*)Tcl_GetHashValue(entry);
2050 Tcl_DecrRefCount(label);
2051 Tcl_SetHashValue(entry, NULL);
2052 }
2053 Tcl_DeleteHashTable(jtHashPtr);
2054 ckfree(jtPtr);
2055 }
2056
2057 /*
2058 *-----------------------------------------------------------------------------
2059 *
2060 * GetNextOperand --
2061 *
2062 * Retrieves the next operand in sequence from an assembly instruction,
2063 * and makes sure that its value is known at compile time.
2064 *
2065 * Results:
2066 * If successful, returns TCL_OK and leaves a Tcl_Obj with the operand
2067 * text in *operandObjPtr. In case of failure, returns TCL_ERROR and
2068 * leaves *operandObjPtr untouched.
2069 *
2070 * Side effects:
2071 * Advances *tokenPtrPtr around the token just processed.
2072 *
2073 *-----------------------------------------------------------------------------
2074 */
2075
2076 static int
2077 GetNextOperand(
2078 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2079 Tcl_Token** tokenPtrPtr, /* INPUT/OUTPUT: Pointer to the token holding
2080 * the operand */
2081 Tcl_Obj** operandObjPtr) /* OUTPUT: Tcl object holding the operand text
2082 * with \-substitutions done. */
2083 {
2084 Tcl_Interp* interp = (Tcl_Interp*) assemEnvPtr->envPtr->iPtr;
2085 Tcl_Obj* operandObj;
2086
2087 TclNewObj(operandObj);
2088 if (!TclWordKnownAtCompileTime(*tokenPtrPtr, operandObj)) {
2089 Tcl_DecrRefCount(operandObj);
2090 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
2091 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2092 "assembly code may not contain substitutions", -1));
2093 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "NOSUBST", (char *)NULL);
2094 }
2095 return TCL_ERROR;
2096 }
2097 *tokenPtrPtr = TokenAfter(*tokenPtrPtr);
2098 Tcl_IncrRefCount(operandObj);
2099 *operandObjPtr = operandObj;
2100 return TCL_OK;
2101 }
2102
2103 /*
2104 *-----------------------------------------------------------------------------
2105 *
2106 * GetBooleanOperand --
2107 *
2108 * Retrieves a Boolean operand from the input stream and advances
2109 * the token pointer.
2110 *
2111 * Results:
2112 * Returns a standard Tcl result (with an error message in the
2113 * interpreter on failure).
2114 *
2115 * Side effects:
2116 * Stores the Boolean value in (*result) and advances (*tokenPtrPtr)
2117 * to the next token.
2118 *
2119 *-----------------------------------------------------------------------------
2120 */
2121
2122 static int
2123 GetBooleanOperand(
2124 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2125 Tcl_Token** tokenPtrPtr, /* Current token from the parser */
2126 int* result) /* OUTPUT: Integer extracted from the token */
2127 {
2128 CompileEnv* envPtr = assemEnvPtr->envPtr;
2129 /* Compilation environment */
2130 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
2131 /* Tcl interpreter */
2132 Tcl_Token* tokenPtr = *tokenPtrPtr;
2133 /* INOUT: Pointer to the next token in the
2134 * source code */
2135 Tcl_Obj* intObj; /* Integer from the source code */
2136 int status; /* Tcl status return */
2137
2138 /*
2139 * Extract the next token as a string.
2140 */
2141
2142 if (GetNextOperand(assemEnvPtr, tokenPtrPtr, &intObj) != TCL_OK) {
2143 return TCL_ERROR;
2144 }
2145
2146 /*
2147 * Convert to an integer, advance to the next token and return.
2148 */
2149
2150 status = Tcl_GetBooleanFromObj(interp, intObj, result);
2151 Tcl_DecrRefCount(intObj);
2152 *tokenPtrPtr = TokenAfter(tokenPtr);
2153 return status;
2154 }
2155
2156 /*
2157 *-----------------------------------------------------------------------------
2158 *
2159 * GetIntegerOperand --
2160 *
2161 * Retrieves an integer operand from the input stream and advances the
2162 * token pointer.
2163 *
2164 * Results:
2165 * Returns a standard Tcl result (with an error message in the
2166 * interpreter on failure).
2167 *
2168 * Side effects:
2169 * Stores the integer value in (*result) and advances (*tokenPtrPtr) to
2170 * the next token.
2171 *
2172 *-----------------------------------------------------------------------------
2173 */
2174
2175 static int
2176 GetIntegerOperand(
2177 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2178 Tcl_Token** tokenPtrPtr, /* Current token from the parser */
2179 int* result) /* OUTPUT: Integer extracted from the token */
2180 {
2181 CompileEnv* envPtr = assemEnvPtr->envPtr;
2182 /* Compilation environment */
2183 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
2184 /* Tcl interpreter */
2185 Tcl_Token* tokenPtr = *tokenPtrPtr;
2186 /* INOUT: Pointer to the next token in the
2187 * source code */
2188 Tcl_Obj* intObj; /* Integer from the source code */
2189 int status; /* Tcl status return */
2190
2191 /*
2192 * Extract the next token as a string.
2193 */
2194
2195 if (GetNextOperand(assemEnvPtr, tokenPtrPtr, &intObj) != TCL_OK) {
2196 return TCL_ERROR;
2197 }
2198
2199 /*
2200 * Convert to an integer, advance to the next token and return.
2201 */
2202
2203 status = Tcl_GetIntFromObj(interp, intObj, result);
2204 Tcl_DecrRefCount(intObj);
2205 *tokenPtrPtr = TokenAfter(tokenPtr);
2206 return status;
2207 }
2208
2209 /*
2210 *-----------------------------------------------------------------------------
2211 *
2212 * GetListIndexOperand --
2213 *
2214 * Gets the value of an operand intended to serve as a list index.
2215 *
2216 * Results:
2217 * Returns a standard Tcl result: TCL_OK if the parse is successful and
2218 * TCL_ERROR (with an appropriate error message) if the parse fails.
2219 *
2220 * Side effects:
2221 * Stores the list index at '*index'. Values between -1 and 0x7FFFFFFF
2222 * have their natural meaning; values between -2 and -0x80000000
2223 * represent 'end-2-N'.
2224 *
2225 *-----------------------------------------------------------------------------
2226 */
2227
2228 static int
2229 GetListIndexOperand(
2230 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2231 Tcl_Token** tokenPtrPtr, /* Current token from the parser */
2232 int* result) /* OUTPUT: Integer extracted from the token */
2233 {
2234 CompileEnv* envPtr = assemEnvPtr->envPtr;
2235 /* Compilation environment */
2236 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
2237 /* Tcl interpreter */
2238 Tcl_Token* tokenPtr = *tokenPtrPtr;
2239 /* INOUT: Pointer to the next token in the
2240 * source code */
2241 Tcl_Obj *value;
2242 int status;
2243
2244 /* General operand validity check */
2245 if (GetNextOperand(assemEnvPtr, tokenPtrPtr, &value) != TCL_OK) {
2246 return TCL_ERROR;
2247 }
2248
2249 /* Convert to an integer, advance to the next token and return. */
2250 /*
2251 * NOTE: Indexing a list with an index before it yields the
2252 * same result as indexing after it, and might be more easily portable
2253 * when list size limits grow.
2254 */
2255 status = TclIndexEncode(interp, value,
2256 TCL_INDEX_BEFORE,TCL_INDEX_BEFORE, result);
2257
2258 Tcl_DecrRefCount(value);
2259 *tokenPtrPtr = TokenAfter(tokenPtr);
2260 return status;
2261 }
2262
2263 /*
2264 *-----------------------------------------------------------------------------
2265 *
2266 * FindLocalVar --
2267 *
2268 * Gets the name of a local variable from the input stream and advances
2269 * the token pointer.
2270 *
2271 * Results:
2272 * Returns the LVT index of the local variable. Returns -1 if the
2273 * variable is non-local, not known at compile time, or cannot be
2274 * installed in the LVT (leaving an error message in the interpreter
2275 * result if necessary).
2276 *
2277 * Side effects:
2278 * Advances the token pointer. May define a new LVT slot if the variable
2279 * has not yet been seen and the execution context allows for it.
2280 *
2281 *-----------------------------------------------------------------------------
2282 */
2283
2284 static int
2285 FindLocalVar(
2286 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2287 Tcl_Token** tokenPtrPtr)
2288 {
2289 CompileEnv* envPtr = assemEnvPtr->envPtr;
2290 /* Compilation environment */
2291 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
2292 /* Tcl interpreter */
2293 Tcl_Token* tokenPtr = *tokenPtrPtr;
2294 /* INOUT: Pointer to the next token in the
2295 * source code. */
2296 Tcl_Obj* varNameObj; /* Name of the variable */
2297 const char* varNameStr;
2298 int varNameLen;
2299 int localVar; /* Index of the variable in the LVT */
2300
2301 if (GetNextOperand(assemEnvPtr, tokenPtrPtr, &varNameObj) != TCL_OK) {
2302 return -1;
2303 }
2304 varNameStr = TclGetStringFromObj(varNameObj, &varNameLen);
2305 if (CheckNamespaceQualifiers(interp, varNameStr, varNameLen)) {
2306 Tcl_DecrRefCount(varNameObj);
2307 return -1;
2308 }
2309 localVar = TclFindCompiledLocal(varNameStr, varNameLen, 1, envPtr);
2310 Tcl_DecrRefCount(varNameObj);
2311 if (localVar == -1) {
2312 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
2313 Tcl_SetObjResult(interp, Tcl_NewStringObj(
2314 "cannot use this instruction to create a variable"
2315 " in a non-proc context", -1));
2316 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "LVT", (char *)NULL);
2317 }
2318 return -1;
2319 }
2320 *tokenPtrPtr = TokenAfter(tokenPtr);
2321 return localVar;
2322 }
2323
2324 /*
2325 *-----------------------------------------------------------------------------
2326 *
2327 * CheckNamespaceQualifiers --
2328 *
2329 * Verify that a variable name has no namespace qualifiers before
2330 * attempting to install it in the LVT.
2331 *
2332 * Results:
2333 * On success, returns TCL_OK. On failure, returns TCL_ERROR and stores
2334 * an error message in the interpreter result.
2335 *
2336 *-----------------------------------------------------------------------------
2337 */
2338
2339 static int
2340 CheckNamespaceQualifiers(
2341 Tcl_Interp* interp, /* Tcl interpreter for error reporting */
2342 const char* name, /* Variable name to check */
2343 int nameLen) /* Length of the variable */
2344 {
2345 const char* p;
2346
2347 for (p = name; p+2 < name+nameLen; p++) {
2348 if ((*p == ':') && (p[1] == ':')) {
2349 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2350 "variable \"%s\" is not local", name));
2351 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "NONLOCAL", name, (char *)NULL);
2352 return TCL_ERROR;
2353 }
2354 }
2355 return TCL_OK;
2356 }
2357
2358 /*
2359 *-----------------------------------------------------------------------------
2360 *
2361 * CheckOneByte --
2362 *
2363 * Verify that a constant fits in a single byte in the instruction
2364 * stream.
2365 *
2366 * Results:
2367 * On success, returns TCL_OK. On failure, returns TCL_ERROR and stores
2368 * an error message in the interpreter result.
2369 *
2370 * This code is here primarily to verify that instructions like INCR_SCALAR1
2371 * are possible on a given local variable. The fact that there is no
2372 * INCR_SCALAR4 is puzzling.
2373 *
2374 *-----------------------------------------------------------------------------
2375 */
2376
2377 static int
2378 CheckOneByte(
2379 Tcl_Interp* interp, /* Tcl interpreter for error reporting */
2380 int value) /* Value to check */
2381 {
2382 Tcl_Obj* result; /* Error message */
2383
2384 if (value < 0 || value > 0xFF) {
2385 result = Tcl_NewStringObj("operand does not fit in one byte", -1);
2386 Tcl_SetObjResult(interp, result);
2387 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "1BYTE", (char *)NULL);
2388 return TCL_ERROR;
2389 }
2390 return TCL_OK;
2391 }
2392
2393 /*
2394 *-----------------------------------------------------------------------------
2395 *
2396 * CheckSignedOneByte --
2397 *
2398 * Verify that a constant fits in a single signed byte in the instruction
2399 * stream.
2400 *
2401 * Results:
2402 * On success, returns TCL_OK. On failure, returns TCL_ERROR and stores
2403 * an error message in the interpreter result.
2404 *
2405 * This code is here primarily to verify that instructions like INCR_SCALAR1
2406 * are possible on a given local variable. The fact that there is no
2407 * INCR_SCALAR4 is puzzling.
2408 *
2409 *-----------------------------------------------------------------------------
2410 */
2411
2412 static int
2413 CheckSignedOneByte(
2414 Tcl_Interp* interp, /* Tcl interpreter for error reporting */
2415 int value) /* Value to check */
2416 {
2417 Tcl_Obj* result; /* Error message */
2418
2419 if (value > 0x7F || value < -0x80) {
2420 result = Tcl_NewStringObj("operand does not fit in one byte", -1);
2421 Tcl_SetObjResult(interp, result);
2422 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "1BYTE", (char *)NULL);
2423 return TCL_ERROR;
2424 }
2425 return TCL_OK;
2426 }
2427
2428 /*
2429 *-----------------------------------------------------------------------------
2430 *
2431 * CheckNonNegative --
2432 *
2433 * Verify that a constant is nonnegative
2434 *
2435 * Results:
2436 * On success, returns TCL_OK. On failure, returns TCL_ERROR and stores
2437 * an error message in the interpreter result.
2438 *
2439 * This code is here primarily to verify that instructions like INCR_INVOKE
2440 * are consuming a positive number of operands
2441 *
2442 *-----------------------------------------------------------------------------
2443 */
2444
2445 static int
2446 CheckNonNegative(
2447 Tcl_Interp* interp, /* Tcl interpreter for error reporting */
2448 int value) /* Value to check */
2449 {
2450 Tcl_Obj* result; /* Error message */
2451
2452 if (value < 0) {
2453 result = Tcl_NewStringObj("operand must be nonnegative", -1);
2454 Tcl_SetObjResult(interp, result);
2455 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "NONNEGATIVE", (char *)NULL);
2456 return TCL_ERROR;
2457 }
2458 return TCL_OK;
2459 }
2460
2461 /*
2462 *-----------------------------------------------------------------------------
2463 *
2464 * CheckStrictlyPositive --
2465 *
2466 * Verify that a constant is positive
2467 *
2468 * Results:
2469 * On success, returns TCL_OK. On failure, returns TCL_ERROR and
2470 * stores an error message in the interpreter result.
2471 *
2472 * This code is here primarily to verify that instructions like INCR_INVOKE
2473 * are consuming a positive number of operands
2474 *
2475 *-----------------------------------------------------------------------------
2476 */
2477
2478 static int
2479 CheckStrictlyPositive(
2480 Tcl_Interp* interp, /* Tcl interpreter for error reporting */
2481 int value) /* Value to check */
2482 {
2483 Tcl_Obj* result; /* Error message */
2484
2485 if (value <= 0) {
2486 result = Tcl_NewStringObj("operand must be positive", -1);
2487 Tcl_SetObjResult(interp, result);
2488 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "POSITIVE", (char *)NULL);
2489 return TCL_ERROR;
2490 }
2491 return TCL_OK;
2492 }
2493
2494 /*
2495 *-----------------------------------------------------------------------------
2496 *
2497 * DefineLabel --
2498 *
2499 * Defines a label appearing in the assembly sequence.
2500 *
2501 * Results:
2502 * Returns a standard Tcl result. Returns TCL_OK and an empty result if
2503 * the definition succeeds; returns TCL_ERROR and an appropriate message
2504 * if a duplicate definition is found.
2505 *
2506 *-----------------------------------------------------------------------------
2507 */
2508
2509 static int
2510 DefineLabel(
2511 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2512 const char* labelName) /* Label being defined */
2513 {
2514 CompileEnv* envPtr = assemEnvPtr->envPtr;
2515 /* Compilation environment */
2516 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
2517 /* Tcl interpreter */
2518 Tcl_HashEntry* entry; /* Label's entry in the symbol table */
2519 int isNew; /* Flag == 1 iff the label was previously
2520 * undefined */
2521
2522 /* TODO - This can now be simplified! */
2523
2524 StartBasicBlock(assemEnvPtr, BB_FALLTHRU, NULL);
2525
2526 /*
2527 * Look up the newly-defined label in the symbol table.
2528 */
2529
2530 entry = Tcl_CreateHashEntry(&assemEnvPtr->labelHash, labelName, &isNew);
2531 if (!isNew) {
2532 /*
2533 * This is a duplicate label.
2534 */
2535
2536 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
2537 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2538 "duplicate definition of label \"%s\"", labelName));
2539 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "DUPLABEL", labelName,
2540 (char *)NULL);
2541 }
2542 return TCL_ERROR;
2543 }
2544
2545 /*
2546 * This is the first appearance of the label in the code.
2547 */
2548
2549 Tcl_SetHashValue(entry, assemEnvPtr->curr_bb);
2550 return TCL_OK;
2551 }
2552
2553 /*
2554 *-----------------------------------------------------------------------------
2555 *
2556 * StartBasicBlock --
2557 *
2558 * Starts a new basic block when a label or jump is encountered.
2559 *
2560 * Results:
2561 * Returns a pointer to the BasicBlock structure of the new
2562 * basic block.
2563 *
2564 *-----------------------------------------------------------------------------
2565 */
2566
2567 static BasicBlock*
2568 StartBasicBlock(
2569 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2570 int flags, /* Flags to apply to the basic block being
2571 * closed, if there is one. */
2572 Tcl_Obj* jumpLabel) /* Label of the location that the block jumps
2573 * to, or NULL if the block does not jump */
2574 {
2575 CompileEnv* envPtr = assemEnvPtr->envPtr;
2576 /* Compilation environment */
2577 BasicBlock* newBB; /* BasicBlock structure for the new block */
2578 BasicBlock* currBB = assemEnvPtr->curr_bb;
2579
2580 /*
2581 * Coalesce zero-length blocks.
2582 */
2583
2584 if (currBB->startOffset == envPtr->codeNext - envPtr->codeStart) {
2585 currBB->startLine = assemEnvPtr->cmdLine;
2586 return currBB;
2587 }
2588
2589 /*
2590 * Make the new basic block.
2591 */
2592
2593 newBB = AllocBB(assemEnvPtr);
2594
2595 /*
2596 * Record the jump target if there is one.
2597 */
2598
2599 currBB->jumpTarget = jumpLabel;
2600 if (jumpLabel != NULL) {
2601 Tcl_IncrRefCount(currBB->jumpTarget);
2602 }
2603
2604 /*
2605 * Record the fallthrough if there is one.
2606 */
2607
2608 currBB->flags |= flags;
2609
2610 /*
2611 * Record the successor block.
2612 */
2613
2614 currBB->successor1 = newBB;
2615 assemEnvPtr->curr_bb = newBB;
2616 return newBB;
2617 }
2618
2619 /*
2620 *-----------------------------------------------------------------------------
2621 *
2622 * AllocBB --
2623 *
2624 * Allocates a new basic block
2625 *
2626 * Results:
2627 * Returns a pointer to the newly allocated block, which is initialized
2628 * to contain no code and begin at the current instruction pointer.
2629 *
2630 *-----------------------------------------------------------------------------
2631 */
2632
2633 static BasicBlock *
2634 AllocBB(
2635 AssemblyEnv* assemEnvPtr) /* Assembly environment */
2636 {
2637 CompileEnv* envPtr = assemEnvPtr->envPtr;
2638 BasicBlock *bb = (BasicBlock*)ckalloc(sizeof(BasicBlock));
2639
2640 bb->originalStartOffset =
2641 bb->startOffset = envPtr->codeNext - envPtr->codeStart;
2642 bb->startLine = assemEnvPtr->cmdLine + 1;
2643 bb->jumpOffset = -1;
2644 bb->jumpLine = -1;
2645 bb->prevPtr = assemEnvPtr->curr_bb;
2646 bb->predecessor = NULL;
2647 bb->successor1 = NULL;
2648 bb->jumpTarget = NULL;
2649 bb->initialStackDepth = 0;
2650 bb->minStackDepth = 0;
2651 bb->maxStackDepth = 0;
2652 bb->finalStackDepth = 0;
2653 bb->catchDepth = 0;
2654 bb->enclosingCatch = NULL;
2655 bb->foreignExceptionBase = -1;
2656 bb->foreignExceptionCount = 0;
2657 bb->foreignExceptions = NULL;
2658 bb->jtPtr = NULL;
2659 bb->flags = 0;
2660
2661 return bb;
2662 }
2663
2664 /*
2665 *-----------------------------------------------------------------------------
2666 *
2667 * FinishAssembly --
2668 *
2669 * Postprocessing after all bytecode has been generated for a block of
2670 * assembly code.
2671 *
2672 * Results:
2673 * Returns a standard Tcl result, with an error message left in the
2674 * interpreter if appropriate.
2675 *
2676 * Side effects:
2677 * The program is checked to see if any undefined labels remain. The
2678 * initial stack depth of all the basic blocks in the flow graph is
2679 * calculated and saved. The stack balance on exit is computed, checked
2680 * and saved.
2681 *
2682 *-----------------------------------------------------------------------------
2683 */
2684
2685 static int
2686 FinishAssembly(
2687 AssemblyEnv* assemEnvPtr) /* Assembly environment */
2688 {
2689 int mustMove; /* Amount by which the code needs to be grown
2690 * because of expanding jumps */
2691
2692 /*
2693 * Resolve the targets of all jumps and determine whether code needs to be
2694 * moved around.
2695 */
2696
2697 if (CalculateJumpRelocations(assemEnvPtr, &mustMove)) {
2698 return TCL_ERROR;
2699 }
2700
2701 /*
2702 * Move the code if necessary.
2703 */
2704
2705 if (mustMove) {
2706 MoveCodeForJumps(assemEnvPtr, mustMove);
2707 }
2708
2709 /*
2710 * Resolve jump target labels to bytecode offsets.
2711 */
2712
2713 FillInJumpOffsets(assemEnvPtr);
2714
2715 /*
2716 * Label each basic block with its catch context. Quit on inconsistency.
2717 */
2718
2719 if (ProcessCatches(assemEnvPtr) != TCL_OK) {
2720 return TCL_ERROR;
2721 }
2722
2723 /*
2724 * Make sure that no block accessible from a catch's error exit that hasn't
2725 * popped the exception stack can throw an exception.
2726 */
2727
2728 if (CheckForThrowInWrongContext(assemEnvPtr) != TCL_OK) {
2729 return TCL_ERROR;
2730 }
2731
2732 /*
2733 * Compute stack balance throughout the program.
2734 */
2735
2736 if (CheckStack(assemEnvPtr) != TCL_OK) {
2737 return TCL_ERROR;
2738 }
2739
2740 /*
2741 * TODO - Check for unreachable code. Or maybe not; unreachable code is
2742 * Mostly Harmless.
2743 */
2744
2745 return TCL_OK;
2746 }
2747
2748 /*
2749 *-----------------------------------------------------------------------------
2750 *
2751 * CalculateJumpRelocations --
2752 *
2753 * Calculate any movement that has to be done in the assembly code to
2754 * expand JUMP1 instructions to JUMP4 (because they jump more than a
2755 * 1-byte range).
2756 *
2757 * Results:
2758 * Returns a standard Tcl result, with an appropriate error message if
2759 * anything fails.
2760 *
2761 * Side effects:
2762 * Sets the 'startOffset' pointer in every basic block to the new origin
2763 * of the block, and turns off JUMP1 flags on instructions that must be
2764 * expanded (and adjusts them to the corresponding JUMP4's). Does *not*
2765 * store the jump offsets at this point.
2766 *
2767 * Sets *mustMove to 1 if and only if at least one instruction changed
2768 * size so the code must be moved.
2769 *
2770 * As a side effect, also checks for undefined labels and reports them.
2771 *
2772 *-----------------------------------------------------------------------------
2773 */
2774
2775 static int
2776 CalculateJumpRelocations(
2777 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2778 int* mustMove) /* OUTPUT: Number of bytes that have been
2779 * added to the code */
2780 {
2781 CompileEnv* envPtr = assemEnvPtr->envPtr;
2782 /* Compilation environment */
2783 BasicBlock* bbPtr; /* Pointer to a basic block being checked */
2784 Tcl_HashEntry* entry; /* Exit label's entry in the symbol table */
2785 BasicBlock* jumpTarget; /* Basic block where the jump goes */
2786 int motion; /* Amount by which the code has expanded */
2787 int offset; /* Offset in the bytecode from a jump
2788 * instruction to its target */
2789 unsigned opcode; /* Opcode in the bytecode being adjusted */
2790
2791 /*
2792 * Iterate through basic blocks as long as a change results in code
2793 * expansion.
2794 */
2795
2796 *mustMove = 0;
2797 do {
2798 motion = 0;
2799 for (bbPtr = assemEnvPtr->head_bb;
2800 bbPtr != NULL;
2801 bbPtr = bbPtr->successor1) {
2802 /*
2803 * Advance the basic block start offset by however many bytes we
2804 * have inserted in the code up to this point
2805 */
2806
2807 bbPtr->startOffset += motion;
2808
2809 /*
2810 * If the basic block references a label (and hence performs a
2811 * jump), find the location of the label. Report an error if the
2812 * label is missing.
2813 */
2814
2815 if (bbPtr->jumpTarget != NULL) {
2816 entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
2817 TclGetString(bbPtr->jumpTarget));
2818 if (entry == NULL) {
2819 ReportUndefinedLabel(assemEnvPtr, bbPtr,
2820 bbPtr->jumpTarget);
2821 return TCL_ERROR;
2822 }
2823
2824 /*
2825 * If the instruction is a JUMP1, turn it into a JUMP4 if its
2826 * target is out of range.
2827 */
2828
2829 jumpTarget = (BasicBlock*)Tcl_GetHashValue(entry);
2830 if (bbPtr->flags & BB_JUMP1) {
2831 offset = jumpTarget->startOffset
2832 - (bbPtr->jumpOffset + motion);
2833 if (offset < -0x80 || offset > 0x7F) {
2834 opcode = TclGetUInt1AtPtr(envPtr->codeStart
2835 + bbPtr->jumpOffset);
2836 ++opcode;
2837 TclStoreInt1AtPtr(opcode,
2838 envPtr->codeStart + bbPtr->jumpOffset);
2839 motion += 3;
2840 bbPtr->flags &= ~BB_JUMP1;
2841 }
2842 }
2843 }
2844
2845 /*
2846 * If the basic block references a jump table, that doesn't affect
2847 * the code locations, but resolve the labels now, and store basic
2848 * block pointers in the jumptable hash.
2849 */
2850
2851 if (bbPtr->flags & BB_JUMPTABLE) {
2852 if (CheckJumpTableLabels(assemEnvPtr, bbPtr) != TCL_OK) {
2853 return TCL_ERROR;
2854 }
2855 }
2856 }
2857 *mustMove += motion;
2858 } while (motion != 0);
2859
2860 return TCL_OK;
2861 }
2862
2863 /*
2864 *-----------------------------------------------------------------------------
2865 *
2866 * CheckJumpTableLabels --
2867 *
2868 * Make sure that all the labels in a jump table are defined.
2869 *
2870 * Results:
2871 * Returns TCL_OK if they are, TCL_ERROR if they aren't.
2872 *
2873 *-----------------------------------------------------------------------------
2874 */
2875
2876 static int
2877 CheckJumpTableLabels(
2878 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2879 BasicBlock* bbPtr) /* Basic block that ends in a jump table */
2880 {
2881 Tcl_HashTable* symHash = &bbPtr->jtPtr->hashTable;
2882 /* Hash table with the symbols */
2883 Tcl_HashSearch search; /* Hash table iterator */
2884 Tcl_HashEntry* symEntryPtr; /* Hash entry for the symbols */
2885 Tcl_Obj* symbolObj; /* Jump target */
2886 Tcl_HashEntry* valEntryPtr; /* Hash entry for the resolutions */
2887
2888 /*
2889 * Look up every jump target in the jump hash.
2890 */
2891
2892 DEBUG_PRINT("check jump table labels %p {\n", bbPtr);
2893 for (symEntryPtr = Tcl_FirstHashEntry(symHash, &search);
2894 symEntryPtr != NULL;
2895 symEntryPtr = Tcl_NextHashEntry(&search)) {
2896 symbolObj = (Tcl_Obj*)Tcl_GetHashValue(symEntryPtr);
2897 valEntryPtr = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
2898 TclGetString(symbolObj));
2899 DEBUG_PRINT(" %s -> %s (%d)\n",
2900 (char*) Tcl_GetHashKey(symHash, symEntryPtr),
2901 TclGetString(symbolObj), (valEntryPtr != NULL));
2902 if (valEntryPtr == NULL) {
2903 ReportUndefinedLabel(assemEnvPtr, bbPtr, symbolObj);
2904 return TCL_ERROR;
2905 }
2906 }
2907 DEBUG_PRINT("}\n");
2908 return TCL_OK;
2909 }
2910
2911 /*
2912 *-----------------------------------------------------------------------------
2913 *
2914 * ReportUndefinedLabel --
2915 *
2916 * Report that a basic block refers to an undefined jump label
2917 *
2918 * Side effects:
2919 * Stores an error message, error code, and line number information in
2920 * the assembler's Tcl interpreter.
2921 *
2922 *-----------------------------------------------------------------------------
2923 */
2924
2925 static void
2926 ReportUndefinedLabel(
2927 AssemblyEnv* assemEnvPtr, /* Assembly environment */
2928 BasicBlock* bbPtr, /* Basic block that contains the undefined
2929 * label */
2930 Tcl_Obj* jumpTarget) /* Label of a jump target */
2931 {
2932 CompileEnv* envPtr = assemEnvPtr->envPtr;
2933 /* Compilation environment */
2934 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
2935 /* Tcl interpreter */
2936
2937 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
2938 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
2939 "undefined label \"%s\"", TclGetString(jumpTarget)));
2940 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "NOLABEL",
2941 TclGetString(jumpTarget), (char *)NULL);
2942 Tcl_SetErrorLine(interp, bbPtr->jumpLine);
2943 }
2944 }
2945
2946 /*
2947 *-----------------------------------------------------------------------------
2948 *
2949 * MoveCodeForJumps --
2950 *
2951 * Move bytecodes in memory to accommodate JUMP1 instructions that have
2952 * expanded to become JUMP4's.
2953 *
2954 *-----------------------------------------------------------------------------
2955 */
2956
2957 static void
2958 MoveCodeForJumps(
2959 AssemblyEnv* assemEnvPtr, /* Assembler environment */
2960 int mustMove) /* Number of bytes of added code */
2961 {
2962 CompileEnv* envPtr = assemEnvPtr->envPtr;
2963 /* Compilation environment */
2964 BasicBlock* bbPtr; /* Pointer to a basic block being checked */
2965 int topOffset; /* Bytecode offset of the following basic
2966 * block before code motion */
2967
2968 /*
2969 * Make sure that there is enough space in the bytecode array to
2970 * accommodate the expanded code.
2971 */
2972
2973 while (envPtr->codeEnd < envPtr->codeNext + mustMove) {
2974 TclExpandCodeArray(envPtr);
2975 }
2976
2977 /*
2978 * Iterate through the bytecodes in reverse order, and move them upward to
2979 * their new homes.
2980 */
2981
2982 topOffset = envPtr->codeNext - envPtr->codeStart;
2983 for (bbPtr = assemEnvPtr->curr_bb; bbPtr != NULL; bbPtr = bbPtr->prevPtr) {
2984 DEBUG_PRINT("move code from %d to %d\n",
2985 bbPtr->originalStartOffset, bbPtr->startOffset);
2986 memmove(envPtr->codeStart + bbPtr->startOffset,
2987 envPtr->codeStart + bbPtr->originalStartOffset,
2988 topOffset - bbPtr->originalStartOffset);
2989 topOffset = bbPtr->originalStartOffset;
2990 bbPtr->jumpOffset += (bbPtr->startOffset - bbPtr->originalStartOffset);
2991 }
2992 envPtr->codeNext += mustMove;
2993 }
2994
2995 /*
2996 *-----------------------------------------------------------------------------
2997 *
2998 * FillInJumpOffsets --
2999 *
3000 * Fill in the final offsets of all jump instructions once bytecode
3001 * locations have been completely determined.
3002 *
3003 *-----------------------------------------------------------------------------
3004 */
3005
3006 static void
3007 FillInJumpOffsets(
3008 AssemblyEnv* assemEnvPtr) /* Assembly environment */
3009 {
3010 CompileEnv* envPtr = assemEnvPtr->envPtr;
3011 /* Compilation environment */
3012 BasicBlock* bbPtr; /* Pointer to a basic block being checked */
3013 Tcl_HashEntry* entry; /* Hashtable entry for a jump target label */
3014 BasicBlock* jumpTarget; /* Basic block where a jump goes */
3015 int fromOffset; /* Bytecode location of a jump instruction */
3016 int targetOffset; /* Bytecode location of a jump instruction's
3017 * target */
3018
3019 for (bbPtr = assemEnvPtr->head_bb;
3020 bbPtr != NULL;
3021 bbPtr = bbPtr->successor1) {
3022 if (bbPtr->jumpTarget != NULL) {
3023 entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
3024 TclGetString(bbPtr->jumpTarget));
3025 jumpTarget = (BasicBlock*)Tcl_GetHashValue(entry);
3026 fromOffset = bbPtr->jumpOffset;
3027 targetOffset = jumpTarget->startOffset;
3028 if (bbPtr->flags & BB_JUMP1) {
3029 TclStoreInt1AtPtr(targetOffset - fromOffset,
3030 envPtr->codeStart + fromOffset + 1);
3031 } else {
3032 TclStoreInt4AtPtr(targetOffset - fromOffset,
3033 envPtr->codeStart + fromOffset + 1);
3034 }
3035 }
3036 if (bbPtr->flags & BB_JUMPTABLE) {
3037 ResolveJumpTableTargets(assemEnvPtr, bbPtr);
3038 }
3039 }
3040 }
3041
3042 /*
3043 *-----------------------------------------------------------------------------
3044 *
3045 * ResolveJumpTableTargets --
3046 *
3047 * Puts bytecode addresses for the targets of a jumptable into the
3048 * table
3049 *
3050 * Results:
3051 * Returns TCL_OK if they are, TCL_ERROR if they aren't.
3052 *
3053 *-----------------------------------------------------------------------------
3054 */
3055
3056 static void
3057 ResolveJumpTableTargets(
3058 AssemblyEnv* assemEnvPtr, /* Assembly environment */
3059 BasicBlock* bbPtr) /* Basic block that ends in a jump table */
3060 {
3061 CompileEnv* envPtr = assemEnvPtr->envPtr;
3062 /* Compilation environment */
3063 Tcl_HashTable* symHash = &bbPtr->jtPtr->hashTable;
3064 /* Hash table with the symbols */
3065 Tcl_HashSearch search; /* Hash table iterator */
3066 Tcl_HashEntry* symEntryPtr; /* Hash entry for the symbols */
3067 Tcl_Obj* symbolObj; /* Jump target */
3068 Tcl_HashEntry* valEntryPtr; /* Hash entry for the resolutions */
3069 int auxDataIndex; /* Index of the auxdata */
3070 JumptableInfo* realJumpTablePtr;
3071 /* Jump table in the actual code */
3072 Tcl_HashTable* realJumpHashPtr;
3073 /* Jump table hash in the actual code */
3074 Tcl_HashEntry* realJumpEntryPtr;
3075 /* Entry in the jump table hash in
3076 * the actual code */
3077 BasicBlock* jumpTargetBBPtr;
3078 /* Basic block that the jump proceeds to */
3079 int junk;
3080
3081 auxDataIndex = TclGetInt4AtPtr(envPtr->codeStart + bbPtr->jumpOffset + 1);
3082 DEBUG_PRINT("bbPtr = %p jumpOffset = %d auxDataIndex = %d\n",
3083 bbPtr, bbPtr->jumpOffset, auxDataIndex);
3084 realJumpTablePtr = (JumptableInfo*)TclFetchAuxData(envPtr, auxDataIndex);
3085 realJumpHashPtr = &realJumpTablePtr->hashTable;
3086
3087 /*
3088 * Look up every jump target in the jump hash.
3089 */
3090
3091 DEBUG_PRINT("resolve jump table {\n");
3092 for (symEntryPtr = Tcl_FirstHashEntry(symHash, &search);
3093 symEntryPtr != NULL;
3094 symEntryPtr = Tcl_NextHashEntry(&search)) {
3095 symbolObj = (Tcl_Obj*)Tcl_GetHashValue(symEntryPtr);
3096 DEBUG_PRINT(" symbol %s\n", TclGetString(symbolObj));
3097
3098 valEntryPtr = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
3099 TclGetString(symbolObj));
3100 jumpTargetBBPtr = (BasicBlock*)Tcl_GetHashValue(valEntryPtr);
3101
3102 realJumpEntryPtr = Tcl_CreateHashEntry(realJumpHashPtr,
3103 Tcl_GetHashKey(symHash, symEntryPtr), &junk);
3104 DEBUG_PRINT(" %s -> %s -> bb %p (pc %d) hash entry %p\n",
3105 (char*) Tcl_GetHashKey(symHash, symEntryPtr),
3106 TclGetString(symbolObj), jumpTargetBBPtr,
3107 jumpTargetBBPtr->startOffset, realJumpEntryPtr);
3108
3109 Tcl_SetHashValue(realJumpEntryPtr,
3110 INT2PTR(jumpTargetBBPtr->startOffset - bbPtr->jumpOffset));
3111 }
3112 DEBUG_PRINT("}\n");
3113 }
3114
3115 /*
3116 *-----------------------------------------------------------------------------
3117 *
3118 * CheckForThrowInWrongContext --
3119 *
3120 * Verify that no beginCatch/endCatch sequence can throw an exception
3121 * after an original exception is caught and before its exception context
3122 * is removed from the stack.
3123 *
3124 * Results:
3125 * Returns a standard Tcl result.
3126 *
3127 * Side effects:
3128 * Stores an appropriate error message in the interpreter as needed.
3129 *
3130 *-----------------------------------------------------------------------------
3131 */
3132
3133 static int
3134 CheckForThrowInWrongContext(
3135 AssemblyEnv* assemEnvPtr) /* Assembly environment */
3136 {
3137 BasicBlock* blockPtr; /* Current basic block */
3138
3139 /*
3140 * Walk through the basic blocks in turn, checking all the ones that have
3141 * caught an exception and not disposed of it properly.
3142 */
3143
3144 for (blockPtr = assemEnvPtr->head_bb;
3145 blockPtr != NULL;
3146 blockPtr = blockPtr->successor1) {
3147 if (blockPtr->catchState == BBCS_CAUGHT) {
3148 /*
3149 * Walk through the instructions in the basic block.
3150 */
3151
3152 if (CheckNonThrowingBlock(assemEnvPtr, blockPtr) != TCL_OK) {
3153 return TCL_ERROR;
3154 }
3155 }
3156 }
3157 return TCL_OK;
3158 }
3159
3160 /*
3161 *-----------------------------------------------------------------------------
3162 *
3163 * CheckNonThrowingBlock --
3164 *
3165 * Check that a basic block cannot throw an exception.
3166 *
3167 * Results:
3168 * Returns TCL_ERROR if the block cannot be proven to be nonthrowing.
3169 *
3170 * Side effects:
3171 * Stashes an error message in the interpreter result.
3172 *
3173 *-----------------------------------------------------------------------------
3174 */
3175
3176 static int
3177 CheckNonThrowingBlock(
3178 AssemblyEnv* assemEnvPtr, /* Assembly environment */
3179 BasicBlock* blockPtr) /* Basic block where exceptions are not
3180 * allowed */
3181 {
3182 CompileEnv* envPtr = assemEnvPtr->envPtr;
3183 /* Compilation environment */
3184 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
3185 /* Tcl interpreter */
3186 BasicBlock* nextPtr; /* Pointer to the succeeding basic block */
3187 int offset; /* Bytecode offset of the current
3188 * instruction */
3189 int bound; /* Bytecode offset following the last
3190 * instruction of the block. */
3191 unsigned char opcode; /* Current bytecode instruction */
3192
3193 /*
3194 * Determine where in the code array the basic block ends.
3195 */
3196
3197 nextPtr = blockPtr->successor1;
3198 if (nextPtr == NULL) {
3199 bound = envPtr->codeNext - envPtr->codeStart;
3200 } else {
3201 bound = nextPtr->startOffset;
3202 }
3203
3204 /*
3205 * Walk through the instructions of the block.
3206 */
3207
3208 offset = blockPtr->startOffset;
3209 while (offset < bound) {
3210 /*
3211 * Determine whether an instruction is nonthrowing.
3212 */
3213
3214 opcode = (envPtr->codeStart)[offset];
3215 if (BytecodeMightThrow(opcode)) {
3216 /*
3217 * Report an error for a throw in the wrong context.
3218 */
3219
3220 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
3221 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3222 "\"%s\" instruction may not appear in "
3223 "a context where an exception has been "
3224 "caught and not disposed of.",
3225 tclInstructionTable[opcode].name));
3226 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADTHROW", (char *)NULL);
3227 AddBasicBlockRangeToErrorInfo(assemEnvPtr, blockPtr);
3228 }
3229 return TCL_ERROR;
3230 }
3231 offset += tclInstructionTable[opcode].numBytes;
3232 }
3233 return TCL_OK;
3234 }
3235
3236 /*
3237 *-----------------------------------------------------------------------------
3238 *
3239 * BytecodeMightThrow --
3240 *
3241 * Tests if a given bytecode instruction might throw an exception.
3242 *
3243 * Results:
3244 * Returns 1 if the bytecode might throw an exception, 0 if the
3245 * instruction is known never to throw.
3246 *
3247 *-----------------------------------------------------------------------------
3248 */
3249
3250 static int
3251 BytecodeMightThrow(
3252 unsigned char opcode)
3253 {
3254 /*
3255 * Binary search on the non-throwing bytecode list.
3256 */
3257
3258 int min = 0;
3259 int max = sizeof(NonThrowingByteCodes) - 1;
3260 int mid;
3261 unsigned char c;
3262
3263 while (max >= min) {
3264 mid = (min + max) / 2;
3265 c = NonThrowingByteCodes[mid];
3266 if (opcode < c) {
3267 max = mid-1;
3268 } else if (opcode > c) {
3269 min = mid+1;
3270 } else {
3271 /*
3272 * Opcode is nonthrowing.
3273 */
3274
3275 return 0;
3276 }
3277 }
3278
3279 return 1;
3280 }
3281
3282 /*
3283 *-----------------------------------------------------------------------------
3284 *
3285 * CheckStack --
3286 *
3287 * Audit stack usage in a block of assembly code.
3288 *
3289 * Results:
3290 * Returns a standard Tcl result.
3291 *
3292 * Side effects:
3293 * Updates stack depth on entry for all basic blocks in the flowgraph.
3294 * Calculates the max stack depth used in the program, and updates the
3295 * compilation environment to reflect it.
3296 *
3297 *-----------------------------------------------------------------------------
3298 */
3299
3300 static int
3301 CheckStack(
3302 AssemblyEnv* assemEnvPtr) /* Assembly environment */
3303 {
3304 CompileEnv* envPtr = assemEnvPtr->envPtr;
3305 /* Compilation environment */
3306 int maxDepth; /* Maximum stack depth overall */
3307
3308 /*
3309 * Checking the head block will check all the other blocks recursively.
3310 */
3311
3312 assemEnvPtr->maxDepth = 0;
3313 if (StackCheckBasicBlock(assemEnvPtr, assemEnvPtr->head_bb, NULL,
3314 0) == TCL_ERROR) {
3315 return TCL_ERROR;
3316 }
3317
3318 /*
3319 * Post the max stack depth back to the compilation environment.
3320 */
3321
3322 maxDepth = assemEnvPtr->maxDepth + envPtr->currStackDepth;
3323 if (maxDepth > envPtr->maxStackDepth) {
3324 envPtr->maxStackDepth = maxDepth;
3325 }
3326
3327 /*
3328 * If the exit is reachable, make sure that the program exits with 1
3329 * operand on the stack.
3330 */
3331
3332 if (StackCheckExit(assemEnvPtr) != TCL_OK) {
3333 return TCL_ERROR;
3334 }
3335
3336 /*
3337 * Reset the visited state on all basic blocks.
3338 */
3339
3340 ResetVisitedBasicBlocks(assemEnvPtr);
3341 return TCL_OK;
3342 }
3343
3344 /*
3345 *-----------------------------------------------------------------------------
3346 *
3347 * StackCheckBasicBlock --
3348 *
3349 * Checks stack consumption for a basic block (and recursively for its
3350 * successors).
3351 *
3352 * Results:
3353 * Returns a standard Tcl result.
3354 *
3355 * Side effects:
3356 * Updates initial stack depth for the basic block and its successors.
3357 * (Final and maximum stack depth are relative to initial, and are not
3358 * touched).
3359 *
3360 * This procedure eventually checks, for the entire flow graph, whether stack
3361 * balance is consistent. It is an error for a given basic block to be
3362 * reachable along multiple flow paths with different stack depths.
3363 *
3364 *-----------------------------------------------------------------------------
3365 */
3366
3367 static int
3368 StackCheckBasicBlock(
3369 AssemblyEnv* assemEnvPtr, /* Assembly environment */
3370 BasicBlock* blockPtr, /* Pointer to the basic block being checked */
3371 BasicBlock* predecessor, /* Pointer to the block that passed control to
3372 * this one. */
3373 int initialStackDepth) /* Stack depth on entry to the block */
3374 {
3375 CompileEnv* envPtr = assemEnvPtr->envPtr;
3376 /* Compilation environment */
3377 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
3378 /* Tcl interpreter */
3379 BasicBlock* jumpTarget; /* Basic block where a jump goes */
3380 int stackDepth; /* Current stack depth */
3381 int maxDepth; /* Maximum stack depth so far */
3382 int result; /* Tcl status return */
3383 Tcl_HashSearch jtSearch; /* Search structure for the jump table */
3384 Tcl_HashEntry* jtEntry; /* Hash entry in the jump table */
3385 Tcl_Obj* targetLabel; /* Target label from the jump table */
3386 Tcl_HashEntry* entry; /* Hash entry in the label table */
3387
3388 if (blockPtr->flags & BB_VISITED) {
3389 /*
3390 * If the block is already visited, check stack depth for consistency
3391 * among the paths that reach it.
3392 */
3393
3394 if (blockPtr->initialStackDepth == initialStackDepth) {
3395 return TCL_OK;
3396 }
3397 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
3398 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3399 "inconsistent stack depths on two execution paths", -1));
3400
3401 /*
3402 * TODO - add execution trace of both paths
3403 */
3404
3405 Tcl_SetErrorLine(interp, blockPtr->startLine);
3406 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADSTACK", (char *)NULL);
3407 }
3408 return TCL_ERROR;
3409 }
3410
3411 /*
3412 * If the block is not already visited, set the 'predecessor' link to
3413 * indicate how control got to it. Set the initial stack depth to the
3414 * current stack depth in the flow of control.
3415 */
3416
3417 blockPtr->flags |= BB_VISITED;
3418 blockPtr->predecessor = predecessor;
3419 blockPtr->initialStackDepth = initialStackDepth;
3420
3421 /*
3422 * Calculate minimum stack depth, and flag an error if the block
3423 * underflows the stack.
3424 */
3425
3426 if (initialStackDepth + blockPtr->minStackDepth < 0) {
3427 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
3428 Tcl_SetObjResult(interp, Tcl_NewStringObj("stack underflow", -1));
3429 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADSTACK", (char *)NULL);
3430 AddBasicBlockRangeToErrorInfo(assemEnvPtr, blockPtr);
3431 Tcl_SetErrorLine(interp, blockPtr->startLine);
3432 }
3433 return TCL_ERROR;
3434 }
3435
3436 /*
3437 * Make sure that the block doesn't try to pop below the stack level of an
3438 * enclosing catch.
3439 */
3440
3441 if (blockPtr->enclosingCatch != 0 &&
3442 initialStackDepth + blockPtr->minStackDepth
3443 < (blockPtr->enclosingCatch->initialStackDepth
3444 + blockPtr->enclosingCatch->finalStackDepth)) {
3445 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
3446 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3447 "code pops stack below level of enclosing catch", -1));
3448 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADSTACKINCATCH", (char *)NULL);
3449 AddBasicBlockRangeToErrorInfo(assemEnvPtr, blockPtr);
3450 Tcl_SetErrorLine(interp, blockPtr->startLine);
3451 }
3452 return TCL_ERROR;
3453 }
3454
3455 /*
3456 * Update maximum stgack depth.
3457 */
3458
3459 maxDepth = initialStackDepth + blockPtr->maxStackDepth;
3460 if (maxDepth > assemEnvPtr->maxDepth) {
3461 assemEnvPtr->maxDepth = maxDepth;
3462 }
3463
3464 /*
3465 * Calculate stack depth on exit from the block, and invoke this procedure
3466 * recursively to check successor blocks.
3467 */
3468
3469 stackDepth = initialStackDepth + blockPtr->finalStackDepth;
3470 result = TCL_OK;
3471 if (blockPtr->flags & BB_FALLTHRU) {
3472 result = StackCheckBasicBlock(assemEnvPtr, blockPtr->successor1,
3473 blockPtr, stackDepth);
3474 }
3475
3476 if (result == TCL_OK && blockPtr->jumpTarget != NULL) {
3477 entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
3478 TclGetString(blockPtr->jumpTarget));
3479 jumpTarget = (BasicBlock*)Tcl_GetHashValue(entry);
3480 result = StackCheckBasicBlock(assemEnvPtr, jumpTarget, blockPtr,
3481 stackDepth);
3482 }
3483
3484 /*
3485 * All blocks referenced in a jump table are successors.
3486 */
3487
3488 if (blockPtr->flags & BB_JUMPTABLE) {
3489 for (jtEntry = Tcl_FirstHashEntry(&blockPtr->jtPtr->hashTable,
3490 &jtSearch);
3491 result == TCL_OK && jtEntry != NULL;
3492 jtEntry = Tcl_NextHashEntry(&jtSearch)) {
3493 targetLabel = (Tcl_Obj*)Tcl_GetHashValue(jtEntry);
3494 entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
3495 TclGetString(targetLabel));
3496 jumpTarget = (BasicBlock*)Tcl_GetHashValue(entry);
3497 result = StackCheckBasicBlock(assemEnvPtr, jumpTarget,
3498 blockPtr, stackDepth);
3499 }
3500 }
3501
3502 return result;
3503 }
3504
3505 /*
3506 *-----------------------------------------------------------------------------
3507 *
3508 * StackCheckExit --
3509 *
3510 * Makes sure that the net stack effect of an entire assembly language
3511 * script is to push 1 result.
3512 *
3513 * Results:
3514 * Returns a standard Tcl result, with an error message in the
3515 * interpreter result if the stack is wrong.
3516 *
3517 * Side effects:
3518 * If the assembly code had a net stack effect of zero, emits code to the
3519 * concluding block to push a null result. In any case, updates the stack
3520 * depth in the compile environment to reflect the net effect of the
3521 * assembly code.
3522 *
3523 *-----------------------------------------------------------------------------
3524 */
3525
3526 static int
3527 StackCheckExit(
3528 AssemblyEnv* assemEnvPtr) /* Assembly environment */
3529 {
3530 CompileEnv* envPtr = assemEnvPtr->envPtr;
3531 /* Compilation environment */
3532 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
3533 /* Tcl interpreter */
3534 int depth; /* Net stack effect */
3535 int litIndex; /* Index in the literal pool of the empty
3536 * string */
3537 BasicBlock* curr_bb = assemEnvPtr->curr_bb;
3538 /* Final basic block in the assembly */
3539
3540 /*
3541 * Don't perform these checks if execution doesn't reach the exit (either
3542 * because of an infinite loop or because the only return is from the
3543 * middle.
3544 */
3545
3546 if (curr_bb->flags & BB_VISITED) {
3547 /*
3548 * Exit with no operands; push an empty one.
3549 */
3550
3551 depth = curr_bb->finalStackDepth + curr_bb->initialStackDepth;
3552 if (depth == 0) {
3553 /*
3554 * Emit a 'push' of the empty literal.
3555 */
3556
3557 litIndex = TclRegisterNewLiteral(envPtr, "", 0);
3558
3559 /*
3560 * Assumes that 'push' is at slot 0 in TalInstructionTable.
3561 */
3562
3563 BBEmitInst1or4(assemEnvPtr, 0, litIndex, 0);
3564 ++depth;
3565 }
3566
3567 /*
3568 * Exit with unbalanced stack.
3569 */
3570
3571 if (depth != 1) {
3572 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
3573 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
3574 "stack is unbalanced on exit from the code (depth=%d)",
3575 depth));
3576 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADSTACK", (char *)NULL);
3577 }
3578 return TCL_ERROR;
3579 }
3580
3581 /*
3582 * Record stack usage.
3583 */
3584
3585 envPtr->currStackDepth += depth;
3586 }
3587
3588 return TCL_OK;
3589 }
3590
3591 /*
3592 *-----------------------------------------------------------------------------
3593 *
3594 * ProcessCatches --
3595 *
3596 * First pass of 'catch' processing.
3597 *
3598 * Results:
3599 * Returns a standard Tcl result, with an appropriate error message if
3600 * the result is TCL_ERROR.
3601 *
3602 * Side effects:
3603 * Labels all basic blocks with their enclosing catches.
3604 *
3605 *-----------------------------------------------------------------------------
3606 */
3607
3608 static int
3609 ProcessCatches(
3610 AssemblyEnv* assemEnvPtr) /* Assembly environment */
3611 {
3612 BasicBlock* blockPtr; /* Pointer to a basic block */
3613
3614 /*
3615 * Clear the catch state of all basic blocks.
3616 */
3617
3618 for (blockPtr = assemEnvPtr->head_bb;
3619 blockPtr != NULL;
3620 blockPtr = blockPtr->successor1) {
3621 blockPtr->catchState = BBCS_UNKNOWN;
3622 blockPtr->enclosingCatch = NULL;
3623 }
3624
3625 /*
3626 * Start the check recursively from the first basic block, which is
3627 * outside any exception context
3628 */
3629
3630 if (ProcessCatchesInBasicBlock(assemEnvPtr, assemEnvPtr->head_bb,
3631 NULL, BBCS_NONE, 0) != TCL_OK) {
3632 return TCL_ERROR;
3633 }
3634
3635 /*
3636 * Check for unclosed catch on exit.
3637 */
3638
3639 if (CheckForUnclosedCatches(assemEnvPtr) != TCL_OK) {
3640 return TCL_ERROR;
3641 }
3642
3643 /*
3644 * Now there's enough information to build the exception ranges.
3645 */
3646
3647 if (BuildExceptionRanges(assemEnvPtr) != TCL_OK) {
3648 return TCL_ERROR;
3649 }
3650
3651 /*
3652 * Finally, restore any exception ranges from embedded scripts.
3653 */
3654
3655 RestoreEmbeddedExceptionRanges(assemEnvPtr);
3656 return TCL_OK;
3657 }
3658
3659 /*
3660 *-----------------------------------------------------------------------------
3661 *
3662 * ProcessCatchesInBasicBlock --
3663 *
3664 * First-pass catch processing for one basic block.
3665 *
3666 * Results:
3667 * Returns a standard Tcl result, with error message in the interpreter
3668 * result if an error occurs.
3669 *
3670 * This procedure checks consistency of the exception context through the
3671 * assembler program, and records the enclosing 'catch' for every basic block.
3672 *
3673 *-----------------------------------------------------------------------------
3674 */
3675
3676 static int
3677 ProcessCatchesInBasicBlock(
3678 AssemblyEnv* assemEnvPtr, /* Assembly environment */
3679 BasicBlock* bbPtr, /* Basic block being processed */
3680 BasicBlock* enclosing, /* Start basic block of the enclosing catch */
3681 enum BasicBlockCatchState state,
3682 /* BBCS_NONE, BBCS_INCATCH, or BBCS_CAUGHT */
3683 int catchDepth) /* Depth of nesting of catches */
3684 {
3685 CompileEnv* envPtr = assemEnvPtr->envPtr;
3686 /* Compilation environment */
3687 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
3688 /* Tcl interpreter */
3689 int result; /* Return value from this procedure */
3690 BasicBlock* fallThruEnclosing;
3691 /* Enclosing catch if execution falls thru */
3692 enum BasicBlockCatchState fallThruState;
3693 /* Catch state of the successor block */
3694 BasicBlock* jumpEnclosing; /* Enclosing catch if execution goes to jump
3695 * target */
3696 enum BasicBlockCatchState jumpState;
3697 /* Catch state of the jump target */
3698 int changed = 0; /* Flag == 1 iff successor blocks need to be
3699 * checked because the state of this block has
3700 * changed. */
3701 BasicBlock* jumpTarget; /* Basic block where a jump goes */
3702 Tcl_HashSearch jtSearch; /* Hash search control for a jumptable */
3703 Tcl_HashEntry* jtEntry; /* Entry in a jumptable */
3704 Tcl_Obj* targetLabel; /* Target label from a jumptable */
3705 Tcl_HashEntry* entry; /* Entry from the label table */
3706
3707 /*
3708 * Update the state of the current block, checking for consistency. Set
3709 * 'changed' to 1 if the state changes and successor blocks need to be
3710 * rechecked.
3711 */
3712
3713 if (bbPtr->catchState == BBCS_UNKNOWN) {
3714 bbPtr->enclosingCatch = enclosing;
3715 } else if (bbPtr->enclosingCatch != enclosing) {
3716 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
3717 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3718 "execution reaches an instruction in inconsistent "
3719 "exception contexts", -1));
3720 Tcl_SetErrorLine(interp, bbPtr->startLine);
3721 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADCATCH", (char *)NULL);
3722 }
3723 return TCL_ERROR;
3724 }
3725 if (state > bbPtr->catchState) {
3726 bbPtr->catchState = state;
3727 changed = 1;
3728 }
3729
3730 /*
3731 * If this block has been visited before, and its state hasn't changed,
3732 * we're done with it for now.
3733 */
3734
3735 if (!changed) {
3736 return TCL_OK;
3737 }
3738 bbPtr->catchDepth = catchDepth;
3739
3740 /*
3741 * Determine enclosing catch and 'caught' state for the fallthrough and
3742 * the jump target. Default for both is the state of the current block.
3743 */
3744
3745 fallThruEnclosing = enclosing;
3746 fallThruState = state;
3747 jumpEnclosing = enclosing;
3748 jumpState = state;
3749
3750 /*
3751 * TODO: Make sure that the test cases include validating that a natural
3752 * loop can't include 'beginCatch' or 'endCatch'
3753 */
3754
3755 if (bbPtr->flags & BB_BEGINCATCH) {
3756 /*
3757 * If the block begins a catch, the state for the successor is 'in
3758 * catch'. The jump target is the exception exit, and the state of the
3759 * jump target is 'caught.'
3760 */
3761
3762 fallThruEnclosing = bbPtr;
3763 fallThruState = BBCS_INCATCH;
3764 jumpEnclosing = bbPtr;
3765 jumpState = BBCS_CAUGHT;
3766 ++catchDepth;
3767 }
3768
3769 if (bbPtr->flags & BB_ENDCATCH) {
3770 /*
3771 * If the block ends a catch, the state for the successor is whatever
3772 * the state was on entry to the catch.
3773 */
3774
3775 if (enclosing == NULL) {
3776 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
3777 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3778 "endCatch without a corresponding beginCatch", -1));
3779 Tcl_SetErrorLine(interp, bbPtr->startLine);
3780 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "BADENDCATCH", (char *)NULL);
3781 }
3782 return TCL_ERROR;
3783 }
3784 fallThruEnclosing = enclosing->enclosingCatch;
3785 fallThruState = enclosing->catchState;
3786 --catchDepth;
3787 }
3788
3789 /*
3790 * Visit any successor blocks with the appropriate exception context
3791 */
3792
3793 result = TCL_OK;
3794 if (bbPtr->flags & BB_FALLTHRU) {
3795 result = ProcessCatchesInBasicBlock(assemEnvPtr, bbPtr->successor1,
3796 fallThruEnclosing, fallThruState, catchDepth);
3797 }
3798 if (result == TCL_OK && bbPtr->jumpTarget != NULL) {
3799 entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
3800 TclGetString(bbPtr->jumpTarget));
3801 jumpTarget = (BasicBlock*)Tcl_GetHashValue(entry);
3802 result = ProcessCatchesInBasicBlock(assemEnvPtr, jumpTarget,
3803 jumpEnclosing, jumpState, catchDepth);
3804 }
3805
3806 /*
3807 * All blocks referenced in a jump table are successors.
3808 */
3809
3810 if (bbPtr->flags & BB_JUMPTABLE) {
3811 for (jtEntry = Tcl_FirstHashEntry(&bbPtr->jtPtr->hashTable,&jtSearch);
3812 result == TCL_OK && jtEntry != NULL;
3813 jtEntry = Tcl_NextHashEntry(&jtSearch)) {
3814 targetLabel = (Tcl_Obj*)Tcl_GetHashValue(jtEntry);
3815 entry = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
3816 TclGetString(targetLabel));
3817 jumpTarget = (BasicBlock*)Tcl_GetHashValue(entry);
3818 result = ProcessCatchesInBasicBlock(assemEnvPtr, jumpTarget,
3819 jumpEnclosing, jumpState, catchDepth);
3820 }
3821 }
3822
3823 return result;
3824 }
3825
3826 /*
3827 *-----------------------------------------------------------------------------
3828 *
3829 * CheckForUnclosedCatches --
3830 *
3831 * Checks that a sequence of assembly code has no unclosed catches on
3832 * exit.
3833 *
3834 * Results:
3835 * Returns a standard Tcl result, with an error message for unclosed
3836 * catches.
3837 *
3838 *-----------------------------------------------------------------------------
3839 */
3840
3841 static int
3842 CheckForUnclosedCatches(
3843 AssemblyEnv* assemEnvPtr) /* Assembly environment */
3844 {
3845 CompileEnv* envPtr = assemEnvPtr->envPtr;
3846 /* Compilation environment */
3847 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
3848 /* Tcl interpreter */
3849
3850 if (assemEnvPtr->curr_bb->catchState >= BBCS_INCATCH) {
3851 if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
3852 Tcl_SetObjResult(interp, Tcl_NewStringObj(
3853 "catch still active on exit from assembly code", -1));
3854 Tcl_SetErrorLine(interp,
3855 assemEnvPtr->curr_bb->enclosingCatch->startLine);
3856 Tcl_SetErrorCode(interp, "TCL", "ASSEM", "UNCLOSEDCATCH", (char *)NULL);
3857 }
3858 return TCL_ERROR;
3859 }
3860 return TCL_OK;
3861 }
3862
3863 /*
3864 *-----------------------------------------------------------------------------
3865 *
3866 * BuildExceptionRanges --
3867 *
3868 * Walks through the assembly code and builds exception ranges for the
3869 * catches embedded therein.
3870 *
3871 * Results:
3872 * Returns a standard Tcl result with an error message in the interpreter
3873 * if anything is unsuccessful.
3874 *
3875 * Side effects:
3876 * Each contiguous block of code with a given catch exit is assigned an
3877 * exception range at the appropriate level.
3878 * Exception ranges in embedded blocks have their levels corrected and
3879 * collated into the table.
3880 * Blocks that end with 'beginCatch' are associated with the innermost
3881 * exception range of the following block.
3882 *
3883 *-----------------------------------------------------------------------------
3884 */
3885
3886 static int
3887 BuildExceptionRanges(
3888 AssemblyEnv* assemEnvPtr) /* Assembly environment */
3889 {
3890 CompileEnv* envPtr = assemEnvPtr->envPtr;
3891 /* Compilation environment */
3892 BasicBlock* bbPtr; /* Current basic block */
3893 BasicBlock* prevPtr = NULL; /* Previous basic block */
3894 int catchDepth = 0; /* Current catch depth */
3895 int maxCatchDepth = 0; /* Maximum catch depth in the program */
3896 BasicBlock** catches; /* Stack of catches in progress */
3897 int* catchIndices; /* Indices of the exception ranges of catches
3898 * in progress */
3899 int i;
3900
3901 /*
3902 * Determine the max catch depth for the entire assembly script
3903 * (excluding embedded eval's and expr's, which will be handled later).
3904 */
3905
3906 for (bbPtr=assemEnvPtr->head_bb; bbPtr != NULL; bbPtr=bbPtr->successor1) {
3907 if (bbPtr->catchDepth > maxCatchDepth) {
3908 maxCatchDepth = bbPtr->catchDepth;
3909 }
3910 }
3911
3912 /*
3913 * Allocate memory for a stack of active catches.
3914 */
3915
3916 catches = (BasicBlock**)ckalloc(maxCatchDepth * sizeof(BasicBlock*));
3917 catchIndices = (int *)ckalloc(maxCatchDepth * sizeof(int));
3918 for (i = 0; i < maxCatchDepth; ++i) {
3919 catches[i] = NULL;
3920 catchIndices[i] = -1;
3921 }
3922
3923 /*
3924 * Walk through the basic blocks and manage exception ranges.
3925 */
3926
3927 for (bbPtr=assemEnvPtr->head_bb; bbPtr != NULL; bbPtr=bbPtr->successor1) {
3928 UnstackExpiredCatches(envPtr, bbPtr, catchDepth, catches,
3929 catchIndices);
3930 LookForFreshCatches(bbPtr, catches);
3931 StackFreshCatches(assemEnvPtr, bbPtr, catchDepth, catches,
3932 catchIndices);
3933
3934 /*
3935 * If the last block was a 'begin catch', fill in the exception range.
3936 */
3937
3938 catchDepth = bbPtr->catchDepth;
3939 if (prevPtr != NULL && (prevPtr->flags & BB_BEGINCATCH)) {
3940 TclStoreInt4AtPtr(catchIndices[catchDepth-1],
3941 envPtr->codeStart + bbPtr->startOffset - 4);
3942 }
3943
3944 prevPtr = bbPtr;
3945 }
3946
3947 /* Make sure that all catches are closed */
3948
3949 if (catchDepth != 0) {
3950 Tcl_Panic("unclosed catch at end of code in "
3951 "tclAssembly.c:BuildExceptionRanges, can't happen");
3952 }
3953
3954 /* Free temp storage */
3955
3956 ckfree(catchIndices);
3957 ckfree(catches);
3958
3959 return TCL_OK;
3960 }
3961
3962 /*
3963 *-----------------------------------------------------------------------------
3964 *
3965 * UnstackExpiredCatches --
3966 *
3967 * Unstacks and closes the exception ranges for any catch contexts that
3968 * were active in the previous basic block but are inactive in the
3969 * current one.
3970 *
3971 *-----------------------------------------------------------------------------
3972 */
3973
3974 static void
3975 UnstackExpiredCatches(
3976 CompileEnv* envPtr, /* Compilation environment */
3977 BasicBlock* bbPtr, /* Basic block being processed */
3978 int catchDepth, /* Depth of nesting of catches prior to entry
3979 * to this block */
3980 BasicBlock** catches, /* Array of catch contexts */
3981 int* catchIndices) /* Indices of the exception ranges
3982 * corresponding to the catch contexts */
3983 {
3984 ExceptionRange* range; /* Exception range for a specific catch */
3985 BasicBlock* block; /* Catch block being examined */
3986 BasicBlockCatchState catchState;
3987 /* State of the code relative to the catch
3988 * block being examined ("in catch" or
3989 * "caught"). */
3990
3991 /*
3992 * Unstack any catches that are deeper than the nesting level of the basic
3993 * block being entered.
3994 */
3995
3996 while (catchDepth > bbPtr->catchDepth) {
3997 --catchDepth;
3998 if (catches[catchDepth] != NULL) {
3999 range = envPtr->exceptArrayPtr + catchIndices[catchDepth];
4000 range->numCodeBytes = bbPtr->startOffset - range->codeOffset;
4001 catches[catchDepth] = NULL;
4002 catchIndices[catchDepth] = -1;
4003 }
4004 }
4005
4006 /*
4007 * Unstack any catches that don't match the basic block being entered,
4008 * either because they are no longer part of the context, or because the
4009 * context has changed from INCATCH to CAUGHT.
4010 */
4011
4012 catchState = bbPtr->catchState;
4013 block = bbPtr->enclosingCatch;
4014 while (catchDepth > 0) {
4015 --catchDepth;
4016 if (catches[catchDepth] != NULL) {
4017 if (catches[catchDepth] != block || catchState >= BBCS_CAUGHT) {
4018 range = envPtr->exceptArrayPtr + catchIndices[catchDepth];
4019 range->numCodeBytes = bbPtr->startOffset - range->codeOffset;
4020 catches[catchDepth] = NULL;
4021 catchIndices[catchDepth] = -1;
4022 }
4023 catchState = block->catchState;
4024 block = block->enclosingCatch;
4025 }
4026 }
4027 }
4028
4029 /*
4030 *-----------------------------------------------------------------------------
4031 *
4032 * LookForFreshCatches --
4033 *
4034 * Determines whether a basic block being entered needs any exception
4035 * ranges that are not already stacked.
4036 *
4037 * Does not create the ranges: this procedure iterates from the innermost
4038 * catch outward, but exception ranges must be created from the outermost
4039 * catch inward.
4040 *
4041 *-----------------------------------------------------------------------------
4042 */
4043
4044 static void
4045 LookForFreshCatches(
4046 BasicBlock* bbPtr, /* Basic block being entered */
4047 BasicBlock** catches) /* Array of catch contexts that are already
4048 * entered */
4049 {
4050 BasicBlockCatchState catchState;
4051 /* State ("in catch" or "caught") of the
4052 * current catch. */
4053 BasicBlock* block; /* Current enclosing catch */
4054 int catchDepth; /* Nesting depth of the current catch */
4055
4056 catchState = bbPtr->catchState;
4057 block = bbPtr->enclosingCatch;
4058 catchDepth = bbPtr->catchDepth;
4059 while (catchDepth > 0) {
4060 --catchDepth;
4061 if (catches[catchDepth] != block && catchState < BBCS_CAUGHT) {
4062 catches[catchDepth] = block;
4063 }
4064 catchState = block->catchState;
4065 block = block->enclosingCatch;
4066 }
4067 }
4068
4069 /*
4070 *-----------------------------------------------------------------------------
4071 *
4072 * StackFreshCatches --
4073 *
4074 * Make ExceptionRange records for any catches that are in the basic
4075 * block being entered and were not in the previous basic block.
4076 *
4077 *-----------------------------------------------------------------------------
4078 */
4079
4080 static void
4081 StackFreshCatches(
4082 AssemblyEnv* assemEnvPtr, /* Assembly environment */
4083 BasicBlock* bbPtr, /* Basic block being processed */
4084 int catchDepth, /* Depth of nesting of catches prior to entry
4085 * to this block */
4086 BasicBlock** catches, /* Array of catch contexts */
4087 int* catchIndices) /* Indices of the exception ranges
4088 * corresponding to the catch contexts */
4089 {
4090 CompileEnv* envPtr = assemEnvPtr->envPtr;
4091 /* Compilation environment */
4092 ExceptionRange* range; /* Exception range for a specific catch */
4093 BasicBlock* block; /* Catch block being examined */
4094 BasicBlock* errorExit; /* Error exit from the catch block */
4095 Tcl_HashEntry* entryPtr;
4096
4097 catchDepth = 0;
4098
4099 /*
4100 * Iterate through the enclosing catch blocks from the outside in,
4101 * looking for ones that don't have exception ranges (and are uncaught)
4102 */
4103
4104 for (catchDepth = 0; catchDepth < bbPtr->catchDepth; ++catchDepth) {
4105 if (catchIndices[catchDepth] == -1 && catches[catchDepth] != NULL) {
4106 /*
4107 * Create an exception range for a block that needs one.
4108 */
4109
4110 block = catches[catchDepth];
4111 catchIndices[catchDepth] =
4112 TclCreateExceptRange(CATCH_EXCEPTION_RANGE, envPtr);
4113 range = envPtr->exceptArrayPtr + catchIndices[catchDepth];
4114 range->nestingLevel = envPtr->exceptDepth + catchDepth;
4115 envPtr->maxExceptDepth =
4116 TclMax(range->nestingLevel + 1, envPtr->maxExceptDepth);
4117 range->codeOffset = bbPtr->startOffset;
4118
4119 entryPtr = Tcl_FindHashEntry(&assemEnvPtr->labelHash,
4120 TclGetString(block->jumpTarget));
4121 if (entryPtr == NULL) {
4122 Tcl_Panic("undefined label in tclAssembly.c:"
4123 "BuildExceptionRanges, can't happen");
4124 }
4125
4126 errorExit = (BasicBlock*)Tcl_GetHashValue(entryPtr);
4127 range->catchOffset = errorExit->startOffset;
4128 }
4129 }
4130 }
4131
4132 /*
4133 *-----------------------------------------------------------------------------
4134 *
4135 * RestoreEmbeddedExceptionRanges --
4136 *
4137 * Processes an assembly script, replacing any exception ranges that
4138 * were present in embedded code.
4139 *
4140 *-----------------------------------------------------------------------------
4141 */
4142
4143 static void
4144 RestoreEmbeddedExceptionRanges(
4145 AssemblyEnv* assemEnvPtr) /* Assembly environment */
4146 {
4147 CompileEnv* envPtr = assemEnvPtr->envPtr;
4148 /* Compilation environment */
4149 BasicBlock* bbPtr; /* Current basic block */
4150 int rangeBase; /* Base of the foreign exception ranges when
4151 * they are reinstalled */
4152 int rangeIndex; /* Index of the current foreign exception
4153 * range as reinstalled */
4154 ExceptionRange* range; /* Current foreign exception range */
4155 unsigned char opcode; /* Current instruction's opcode */
4156 int catchIndex; /* Index of the exception range to which the
4157 * current instruction refers */
4158 int i;
4159
4160 /*
4161 * Walk the basic blocks looking for exceptions in embedded scripts.
4162 */
4163
4164 for (bbPtr = assemEnvPtr->head_bb;
4165 bbPtr != NULL;
4166 bbPtr = bbPtr->successor1) {
4167 if (bbPtr->foreignExceptionCount != 0) {
4168 /*
4169 * Reinstall the embedded exceptions and track their nesting level
4170 */
4171
4172 rangeBase = envPtr->exceptArrayNext;
4173 for (i = 0; i < bbPtr->foreignExceptionCount; ++i) {
4174 range = bbPtr->foreignExceptions + i;
4175 rangeIndex = TclCreateExceptRange(range->type, envPtr);
4176 range->nestingLevel += envPtr->exceptDepth + bbPtr->catchDepth;
4177 memcpy(envPtr->exceptArrayPtr + rangeIndex, range,
4178 sizeof(ExceptionRange));
4179 if (range->nestingLevel >= envPtr->maxExceptDepth) {
4180 envPtr->maxExceptDepth = range->nestingLevel + 1;
4181 }
4182 }
4183
4184 /*
4185 * Walk through the bytecode of the basic block, and relocate
4186 * INST_BEGIN_CATCH4 instructions to the new locations
4187 */
4188
4189 i = bbPtr->startOffset;
4190 while (i < bbPtr->successor1->startOffset) {
4191 opcode = envPtr->codeStart[i];
4192 if (opcode == INST_BEGIN_CATCH4) {
4193 catchIndex = TclGetUInt4AtPtr(envPtr->codeStart + i + 1);
4194 if (catchIndex >= bbPtr->foreignExceptionBase
4195 && catchIndex < (bbPtr->foreignExceptionBase +
4196 bbPtr->foreignExceptionCount)) {
4197 catchIndex -= bbPtr->foreignExceptionBase;
4198 catchIndex += rangeBase;
4199 TclStoreInt4AtPtr(catchIndex, envPtr->codeStart+i+1);
4200 }
4201 }
4202 i += tclInstructionTable[opcode].numBytes;
4203 }
4204 }
4205 }
4206 }
4207
4208 /*
4209 *-----------------------------------------------------------------------------
4210 *
4211 * ResetVisitedBasicBlocks --
4212 *
4213 * Turns off the 'visited' flag in all basic blocks at the conclusion
4214 * of a pass.
4215 *
4216 *-----------------------------------------------------------------------------
4217 */
4218
4219 static void
4220 ResetVisitedBasicBlocks(
4221 AssemblyEnv* assemEnvPtr) /* Assembly environment */
4222 {
4223 BasicBlock* block;
4224
4225 for (block = assemEnvPtr->head_bb; block != NULL;
4226 block = block->successor1) {
4227 block->flags &= ~BB_VISITED;
4228 }
4229 }
4230
4231 /*
4232 *-----------------------------------------------------------------------------
4233 *
4234 * AddBasicBlockRangeToErrorInfo --
4235 *
4236 * Updates the error info of the Tcl interpreter to show a given basic
4237 * block in the code.
4238 *
4239 * This procedure is used to label the callstack with source location
4240 * information when reporting an error in stack checking.
4241 *
4242 *-----------------------------------------------------------------------------
4243 */
4244
4245 static void
4246 AddBasicBlockRangeToErrorInfo(
4247 AssemblyEnv* assemEnvPtr, /* Assembly environment */
4248 BasicBlock* bbPtr) /* Basic block in which the error is found */
4249 {
4250 CompileEnv* envPtr = assemEnvPtr->envPtr;
4251 /* Compilation environment */
4252 Tcl_Interp* interp = (Tcl_Interp*) envPtr->iPtr;
4253 /* Tcl interpreter */
4254 Tcl_Obj* lineNo; /* Line number in the source */
4255
4256 Tcl_AddErrorInfo(interp, "\n in assembly code between lines ");
4257 TclNewIntObj(lineNo, bbPtr->startLine);
4258 Tcl_IncrRefCount(lineNo);
4259 Tcl_AppendObjToErrorInfo(interp, lineNo);
4260 Tcl_AddErrorInfo(interp, " and ");
4261 if (bbPtr->successor1 != NULL) {
4262 Tcl_SetIntObj(lineNo, bbPtr->successor1->startLine);
4263 Tcl_AppendObjToErrorInfo(interp, lineNo);
4264 } else {
4265 Tcl_AddErrorInfo(interp, "end of assembly code");
4266 }
4267 Tcl_DecrRefCount(lineNo);
4268 }
4269
4270 /*
4271 *-----------------------------------------------------------------------------
4272 *
4273 * DupAssembleCodeInternalRep --
4274 *
4275 * Part of the Tcl object type implementation for Tcl assembly language
4276 * bytecode. We do not copy the bytecode internalrep. Instead, we return
4277 * without setting copyPtr->typePtr, so the copy is a plain string copy
4278 * of the assembly source, and if it is to be used as a compiled
4279 * expression, it will need to be reprocessed.
4280 *
4281 * This makes sense, because with Tcl's copy-on-write practices, the
4282 * usual (only?) time Tcl_DuplicateObj() will be called is when the copy
4283 * is about to be modified, which would invalidate any copied bytecode
4284 * anyway. The only reason it might make sense to copy the bytecode is if
4285 * we had some modifying routines that operated directly on the internalrep,
4286 * as we do for lists and dicts.
4287 *
4288 * Results:
4289 * None.
4290 *
4291 * Side effects:
4292 * None.
4293 *
4294 *-----------------------------------------------------------------------------
4295 */
4296
4297 static void
4298 DupAssembleCodeInternalRep(
4299 Tcl_Obj *srcPtr,
4300 Tcl_Obj *copyPtr)
4301 {
4302 (void)srcPtr;
4303 (void)copyPtr;
4304
4305 return;
4306 }
4307
4308 /*
4309 *-----------------------------------------------------------------------------
4310 *
4311 * FreeAssembleCodeInternalRep --
4312 *
4313 * Part of the Tcl object type implementation for Tcl expression
4314 * bytecode. Frees the storage allocated to hold the internal rep, unless
4315 * ref counts indicate bytecode execution is still in progress.
4316 *
4317 * Results:
4318 * None.
4319 *
4320 * Side effects:
4321 * May free allocated memory. Leaves objPtr untyped.
4322 *
4323 *-----------------------------------------------------------------------------
4324 */
4325
4326 static void
4327 FreeAssembleCodeInternalRep(
4328 Tcl_Obj *objPtr)
4329 {
4330 ByteCode *codePtr = (ByteCode *)objPtr->internalRep.twoPtrValue.ptr1;
4331
4332 if (codePtr->refCount-- <= 1) {
4333 TclCleanupByteCode(codePtr);
4334 }
4335 objPtr->typePtr = NULL;
4336 }
4337
4338 /*
4339 * Local Variables:
4340 * mode: c
4341 * c-basic-offset: 4
4342 * fill-column: 78
4343 * End:
4344 */