目录
正在加载目录…
正在阅读专栏 Essentials of Compilation 专栏 第 10 篇 · 共 13 篇 · 77%

Essentials of Compilation:动态类型

发布于 2026-09-16 22:17 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 9,504 · 预计阅读 20 分钟 👁 21 次阅读

Essentials of Compilation:动态类型

本章把 dynamically typed LangDyn 编译为带显式 Any、Inject、Project 和 runtime tag 的 LangAny。

TL;DR

  • Dynamic typing 允许同一个 expression 在不同 execution 中产生不同 type 的 value。
  • Runtime 用 tagged value 记录 value kind;本章从 64-bit value 的最低 3 bits 中借出 tag bits。
  • Inject 把 statically typed value 转换为 Any,Project 检查 tag 后恢复 flat type。
  • Tuple access、procedure application 和 primitive operation 的类型约束从 compile time 移到 runtime。
  • cast_insert 保证每个动态 expression 的 output 都是 Any,并在需要处插入 projections。

名词解释

名词含义本章对应物
dynamic typingvalue type 在 runtime 检查LangDyn
tagged valuevalue 与标识其 kind 的 tag 的组合Tagged(value, tag)
Any可以承载任意 flat value 的 static typeLangAny
inject把具体 type 包装成 AnyInject e Integer
project从 Any 检查并取出具体 typeProject e Integer
tag bits编码 value kind 的 bit pattern001、100、010 等

目录

章节说明
Dynamic Typingdynamic language 的 behavior
The LangDyn Languageuntyped syntax 与 runtime interpreter
Representation of Tagged Values64-bit tagged representation
The LangAny LanguageAny、inject、project 与 any-vector operation
Cast Insertion从 LangDyn 插入 runtime casts

Dynamic Typing

本章学习如何编译 dynamically typed 的 LangDyn,它是 Racket 的一个 subset。前几章研究 statically typed language;dynamic typing 的区别是:某个 expression 每次执行都可能产生不同 type 的 value。

racket
(not (if (eq? (read) 1) #f 0))

如果 input 是 1,if 产生 Boolean #f;否则产生 integer 0。因此同一个 if expression 可能产生两种 type。

允许 expression 产生不同 value kind 的 language 被称为 polymorphic。Dynamic language 的另一个特征是 primitive operation 经常定义为可作用于多种 value。例如 Racket 的 not 对任意 value 都产生结果:给定 #f 返回 #t,其他 value 返回 #f。

即使 primitive operation 限制 input type,这个限制也在 runtime 而非 compilation 期间执行。例如:

racket
(vector-ref #t 0)

会产生 runtime error,因为第一个 argument 必须是 tuple,而不是 Boolean。

The LangDyn Language

LangDyn 的 syntax 包含 function application、lambda、type predicate 和 top-level function definition:

text
Exp ::= (Exp Exp...)
      | (lambda (Var...) Exp)
      | (boolean? Exp) | (integer? Exp)
      | (vector? Exp) | (procedure? Exp) | (void? Exp)
Def ::= (define (Var Var...) Exp)
LangDyn ::= Def... Exp

它没有 type checker,因为 type 只在 runtime 检查。

Interpreter 不会像 LangVar interpreter 那样遇到 integer 就直接返回 n,而是创建结合 underlying value 和 value kind 的 tagged value:

racket
(struct Tagged (value tag) #:transparent)

Racket 版 tags 为 Integer、Boolean、Void、Vector 和 Procedure。Tag 与 type closely related,但 tag 不一定包含 type 的全部信息;例如 (Vector Any Any) 和 (Vector Integer Boolean) 都只使用 Vector tag。

Tuple access 使用 check-tag 确认第一个 argument 是 Vector、第二个是 Integer;如果 tag 不匹配或 index 超出 vector length,就抛出 trapped-error。按照前面章节的约定,compiled code 也必须以 return code 255 signal 该 error。

Dynamic interpreter 的核心规则是:

racket
[(Var x) (dict-ref env x)]
[(Int n) (Tagged n 'Integer)]
[(Bool b) (Tagged b 'Boolean)]
[(Lambda xs rt body)
 (Tagged `(function ,xs ,body ,env) 'Procedure)]
[(Prim 'vector es)
 (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]

if 的 condition 只需按 dynamic semantics 解释;eq? 可以处理同 tag 的 value;function application 先确认 callee tag 是 Procedure,再确认 arity 匹配。

Racket 版 interpreter 的关键 runtime checks 可以展开为:

racket
(define ((interp-Ldyn-exp env) ast)
  (define recur (interp-Ldyn-exp env))
  (match ast
    [(Var x) (dict-ref env x)]
    [(Int n) (Tagged n 'Integer)]
    [(Bool b) (Tagged b 'Boolean)]
    [(Lambda xs rt body)
     (Tagged `(function ,xs ,body ,env) 'Procedure)]
    [(Prim 'vector es)
     (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
    [(Prim 'vector-ref (list e1 e2))
     (define vec (recur e1))
     (define i (recur e2))
     (check-tag vec 'Vector ast)
     (check-tag i 'Integer ast)
     (unless (< (Tagged-value i)
                (vector-length (Tagged-value vec)))
       (error 'trapped-error "index ~a too big" (Tagged-value i)))
     (vector-ref (Tagged-value vec) (Tagged-value i))]
    [(Prim 'vector-set! (list e1 e2 e3))
     (define vec (recur e1))
     (define i (recur e2))
     (define arg (recur e3))
     (check-tag vec 'Vector ast)
     (check-tag i 'Integer ast)
     (unless (< (Tagged-value i)
                (vector-length (Tagged-value vec)))
       (error 'trapped-error "index ~a too big" (Tagged-value i)))
     (vector-set! (Tagged-value vec) (Tagged-value i) arg)
     (Tagged (void) 'Void)]
    [(If q t f)
     (match (Tagged-value (recur q))
       [#f (recur f)]
       [else (recur t)])]
    [(Apply f es)
     (define new-f (recur f))
     (define args (map recur es))
     (check-tag new-f 'Procedure ast)
     (match (Tagged-value new-f)
       [`(function ,xs ,body ,lam-env)
        (unless (= (length xs) (length args))
          (error 'trapped-error "arity mismatch"))
        ((interp-Ldyn-exp (append (map cons xs args) lam-env)) body)])]))

这里 vector-set! 的返回值也必须重新包装为 Tagged 的 Void;不能把底层 Racket 的 #<void> 当成未标记 value 继续流入 dynamic program。vector-ref 的返回值是 vector 中已经 tagged 的 element,因此不应再次套一层 tag。if 只把 tagged #f 视为 false,其他 tagged value 都进入 then branch。

Interpreter 使用下面这些 auxiliary function 统一完成 operator tag contract 与错误检查:

racket
(define (op-tags op)
  (match op
    ['+ '((Integer Integer))]
    ['- '((Integer Integer) (Integer))]
    ['read '(())]
    ['not '((Boolean))]
    ['< '((Integer Integer))]
    ['<= '((Integer Integer))]
    ['> '((Integer Integer))]
    ['>= '((Integer Integer))]
    ['vector-length '((Vector))]))

(define type-predicates
  (set 'boolean? 'integer? 'vector? 'procedure? 'void?))

(define (tag-value v)
  (cond [(boolean? v) (Tagged v 'Boolean)]
        [(fixnum? v) (Tagged v 'Integer)]
        [(procedure? v) (Tagged v 'Procedure)]
        [(vector? v) (Tagged v 'Vector)]
        [(void? v) (Tagged v 'Void)]
        [else (error 'tag-value "unidentified value ~a" v)]))

(define (check-tag val expected ast)
  (define tag (Tagged-tag val))
  (unless (eq? tag expected)
    (error 'trapped-error
           "expected ~a, not ~a\\nin ~v"
           expected tag ast)))

op-tags 描述普通 primitive operation 接受的 tag sequence;interpreter 在执行 operation 前先比较 argument tags,再调用底层 operation,最后用 tag-value 把结果重新包装。Type predicate 是例外:它们接受任意一个 tagged value,并返回新的 Boolean tagged value。check-tag 的 ast 参数用于在错误信息中保留触发失败的 source expression。

Representation of Tagged Values

要把 LangDyn 编译到 x86,必须在 bit level 决定 tagged value 的表示。因为 LangDyn 几乎每个 operation 都要操作 tagged value,representation 必须高效。所有 value 都是 64 bits,因此借用最右侧 3 bits 编码 tag:

text
Integer   = 001
Boolean   = 100
Vector    = 010
Procedure = 011
Void      = 101

代价是 integer 范围缩小到 -2^60 到 2^60-1。Tuple 和 procedure 是 address,而 address 按 8-byte 对齐,因此最右 3 bits 原本总是 000;覆盖它们不会丢失信息,只需清零 tag bits 就能恢复原 address。

The LangAny Language

为了让 tagged value 成为 first-class entity,为它定义 type Any,并定义创建、使用 tagged value 的 Inject 和 Project operation,得到 statically typed 的 LangAny intermediate language。

text
Type ::= Any
FType ::= Integer | Boolean | Void
       | (Vector Any...)
       | (Any... -> Any)
Exp ::= Inject(Exp, FType)
      | Project(Exp, FType)
      | any-vector-length(Exp)
      | any-vector-ref(Exp, Exp)
      | any-vector-set!(Exp, Exp, Exp)
      | boolean?(Exp) | integer?(Exp) | vector?(Exp)
      | procedure?(Exp) | void?(Exp)

Inject(e,T) 把 type 为 T 的 expression 转换为 tagged Any value。Project(e,T) 把 tagged value 转换为 T;如果 tag 不匹配,则停止 program。T 只能是 flat type,这简化了 implementation,也符合编译 LangDyn 的需要。

any-vector-length、any-vector-ref 和 any-vector-set! 让 tuple operation 可以作用于 Any;它们还允许 index 是任意 expression,而不再局限于 literal integer。Type predicates 要求 argument type 是 Any,根据 tag 返回 Boolean。

Cast Insertion

cast_insert pass 从 LangDyn 编译到 LangAny。它的重要 invariant 是:给定 LangDyn program 中任意 subexpression e,都会产生一个 type 为 Any 的 LangAny expression e'。

Boolean literal 必须 inject:

text
#t
  ⇒ (inject #t Boolean)

Addition 的 arguments 是 Any,因此先 project 为 Integer,完成 addition 后再 inject 回 Any:

text
(+ e1 e2)
  ⇒ (inject
       (+ (project e1' Integer)
          (project e2' Integer))
       Integer)

Lambda 的 parameters 和 return type 统一标为 Any;function application 先 project callee 为 (Any... -> Any),再传入已经转为 Any 的 arguments:

text
(e0 e1 ... en)
  ⇒ ((project e0' (Any... -> Any)) e1' ... en')

Tuple access 使用 any-vector-ref,因为 tuple 本身是 Any、index 可能是 dynamic expression。if 和 eq? 需要额外处理 LangDyn 与 LangAny 的 behavior 差异:dynamic if 的 condition 不一定是 Boolean;当 eq? 的两个 argument type 不同,dynamic semantics 返回 #f,而不是直接 type error。

后续 compiler pass 会在 LangAny 上继续执行 closure conversion、allocation exposure、control-flow explicitation、instruction selection 和 register allocation,最终将 tag checks 降低为 x86 bit operation 与 conditional jump。

LangAny 的 Type Checking 与 Interpreter

LangAny 是 statically typed 的 intermediate language。Inject 只能从 flat type 注入到 Any;Project 只能从 Any 投影到 flat type。type checker 会检查 operand 的 type,并把结果 type 分别设为 Any 与目标 flat type。

flat type 包括 Integer、Boolean、Void、元素均为 Any 的 Vector,以及参数和返回值均为 Any 的 function type。any-vector-length 要求 Any,返回 Integer;any-vector-ref 要求 tuple 为 Any、index 为 Integer,返回 Any;any-vector-set! 返回 Void。boolean?、integer?、vector?、procedure?、void? 要求 Any,返回 Boolean。

interpreter 将 Inject 表示为 (tagged value tag)。Project 先比较 tag;若目标是 tuple,还检查 tuple length;若目标是 function,还检查 function arity。tag 或 shape 不匹配时报告错误。

下面是 LangAny type checker 的核心实现。Inject 的 source 和 Project 的 target 都必须是 flat-ty?;tuple primitive 与 type predicates 则分别检查 Any、Integer 等 operand type:

racket
(define type-check-Lany-class
  (class type-check-Llambda-class
    (super-new)
    (inherit check-type-equal?)

    (define/override (type-check-exp env)
      (lambda (e)
        (define recur (type-check-exp env))
        (match e
          [(Inject e1 ty)
           (unless (flat-ty? ty)
             (error 'type-check
                    "may only inject from flat type, not ~a" ty))
           (define-values (new-e1 e-ty) (recur e1))
           (check-type-equal? e-ty ty e)
           (values (Inject new-e1 ty) 'Any)]
          [(Project e1 ty)
           (unless (flat-ty? ty)
             (error 'type-check
                    "may only project to flat type, not ~a" ty))
           (define-values (new-e1 e-ty) (recur e1))
           (check-type-equal? e-ty 'Any e)
           (values (Project new-e1 ty) ty)]
          [(Prim 'any-vector-length (list e1))
           (define-values (e1^ t1) (recur e1))
           (check-type-equal? t1 'Any e)
           (values (Prim 'any-vector-length (list e1^)) 'Integer)]
          [(Prim 'any-vector-ref (list e1 e2))
           (define-values (e1^ t1) (recur e1))
           (define-values (e2^ t2) (recur e2))
           (check-type-equal? t1 'Any e)
           (check-type-equal? t2 'Integer e)
           (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
          [(Prim 'any-vector-set! (list e1 e2 e3))
           (define-values (e1^ t1) (recur e1))
           (define-values (e2^ t2) (recur e2))
           (define-values (e3^ t3) (recur e3))
           (check-type-equal? t1 'Any e)
           (check-type-equal? t2 'Integer e)
           (check-type-equal? t3 'Any e)
           (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
          [(Prim pred (list e1))
           #:when (set-member? (type-predicates) pred)
           (define-values (new-e1 e-ty) (recur e1))
           (check-type-equal? e-ty 'Any e)
           (values (Prim pred (list new-e1)) 'Boolean)]
          [(Prim 'eq? (list arg1 arg2))
           (define-values (e1 t1) (recur arg1))
           (define-values (e2 t2) (recur arg2))
           (match* (t1 t2)
             [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
             [(other wise) (check-type-equal? t1 t2 e)])
           (values (Prim 'eq? (list e1 e2)) 'Boolean)]
          [else ((super type-check-exp env) e)]))))

配套的 helper method 如下。flat-ty? 的 restrictions 保证 runtime tag check 只需检查一个 generic tag,并在需要时检查 tuple length 或 function arity,而不必递归检查任意深的 type:

racket
(define/override (operator-types)
  (append
   '((integer? . ((Any) . Boolean))
     (vector? . ((Any) . Boolean))
     (procedure? . ((Any) . Boolean))
     (void? . ((Any) . Boolean)))
   (super operator-types)))

(define/public (type-predicates)
  (set 'boolean? 'integer? 'vector? 'procedure? 'void?))

(define/public (flat-ty? ty)
  (match ty
    [(or `Integer `Boolean `Void) #t]
    [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
    [`(Vectorof Any) #t]
    [`(,ts ... -> ,rt)
     (and (eq? rt 'Any)
          (for/and ([t ts]) (eq? t 'Any)))]
    [else #f]))

LangAny interpreter 的关键部分把 injection 表示为 tagged value,并把 predicates、dynamic tuple operation 接到对应的 runtime operation:

racket
(define interp-Lany-class
  (class interp-Llambda-class
    (super-new)

    (define/override (interp-op op)
      (match op
        ['boolean? (match-lambda
                     [`(tagged ,v1 ,tg)
                      (equal? tg (any-tag 'Boolean))]
                     [else #f])]
        ['integer? (match-lambda
                     [`(tagged ,v1 ,tg)
                      (equal? tg (any-tag 'Integer))]
                     [else #f])]
        ['vector? (match-lambda
                   [`(tagged ,v1 ,tg)
                    (equal? tg (any-tag `(Vector Any)))]
                   [else #f])]
        ['procedure? (match-lambda
                      [`(tagged ,v1 ,tg)
                       (equal? tg (any-tag `(Any -> Any)))]
                      [else #f])]
        ['eq? (match-lambda*
               [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
                (and (eq? v1^ v2^) (equal? tg1 tg2))]
               [ls (apply (super interp-op op) ls)])]
        ['any-vector-ref
         (lambda (v i)
           (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
        ['any-vector-set!
         (lambda (v i a)
           (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
        ['any-vector-length
         (lambda (v)
           (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
        [else (super interp-op op)]))

    (define/override ((interp-exp env) e)
      (define recur (interp-exp env))
      (match e
        [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
        [(Project e ty2) (apply-project (recur e) ty2)]
        [else ((super interp-exp env) e)]))))

(define (interp-Lany p)
  (send (new interp-Lany-class) interp-program p))

apply-project 在 tag 相同后继续检查 tuple length 或 function arity:

racket
(define/public (apply-project v ty2)
  (define tag2 (any-tag ty2))
  (match v
    [(Tagged v1 tag1)
     (cond
       [(eq? tag1 tag2)
        (match ty2
          [`(Vector ,ts ...)
           (define l1 ((interp-op 'vector-length) v1))
           (if (eq? l1 (length ts))
               v1
               (error 'apply-project "vector length mismatch"))]
          [`(,ts ... -> ,rt)
           (match v1
             [`(function ,xs ,body ,env)
              (if (eq? (length xs) (length ts))
                  v1
                  (error 'apply-project "arity mismatch"))]
             [else (error 'apply-project "expected function")])]
          [else v1])]
       [else (error 'apply-project "tag mismatch")])]
    [else (error 'apply-project "expected tagged value, not ~a" v)]))

这也是 LangAny 中 flat type 限制的实际原因。Inject 的 source 必须是 flat type,Project 的 target 也必须是 flat type;允许的 tuple 形状是元素全部为 Any 的 Vector,允许的 function 形状是参数和返回值全部为 Any 的 function type。这样,runtime 只需检查一个通用 tag,再检查 tuple 的长度或 function 的 arity,不必在此阶段递归检查任意深的静态 type。

对于 Project e T,interpreter 的检查顺序可以明确写成:

text
v = evaluate(e)
若 v 不是 tagged value:报告错误
若 tag(v) != tagof(T):报告错误
若 T 是 Vector Any...:检查 length(value(v)) 与 T 的长度相同
若 T 是 (Any... -> Any):检查 arity(value(v)) 与 T 的参数数相同
否则:返回 value(v)

因此,(Project e (Vector Any Any)) 不仅要求 e 的 tag 是 Vector,还要求底层 tuple 恰好有两个 elements;(Project e (Any Integer -> Any)) 在 LangAny 中并不是合法的 flat target,因为它包含了非 Any 的参数 type。更具体的 tuple/function cast 会留给后续 gradual-typing 的 proxy 机制处理。

Cast Insertion 的完整规则

cast_insert 的 invariant 是:LangDyn 中每个 subexpression 都被翻译成 type 为 Any 的 LangAny expression。主要规则如下:

LangDynLangAny
#t / #f(inject #t Boolean) / (inject #f Boolean)
(+ e1 e2)把两个结果 project 为 Integer,相加后 inject 为 Integer
(lambda (x ...) e)参数和返回类型均标为 Any,结果 function 注入为 (Any ... -> Any)
(e0 e1 ... en)callee project 为 (Any ... -> Any),arguments 保持 Any
(vector-ref e1 e2)any-vector-ref e1' e2'
(vector-set! e1 e2 e3)any-vector-set! e1' e2' e3'
(if e1 e2 e3)与注入的 #f 比较;只有 tagged false 才走 else
(eq? e1 e2)对两个 Any tagged values 比较并注入 Boolean
(not e)将 e 与注入的 #f 比较,返回注入的 Boolean

这体现了 dynamic semantics 与 static LangAny 的差异:dynamic if 不要求 condition 本身是 Boolean,只有 false 才算 false;dynamic eq? 可以比较不同 runtime types,并在不相同的情况下返回 #f。

Reveal Casts

reveal_casts 把 Inject、Project 降为更底层的 primitive。新增 TagOf/tag-of-any 读取 tagged value 的 tag,ValueOf 读取底层 value,Exit 终止程序。

对于 Project e Integer 或 Project e Boolean:先保存 e',比较 tag-of-any 与目标 tag;匹配时 ValueOf,否则 Exit。对于 tuple,除 tag 外还要比较 tuple length;对于 function,还要比较 function arity。

text
Project(e, T) ↦
  let tmp = e'
    if tag-of-any(tmp) == tagof(T)
      value-of(tmp, T)
    else
      exit

Inject e T 降为 make-any(e', tagof(T))。type predicates 则使用 tag-of-any 与 eq? 检查对应 tag。

any-vector-ref、any-vector-set! 和 any-vector-length 还要进行 runtime bounds checking。以 read 为例,先确认 value 的 tag 是 tuple,再确认 index 小于 runtime tuple length;任何检查失败都执行 Exit。

Assignment Conversion 与 Closure Conversion

在 reveal_casts 之后,后续 pass 仍沿用前面章节的 assignment conversion 与 closure conversion,但需要认识 LangAny 的两个新特点:TagOf、ValueOf 和 Exit 是新增的 primitive,必须被递归转换;而 type 为 Any 的 variable 可能隐藏 tuple pointer,因而在 closure 或 function call 期间也必须遵守 GC root 的保存规则。

convert_assignments 应像处理普通 variable 一样处理 Any variable 的 boxing:如果变量在 lambda 中 free 且出现在 set! 左侧,就把它放入 heap tuple;对它的读取/写入分别变成 vector-ref/vector-set!。随后 convert_to_closures 把 lambda 转成 flat closure,并把 captured Any values 放入 closure tuple。Closure conversion 不改变 Any 的 tagged representation,只改变 function pointer 与 captured environment 的组织方式。

这几个 pass 的顺序不能任意交换:先 reveal_casts,才能把 cast failure 和 tagged-value access 显式化;再做 assignment/closure conversion,才能让新增的 primitive 和 captured values 进入统一的 heap/root-stack 处理;之后才进入 remove_complex_operands 与 explicate_control。LangCAny 的 control-flow 阶段因此可以把 Exit 作为不会正常返回的 tail 处理,并把 dynamic tuple operation 留给 instruction selection。

Remove Complex Operands 与 LangCAny

ValueOf、TagOf 和 Exit 都是 complex expressions,它们的 operand 需要先变为 atomic。explicate_control 的输出 LangCAny 保留 ValueOf,把 Exit 转换为 Tail;any-vector-ref 与 any-vector-set! 的 index 在此阶段是 arbitrary atom,而不是编译期常量。

Select Instructions

LangCAny 的 instruction selection 直接操作 tagged value 的低 3 bits:

  • make-any 对 integer/Boolean 先左移 3 bits,再与 tag 做 orq;pointer(tuple/function)地址已经按 8-byte 对齐,不需左移,只需 orq tag;
  • tag-of-any:andq $7,提取底部 3 bits;
  • ValueOf 对 integer/Boolean 执行 sarq $3;对 tuple/function 用 andq -8 清除底部 3 bits;
  • any-vector-length 清除 value tag,读取 tuple tag,再提取 bit 1–6;
  • any-vector-ref 清除 value tag,计算 (index + 1) * 8 offset,再读取 tuple element;any-vector-set! 类似。
asm
movq value, dst
salq $3, dst
orq $tag, dst

LangAny 的 x86 指令选择细节

make-any 对 integer 或 Boolean value 先左移 3 bits,再把 tag 合并进去;这是因为这两类 value 的 payload 需要避开最低三位:

asm
movq value, dst
salq $3, dst
orq  $tag, dst

tuple 和 procedure 不需要左移,因为它们的 address 已经按 8-byte 对齐,低三位本来就是零;这时只需把 tag orq 到 address 上。tag-of-any 则复制 tagged value 后执行 andq $7,保留最低三位。

ValueOf 要根据目标 type 是否为 pointer 选择不同操作。Integer/Boolean 使用 arithmetic right shift 恢复 payload:

asm
movq value, dst
sarq $3, dst

tuple/procedure 则用 -8 清除低三位:

asm
movq $-8, dst
andq value, dst

any-vector-length 先清除 value 的 tag 得到 tuple address,再读取 tuple tag;andq $126 保留 length 所在的 bit 1–6,最后 sarq $1 得到长度。动态 index 的 any-vector-ref 还要在 runtime 计算 (index + 1) * 8:

asm
movq $-8, %r11
andq value, %r11
movq index, %rax
addq $1, %rax
imulq $8, %rax
addq %rax, %r11
movq 0(%r11), dst

%r11 用来保存 tuple address,%rax 用来计算 offset;这两个 scratch register 的分工可以避免 address 与 offset 相互覆盖。any-vector-set! 使用相同的 address/offset 计算,但把 rhs 写入目标 element。

对应的 any-vector-length 和 any-vector-set! 可以展开为下面的形式。length 读取 tuple header 中编码的长度;set 则把同样的 (index + 1) * 8 offset 用于写入 element:

asm
# any-vector-length
movq $-8, %r11
andq value, %r11
movq 0(%r11), %r11
andq $126, %r11
sarq $1, %r11
movq %r11, dst
asm
# any-vector-set!
movq $-8, %r11
andq tuple-value, %r11
movq index, %rax
addq $1, %rax
imulq $8, %rax
addq %rax, %r11
movq rhs, 0(%r11)
movq $0, dst

这里的 0(%r11) 是 tuple header 或 element 的实际内存访问;set! 返回 Void,所以最后把零写入结果位置。tag check、index bounds check 和 failure path 由前面的 reveal_casts/runtime 逻辑保证。

Register Allocation for LangAny

Any value 可能包装一个 tuple,因此 type 为 Any 的 variable 也可能是 GC root:

  • 若 Any variable 在 function call 后仍 live,必须 spill;构建 interference graph 时让它与所有 registers interfere;
  • Any variable spill 到 root stack,而不是普通 procedure call stack。

root stack 还需区分三类值:普通 tuple pointer、指向 tuple 的 tagged value、非 tuple tagged value。因此 tagof 不使用 000,把它保留给 plain tuple pointer;只要底部 3 bits 非零,就知道这是 tagged value,可进一步区分 tuple(010)与其他类型。

动态类型编译流水线

mermaid
flowchart LR
  A[LangDyn] -->|shrink| B[LangDyn]
  B -->|uniquify| C[LangDyn]
  C -->|reveal_functions| D[LangDynFunRef]
  D -->|cast_insert| E[LangAny]
  E -->|reveal_casts| F[LangAny]
  F -->|assignment / closure conversion| G[LangAnyFunRef]
  G -->|limit / expose allocation / RCO| H[LangAnyAlloc]
  H -->|explicate_control| I[LangCAny]
  I -->|select instructions| J[LangXIndCallVar]
  J -->|liveness / allocation| K[LangXIndCall]
  K --> L[x86]

练习与实现要求

  1. 将 compiler 扩展到本章介绍的 LangAny:创建 5 个使用 Any、Inject、Project 等新 type 和 operations 的 programs,并与此前的 tests 一起验证。
  2. 将 compiler 扩展到 LangDyn:从此前的十个 tests 中移除 type annotations,再增加 5 个只能在 dynamic typing 下合法、但能无错误运行完成的 tests。实现时需要同时验证 tagged values、Inject/Project、dynamic tuple access、runtime bounds checking、closure conversion 与 GC root handling。

参考资料

← 返回列表
← 上一篇 Essentials of Compilation:词法作用域函数 下一篇 → Essentials of Compilation:渐进式类型

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论