skylabs.lang.cpp.semantics.types

(*
 * Copyright (c) 2020-2024 BlueRock Security, Inc.
 * This software is distributed under the terms of the BedRock Open-Source License.
 * See the LICENSE-BedRock file in the repository root for details.
 *)

Require Import elpi.apps.locker.locker.
Require Import skylabs.prelude.base.
Require Export skylabs.prelude.option.
Require Import skylabs.lang.cpp.syntax.
Require Import skylabs.lang.cpp.semantics.genv.

Definition GlobDecl_size_of (g : GlobDecl) : option N :=
  match g with
  | Gstruct s => Some s.(s_size)
  | Gunion u => Some u.(u_size)
  | Gopaque o => Some o.(o_size)
  | Genum t _ =>
    match drop_qualifiers t with
    | Tchar_ sz => Some $ char_type.bytesN sz
    | Tnum sz _ => Some $ int_rank.bytesN sz
    | Tbool => Some 1%N
    | _ => None
    end
  | _ => None
  end.
Definition GlobDecl_align_of (g : GlobDecl) : option N :=
  match g with
  | Gstruct s => Some s.(s_alignment)
  | Gunion u => Some u.(u_alignment)
  | Gopaque o => Some o.(o_alignment)
  | Genum t _ =>
    match drop_qualifiers t with
    | Tchar_ sz => Some $ char_type.bytesN sz
    | Tnum sz _ => Some $ int_rank.bytesN sz
    | Tbool => Some 1%N
    | _ => None
    end
  | _ => None
  end.

Layout metadata is untrusted: genv does not enforce these invariants. The logarithm formulation makes the power-of-two check decidable by computation and also excludes zero.
Definition valid_alignment (sz al : N) : Prop :=
  al = (2 ^ N.log2 al)%N /\ (sz mod al = 0)%N.

#[global] Instance valid_alignment_decision (sz al : N) :
  Decision (valid_alignment sz al).
Proof. unfold valid_alignment. solve_decision. Defined.

Lemma valid_alignment_spec (sz al : N) :
  valid_alignment sz al ->
  al <> 0%N /\ (exists n, al = (2 ^ n)%N) /\ (al | sz)%N.
Proof.
  intros [Hpow Hmod].
  have Hnonzero : al <> 0%N by rewrite Hpow; apply N.pow_nonzero.
  split; first done. split; first by exists (N.log2 al).
  by apply N.Lcm0.mod_divide.
Qed.

Only validated metadata may determine semantic alignment. Invalid or absent metadata leaves align_of abstract, just as an incomplete type does; None here does not assert that the type has no alignment.
Definition GlobDecl_valid_align_of (g : GlobDecl) : option N :=
  match GlobDecl_size_of g, GlobDecl_align_of g with
  | Some sz, Some al =>
      if bool_decide (valid_alignment sz al) then Some al else None
  | _, _ => None
  end.

Lemma GlobDecl_valid_align_of_spec (g : GlobDecl) (al : N) :
  GlobDecl_valid_align_of g = Some al ->
  exists sz, GlobDecl_size_of g = Some sz /\
    GlobDecl_align_of g = Some al /\ valid_alignment sz al.
Proof.
  rewrite /GlobDecl_valid_align_of.
  destruct (GlobDecl_size_of g) as [sz|] eqn:Hsz; cbn; last done.
  destruct (GlobDecl_align_of g) as [a|] eqn:Hal; cbn; last done.
  case_bool_decide; naive_solver.
Qed.

#[global] Instance proper_GlobDecl_size_of: Proper (GlobDecl_ler ==> Roption_leq eq) GlobDecl_size_of.
Proof.
  rewrite /GlobDecl_size_of/GlobDecl_ler/GlobDecl_le => x y Heq.
  do 2 case_match; subst; try contradiction; try constructor.
  case_bool_decide; subst; eauto. contradiction.
  case_bool_decide; subst; eauto. contradiction.
  case_bool_decide; subst; eauto. case_match; constructor; eauto. contradiction. case_bool_decide; subst; eauto. contradiction.
Qed.
#[global] Instance proper_GlobDecl_align_of: Proper (GlobDecl_ler ==> Roption_leq eq) GlobDecl_align_of.
Proof.
  rewrite /GlobDecl_size_of/GlobDecl_ler/GlobDecl_le => x y Heq.
  do 2 case_match; subst; try contradiction; try constructor.
  case_bool_decide; subst; eauto. contradiction.
  case_bool_decide; subst; eauto. contradiction.
  case_bool_decide; subst; eauto. simpl. case_match; constructor; eauto. contradiction. case_bool_decide; subst; eauto. contradiction.
Qed.

sizeof

The alignment that Trealigned states for an object of type t, looking through qualifiers and array layers: an array has the alignment of its element type.
Fixpoint realigned_head (t : type) : option N :=
  match t with
  | Tqualified _ t
  | Tarray t _
  | Tincomplete_array t
  | Tvariable_array t _ => realigned_head t
  | Trealigned n _ => Some n
  | _ => None
  end.

realign_ok t sz holds if sz, the size of t, is a multiple of the alignment that t states through Trealigned. Types with no such alignment, which is every type without Trealigned, satisfy it trivially, so it computes to true on concrete types. An over-aligned type such as Trealigned 32 Tint (size 4) does not satisfy it.
Definition realign_ok (t : type) (sz : N) : bool :=
  match realigned_head t with
  | Some a => bool_decide ((a | sz)%N)
  | None => true
  end.

The size of a C++ object. This is *not* the same as the semantics of the sizeof() operator because sizeof(int&) is actually sizeof(int) whereas size_of (Tref Tint) is the size of the reference cell, represented by a pointer (as are reference fields in offset_of).
Void call results use a one-byte logical storage cell. This models their existing primR Tvoid representation; it does not make void a complete C++ object type. This is safe because clang rejects every sized use of void in C++ (sizeof(void), alignof(void), arithmetic on or subtraction of void*, dereferencing or subscripting void*, arrays of void), so wp_operand_sizeof and pointer arithmetic never observe this size. If cpp2v ever accepted GNU C's void* arithmetic, this size would become its semantics, matching GNU's one-byte stride.
Also, size_of is well-defined even in case of overflow, so many users need bound-checking; see for instance wp_operand_sizeof.
Fixpoint size_of (resolve : genv) (t : type) : option N :=
  match t with
  | Tptr _ | Tref _ | Trv_ref _ => Some (pointer_size resolve)
  | Tnum sz _ => Some (int_rank.bytesN sz)
  | Tchar_ ct => Some (char_type.bytesN ct)
  | Tvoid => Some 1
  | Tarray t n =>
    (* Clang rejects arrays whose element size is not a multiple of the
       element's (over-)alignment, e.g. an array of
       Trealigned 32 Tint. *)

    match size_of resolve t with
    | Some sz => if realign_ok t sz then Some (N.mul n sz) else None
    | None => None
    end
  | Tincomplete_array _ => None
  | Tvariable_array _ _ => None
  | Tnamed nm => glob_def resolve nm ≫= GlobDecl_size_of
  | Tenum nm => glob_def resolve nm ≫= GlobDecl_size_of
  | Tfunction _ => None
  | Tbool => Some 1
  | Tmember_pointer _ _ => Some (member_pointer_size resolve)
  | Tqualified _ t => size_of resolve t
  | Trealigned _ t => size_of resolve t
  | Tnullptr => Some (pointer_size resolve)
  | Tfloat_ sz => Some (float_type.bytesN sz)
  | Tarch sz _ => bitsize.bytesN <$> sz
  | Tattributed _ _ => None
  | Tunsupported _ => None
  | Tdecltype _
  | Texprtype _
  | Tparam _
  | Tresult_param _
  | Tresult_global _
  | Tresult_unop _ _
  | Tresult_binop _ _ _
  | Tresult_parenlist _ _
  | Tresult_member _ _
  | Tresult_call _ _
  | Tresult_member_call _ _ _
  | Tauto => None
  end%N.

(* size_of result can overflow: *)
Goal forall σ, size_of σ (Tarray Tchar (2^128)) = Some (2^128)%N.
Proof. by []. Abort.
(* size_of result can overflow, even with in-bounds arguments: *)
Goal forall σ, size_of σ (Tarray Tlonglong (2^61)) = Some (2^64)%N.
Proof. by []. Abort.

#[global] Instance Proper_size_of
  : Proper (genv_leq ==> eq ==> Roption_leq eq) (@size_of).
Proof.
  intros ?? Hle ? t ->; induction t; simpl; (try constructor) => //.
  all: try exact: pointer_size_proper.
  all: try exact: member_pointer_size_proper.
  - move: IHt. rewrite /=.
    case: (size_of x t) => [a|]; case: (size_of y t) => [b|] H; inversion H; subst;
      try by constructor.
    case_match; constructor; done.
(*  - rewrite /glob_def.
    generalize (types_compat _ _ (tu_le Hle) gn).
    destruct (types (genv_tu x) !! gn) eqn:Heq; simpl.
    { intro H; destruct (H _ Heq) as ?[Heq' ?].
      rewrite Heq' /=.
      by eapply proper_GlobDecl_size_of. }
    { intros. constructor. }
  - rewrite /glob_def.
    generalize (types_compat _ _ (tu_le Hle) gn).
    destruct (types (genv_tu x) !! gn) eqn:Heq; simpl.
    { intro H; destruct (H _ Heq) as ?[Heq' ?].
      rewrite Heq' /=.
      by eapply proper_GlobDecl_size_of. }
    { intros. constructor. }
*)

  - rewrite /glob_def. move: Hle => /tu_le [/(_ gn) Hle _ _].
    revert Hle.
    case: (types (genv_tu x) !! gn); simpl; try constructor.
    move => ? /(_ _ eq_refl) [g2 [-> HH]] * /=.
    exact: proper_GlobDecl_size_of.
  - rewrite /glob_def. move: Hle => /tu_le [/(_ gn) Hle _ _].
    revert Hle.
    case: (types (genv_tu x) !! gn); simpl; try constructor.
    move => ? /(_ _ eq_refl) [g2 [-> HH]] * /=.
    exact: proper_GlobDecl_size_of.
  - by destruct osz; constructor.
Qed.

RealignOk σ ty says that ty's size, if any, is a multiple of the alignment ty states through Trealigned. It excludes over-aligned types such as Trealigned 32 Tint. Pointer arithmetic on ty requires it: offsetting an n-aligned pointer by whole elements preserves the alignment only if n divides the element size. Like HasSize, it is solved by instances; it holds trivially for every type without Trealigned (looking through qualifiers and arrays), whatever its size.
Class RealignOk {σ : genv} (ty : type) : Prop :=
  realign_ok_spec : forall sz, size_of σ ty = Some sz -> realign_ok ty sz = true.
#[global] Hint Mode RealignOk - + : typeclass_instances.
Lemma realign_ok_of (σ : genv) ty `{!RealignOk ty} sz :
  size_of σ ty = Some sz -> realign_ok ty sz = true.
Proof. intros. by apply realign_ok_spec. Qed.

#[global] Instance RealignOk_not_realigned {σ : genv} ty
  (H : TCEq (realigned_head ty) None) : RealignOk ty.
Proof.
  have E := proj1 (TCEq_eq _ _) H. rewrite /RealignOk /realign_ok => sz _. by rewrite E.
Qed.

Lemma RealignOk_of_ok σ ty sz :
  size_of σ ty = Some sz -> realign_ok ty sz = true -> RealignOk ty.
Proof. intros H1 H2 sz' H3. rewrite H1 in H3. by injection H3 as <-. Qed.

Theorem size_of_int : forall {c : genv} s w,
    @size_of c (Tnum w s) = Some (int_rank.bytesN w).
Proof. reflexivity. Qed.
Theorem size_of_char : forall {c : genv} s,
    @size_of c (Tchar_ s) = Some (char_type.bytesN s).
Proof. reflexivity. Qed.
Theorem size_of_void : forall {c : genv},
    @size_of c Tvoid = Some 1%N.
Proof. reflexivity. Qed.
Theorem size_of_bool : forall {c : genv},
    @size_of c Tbool = Some 1%N.
Proof. reflexivity. Qed.
Theorem size_of_pointer : forall {c : genv} t,
    @size_of c (Tptr t) = Some (pointer_size c).
Proof. reflexivity. Qed.
Theorem size_of_member_pointer : forall {c : genv} cls t,
    @size_of c (Tmember_pointer cls t) = Some (member_pointer_size c).
Proof. reflexivity. Qed.
Theorem size_of_ref : forall {c : genv} t,
    @size_of c (Tref t) = Some (pointer_size c).
Proof. reflexivity. Qed.
Theorem size_of_rv_ref : forall {c : genv} t,
    @size_of c (Trv_ref t) = Some (pointer_size c).
Proof. reflexivity. Qed.
Theorem size_of_qualified : forall {c : genv} t q,
    @size_of c t = @size_of c (Tqualified q t).
Proof. reflexivity. Qed.
Theorem size_of_array_0 : forall {c : genv} t sz `{!RealignOk t},
    @size_of c t = Some sz ->
    @size_of c (Tarray t 0) = Some 0%N.
Proof. intros c t sz HR H. simpl. by rewrite H (realign_ok_of c t sz H). Qed.

An array has a size only if its element's size is a multiple of the element's stated alignment (realign_ok); this is vacuous unless the element type is Trealigned.
Theorem size_of_array_shatter : forall {c : genv} ty n sz,
    @size_of c (Tarray ty n) = Some sz <-> exists sz', (sz = n * sz')%N /\ @size_of c ty = Some sz' /\ @size_of c (Tarray ty n) = Some (n * sz')%N.
Proof.
  simpl. intros. destruct (size_of c ty) as [s|] => /=; split; intros H.
  - destruct (realign_ok ty s); inversion H; subst; eauto.
  - destruct H as [? [-> [H1 H2]]]; injection H1 as <-. exact H2.
  - by inversion H.
  - by destruct H as [? [? [? ?]]]; discriminate.
Qed.

Theorem size_of_array_realign_ok : forall {c : genv} ty n sz,
    @size_of c (Tarray ty n) = Some sz ->
    exists sz', @size_of c ty = Some sz' /\ realign_ok ty sz' = true.
Proof.
  simpl. intros c ty n sz H. destruct (size_of c ty) as [s|]; last done.
  destruct (realign_ok ty s) eqn:E; last done. by exists s.
Qed.

Theorem size_of_array_pos : forall {c : genv} t n sz `{!RealignOk t},
    (0 < n)%N ->
    @size_of c t = Some sz <-> @size_of c (Tarray t n) = Some (n * sz)%N.
Proof.
  intros c t n sz HR Hn.
  simpl. destruct (size_of c t) as [s|] eqn:E; split; try congruence.
  - intros H. inversion H; subst. by rewrite (realign_ok_of c t _ E).
  - destruct (realign_ok t s); try congruence.
    inversion 1. f_equal. apply N.mul_cancel_l in H1. auto. lia.
Qed.

Theorem size_of_array : forall {c : genv} t n sz `{!RealignOk t},
    @size_of c t = Some sz ->
    @size_of c (Tarray t n) = Some (n * sz)%N.
Proof.
  intros c t n sz HR H. simpl. by rewrite H (realign_ok_of c t sz H).
Qed.

Lemma size_of_Tmut : forall {c} t,
    @size_of c t = @size_of c (Tmut t).
Proof. reflexivity. Qed.

Lemma size_of_Tconst : forall {c} t ,
    @size_of c t = @size_of c (Tconst t).
Proof. reflexivity. Qed.

(* XXX: since size_of simplifies eagerly, this might be hard to apply, so you
might need to inline the proof. *)

Lemma size_of_genv_compat tu σ gn st
      (Hσ : tu ⊧ σ)
      (Hl : tu.(types) !! gn = Some (Gstruct st)) :
  size_of σ (Tnamed gn) = GlobDecl_size_of (Gstruct st).
Proof. by rewrite /= (glob_def_genv_compat_struct st Hl). Qed.

Lemma realigned_head_erase_qualifiers ty :
  realigned_head (erase_qualifiers ty) = realigned_head ty.
Proof. induction ty => //=. Qed.
Lemma realign_ok_erase_qualifiers ty sz :
  realign_ok (erase_qualifiers ty) sz = realign_ok ty sz.
Proof. by rewrite /realign_ok realigned_head_erase_qualifiers. Qed.

Lemma size_of_erase_qualifiers σ ty :
  size_of σ (erase_qualifiers ty) = size_of σ ty.
Proof.
  induction ty => //=.
  rewrite IHty. case: (size_of σ ty) => [sz|] //.
  by rewrite realign_ok_erase_qualifiers.
Qed.

#[global] Instance RealignOk_erase_qualifiers {σ : genv} ty :
  RealignOk ty -> RealignOk (erase_qualifiers ty).
Proof.
  rewrite /RealignOk => H sz.
  by rewrite size_of_erase_qualifiers realign_ok_erase_qualifiers => /H.
Qed.

#[global] Instance RealignOk_qualified {σ : genv} q ty :
  RealignOk ty -> RealignOk (Tqualified q ty).
Proof. by rewrite /RealignOk /realign_ok. Qed.

#[global] Instance RealignOk_array {σ : genv} ty n :
  RealignOk ty -> RealignOk (Tarray ty n).
Proof.
  move=> H sz /size_of_array_shatter [sz' [-> [Hsz' _]]].
  have Hok := H _ Hsz'. move: Hok. rewrite /realign_ok /=.
  case: (realigned_head ty) => [a|] //.
  move=> /bool_decide_eq_true ?. apply bool_decide_eq_true. by apply N.divide_mul_r.
Qed.

#[global] Instance RealignOk_incomplete_array {σ : genv} ty : RealignOk (Tincomplete_array ty).
Proof. by move=> sz. Qed.
#[global] Instance RealignOk_variable_array {σ : genv} ty e : RealignOk (Tvariable_array ty e).
Proof. by move=> sz. Qed.

Lemma size_of_drop_qualifiers σ ty :
  size_of σ (drop_qualifiers ty) = size_of σ ty.
Proof. by induction ty. Qed.

SizeOf ty n means that C++ type ty has size n bytes
Class SizeOf {σ : genv} (ty : type) (n : N) : Prop :=
  size_of_spec : size_of σ ty = Some n.
#[global] Hint Mode SizeOf - + - : typeclass_instances.

#[global] Instance SizeOf_mono :
  Proper (genv_leq ==> eq ==> eq ==> impl) (@SizeOf).
Proof.
  rewrite /SizeOf=>σ1 σ2 Hσ t1 t2 Ht n ? <- ?.
  by destruct (Proper_size_of _ _ Hσ _ _ Ht); simplify_eq.
Qed.

#[global] Instance array_size_of {σ : genv} ty a n b :
  SizeOf ty a ->
  RealignOk ty ->
  TCEq (n * a)%N b ->
  SizeOf (Tarray ty n) b.
Proof.
  rewrite /SizeOf TCEq_eq=>Hty HR <-.
  cbn. by rewrite Hty (HR _ Hty).
Qed.

An explicit alignment that divides the size, e.g. a packed field.
#[global] Instance RealignOk_realigned {σ : genv} n ty sz :
  SizeOf ty sz -> TCEq (bool_decide (n | sz)%N) true ->
  RealignOk (Trealigned n ty).
Proof.
  move=> Hsz /(proj1 (TCEq_eq _ _)) H sz' /=. rewrite Hsz => -[<-].
  by rewrite /realign_ok /= H.
Qed.

#[global] Instance named_struct_size_of tu σ gn st n :
  genv_compat tu σ ->
  TCEq (tu.(types) !! gn) (Some (Gstruct st)) ->
  TCEq st.(s_size) n ->
  SizeOf (Tnamed gn) n.
Proof.
  rewrite /SizeOf !TCEq_eq=>? /glob_def_genv_compat_struct Htu <-.
  cbn. by rewrite Htu.
Qed.

#[global] Instance named_union_size_of tu σ gn u n :
  genv_compat tu σ ->
  TCEq (tu.(types) !! gn) (Some (Gunion u)) ->
  TCEq u.(u_size) n ->
  SizeOf (Tnamed gn) n.
Proof.
  rewrite /SizeOf !TCEq_eq=>? /glob_def_genv_compat_union Htu <-.
  cbn. by rewrite Htu.
Qed.

An opaque record has a size even though its body is not modeled.
#[global] Instance named_opaque_size_of tu σ gn o n :
  genv_compat tu σ ->
  TCEq (tu.(types) !! gn) (Some (Gopaque o)) ->
  TCEq o.(o_size) n ->
  SizeOf (Tnamed gn) n.
Proof.
  rewrite /SizeOf !TCEq_eq=>? /glob_def_genv_compat_opaque Htu <-.
  cbn. by rewrite Htu.
Qed.

#[global] Instance void_size_of {σ : genv} : SizeOf Tvoid 1.
Proof. done. Qed.

#[global] Instance bool_size_of {σ : genv} : SizeOf Tbool 1.
Proof. done. Qed.

(* TODO?: consider using SizeOf (Tnum sz sgn) (bytesN sz). *)
#[global] Instance int_size_of {σ : genv} sz sgn n :
  TCEq (int_rank.bytesN sz) n -> SizeOf (Tnum sz sgn) n.
Proof. by rewrite /SizeOf TCEq_eq=><-. Qed.

(* TODO?: consider using SizeOf (Tnum sz sgn) (char_type.bytesN ct). *)
#[global] Instance char_size_of {σ' : genv} ct n :
  TCEq (char_type.bytesN ct) n -> SizeOf (Tchar_ ct) n.
Proof. by rewrite /SizeOf TCEq_eq=><-. Qed.

#[global] Instance qualified_size_of {σ : genv} qual ty n :
  SizeOf ty n -> SizeOf (Tqualified qual ty) n.
Proof. done. Qed.

#[global] Instance ptr_size_of {σ : genv} ty n :
  TCEq (pointer_size σ) n -> SizeOf (Tptr ty) n.
Proof. by rewrite /SizeOf TCEq_eq=><-. Qed.

#[global] Instance member_ptr_size_of {σ : genv} cls ty n :
  TCEq (member_pointer_size σ) n -> SizeOf (Tmember_pointer cls ty) n.
Proof. by rewrite /SizeOf TCEq_eq=><-. Qed.

#[global] Instance ref_size_of {σ : genv} ty n :
  TCEq (pointer_size σ) n -> SizeOf (Tref ty) n.
Proof. by rewrite /SizeOf TCEq_eq=><-. Qed.

#[global] Instance rv_ref_size_of {σ : genv} ty n :
  TCEq (pointer_size σ) n -> SizeOf (Trv_ref ty) n.
Proof. by rewrite /SizeOf TCEq_eq=><-. Qed.

#[global] Instance arch_size_of {σ : genv} sz name n :
  TCEq (bitsize.bytesN sz) n -> SizeOf (Tarch (Some sz) name) n.
Proof. by rewrite /SizeOf TCEq_eq=><-. Qed.

Lemma size_of_to_heap_type g ty : size_of g (to_heap_type ty) = size_of g ty.
Proof.
  rewrite -(size_of_erase_qualifiers _ ty).
  rewrite /to_heap_type.
  by destruct (erase_qualifiers ty).
Qed.

HasSize ty means that C++ type ty has a defined size
Class HasSize {σ : genv} (ty : type) : Prop :=
  has_size : is_Some (size_of σ ty).
#[global] Hint Mode HasSize - + : typeclass_instances.
#[global] Arguments has_size {_} _ {_} : assert.

#[global] Instance HasSize_mono :
  Proper (genv_leq ==> eq ==> impl) (@HasSize).
Proof.
  rewrite /HasSize=>σ1 σ2 Hσ t1 t2 Ht H.
  destruct (Proper_size_of _ _ Hσ _ _ Ht).
  - exfalso. exact: is_Some_None.
  - by simplify_eq.
Qed.

#[global] Instance size_of_has_size {σ : genv} ty n :
  SizeOf ty n -> HasSize ty.
Proof.
  intros. rewrite /HasSize size_of_spec. by eexists.
Qed.

sizeof ty : N is the size of C++ type ty (if it has a size)
Definition sizeof {σ : genv} (ty : type) `{!HasSize ty} : N :=
  is_Some_proj (has_size ty).

Lemma sizeof_spec {σ : genv} ty `{Hsz : !HasSize ty} :
  size_of σ ty = Some (sizeof ty).
Proof.
  rewrite/sizeof/has_size. by destruct Hsz as [sz ->].
Qed.


Fixpoint find_assoc_list {K T} `{!EqDecision K} (f : K) (fs : list (K * T)) : option T :=
  match fs with
  | nil => None
  | (f',v) :: fs =>
    if decide (f = f') then
      Some v
    else find_assoc_list f fs
  end%list.

Lemma find_assoc_list_elem_of {K T} `{!EqDecision K} (base : K) xs :
  (∃ v, (base, v) ∈ xs) ->
  ∃ y, find_assoc_list (T := T) base xs = Some y.
Proof.
  move=>[v]. elim: xs => /= [/elem_of_nil //|[k w] xs IH]
    /elem_of_cons [|] Hin; simplify_eq.
  { rewrite decide_True; eauto. }
  case_decide; eauto.
Qed.

#[local] Close Scope nat_scope.
#[local] Open Scope Z_scope.
(* note: we expose the fact that reference fields are compiled to pointers,
   so the offset_of a reference field is the offset of the pointer.
 *)

Definition offset_of (σ : genv) (t : globname) (f : atomic_name) : option Z :=
  match glob_def σ t with
  | Some (Gstruct s) =>
    find_assoc_list f (List.map (fun m => (m.(mem_name),m.(mem_layout).(li_offset) / 8)) s.(s_fields))
  | Some (Gunion u) =>
    find_assoc_list f (List.map (fun m => (m.(mem_name),m.(mem_layout).(li_offset) / 8)) u.(u_fields))
  | _ => None
  end.

Field layout is preserved when a global environment is extended. This semantic fact does not depend on a particular pointer representation.
Lemma offset_of_extension (s1 s2 : genv) cls fld :
  genv_leq s1 s2 -> Roption_leq eq (offset_of s1 cls fld) (offset_of s2 cls fld).
Proof.
  intros Hle. have Hcompat : s1.(genv.genv_tu) ⊧ s2 by constructor; exact (tu_le Hle).
  apply (Roption_leq_eq_equiv (R:=eq)). intros z.
  rewrite /offset_of. case Hdef: (glob_def s1 cls) => [gd|] //.
  destruct gd => //; intros H.
  - erewrite (glob_def_genv_compat_union (Hσ := Hcompat)); eauto.
  - erewrite (glob_def_genv_compat_struct (Hσ := Hcompat)); eauto.
Qed.

Definition parent_offset_tu (tu : translation_unit) (derived : name) (base : name) : option Z :=
  match tu.(types) !! derived with
  | Some (Gstruct s) => find_assoc_list base (List.map (fun '(s,l) => (s,l.(li_offset) / 8)) s.(s_bases))
  | _ => None
  end.
(* We hide whether genv_tu exists. *)
mlock Definition parent_offset σ derived base := parent_offset_tu σ.(genv_tu) derived base.
Notation directly_derives_tu tu derived base := (is_Some (parent_offset_tu tu derived base)).
Notation directly_derives σ derived base := (is_Some (parent_offset σ derived base)).

Lemma find_assoc_list_parent_offset tu derived st base li :
  tu.(types) !! derived = Some (Gstruct st) ->
  (base, li) ∈ st.(s_bases) ->
  ∃ z, parent_offset_tu tu derived base = Some z.
Proof.
  rewrite /parent_offset_tu => -> Hin.
  apply /find_assoc_list_elem_of.
  eexists; apply /list_elem_of_fmap; by exists (base, li).
Qed.

Lemma parent_offset_genv_compat {σ tu derived base z} {Hσ : tu ⊧ σ} :
  parent_offset_tu tu derived base = Some z ->
  parent_offset σ derived base = Some z.
Proof.
  rewrite parent_offset.unlock /parent_offset_tu -/(glob_def σ derived).
  case E: (tu.(types) !! derived) => [ gd //= | // ]; destruct gd => //.
  by erewrite glob_def_genv_compat_struct.
Qed.

Base layout is likewise preserved independently of the pointer model.
Lemma parent_offset_extension (s1 s2 : genv) derived base :
  genv_leq s1 s2 ->
  Roption_leq eq (parent_offset s1 derived base) (parent_offset s2 derived base).
Proof.
  intros Hle. have Hcompat : s1.(genv.genv_tu) ⊧ s2 by constructor; exact (tu_le Hle).
  apply (Roption_leq_eq_equiv (R:=eq)). intros z H.
  apply (parent_offset_genv_compat (Hσ := Hcompat)).
  move: H. by rewrite parent_offset.unlock.
Qed.

alignof


(* align_of t returns the alignment of the type t.
 *)

Parameter align_of : forall {σ : genv} (t : type), option N.
Section with_genv.
  Context {σ : genv}.

  (* All alignments are in integral power of 2.
     See <https://eel.is/c++draft/basic.memobjbasic.align-4> *)

  Axiom align_of_power_of_two : forall t al, align_of t = Some al -> exists n, al = N.pow 2 n.

If size_of is defined, align_of exists and is nonzero.
  Axiom align_of_size_of_some : forall (t : type) sz,
      size_of σ t = Some sz ->
      (exists al, align_of t = Some al /\ al <> 0)%N.

align_of divides size_of, except for over-aligned types: RealignOk t excludes a Trealigned n u (under qualifiers and arrays) whose alignment n does not divide the size. RealignOk is solved by instances, so calls on concrete types need no extra argument. For instance, typedef int X __attribute__((aligned(32))) has size 4 and alignment 32. The side condition computes to true on concrete types without Trealigned.
If size_of is defined, align_of exists, is nonzero and divides size_of (except for over-aligned types, see align_of_divide_size_of).
  Lemma align_of_size_of' (t : type) sz `{!RealignOk t} :
      size_of σ t = Some sz ->
      (exists al, align_of t = Some al /\ al <> 0 /\ (al | sz))%N.
  Proof.
    move=> Hsz. have [al [Hal Hnz]] := align_of_size_of_some t sz Hsz.
    exists al. split_and!; [done..|]. exact: align_of_divide_size_of Hsz Hal.
  Qed.

  Lemma align_of_size_of (t : type) sz `{!RealignOk t} :
      size_of σ t = Some sz ->
      exists al, align_of t = Some al /\
            (* size is a multiple of alignment *)
            (sz mod al = 0)%N.
  Proof.
    move=>H1. destruct (align_of_size_of' _ _ H1) as [al [? [? ?]]].
    exists al. split; first done. by apply N.Lcm0.mod_divide.
  Qed.

An object of type Trealigned n t, such as a field of a packed record or an over-aligned variable, has the alignment its type states. cpp2v emits Trealigned n t for a field, or a variable, that Clang aligns to n bytes, which can be less than BRiCk assumes for t (packed) or more (typedef int X __attribute__((aligned(32)))). So n is only required to be a power of two. If n does not divide the size of t, then arrays of this type have no size (size_of), and align_of_size_of' does not apply.
  Axiom align_of_realigned : forall n t sz,
      size_of σ t = Some sz ->
      n = (2 ^ N.log2 n)%N ->
      align_of (Trealigned n t) = Some n.

  (* Validated alignments of named types are recorded in the translation unit.
     Missing layout metadata (e.g. Gtype or Gunsupported) does not mean
     that the type has no alignment: pointers to these types are still valid.
     Invalid metadata likewise leaves align_of abstract. *)

  Axiom align_of_named : forall nm al,
    glob_def σ nm ≫= GlobDecl_valid_align_of = Some al ->
    align_of (Tnamed nm) = Some al.

  Axiom align_of_array : forall (ty : type) n,
      align_of (Tarray ty n) = align_of ty.
  Axiom align_of_incomplete_array : forall (ty : type),
      align_of (Tincomplete_array ty) = align_of ty.
  Axiom align_of_variable_array : forall (ty : type) e,
      align_of (Tvariable_array ty e) = align_of ty.

  Axiom align_of_erase_qualifiers : ∀ t,
      align_of (erase_qualifiers t) = align_of t.

  Lemma align_of_char : align_of Tchar = Some 1%N.
  Proof.
    destruct (align_of_size_of' Tchar 1 (size_of_char _)) as [?[->[?Hd]]].
    by f_equal; eapply N.divide_1_r.
  Qed.
  Lemma align_of_uchar : align_of Tuchar = Some 1%N.
  Proof.
    destruct (align_of_size_of' Tuchar 1 (size_of_int _ _)) as [?[->[?Hd]]].
    by f_equal; eapply N.divide_1_r.
  Qed.
  Lemma align_of_schar : align_of Tschar = Some 1%N.
  Proof.
    destruct (align_of_size_of' Tschar 1 (size_of_int _ _)) as [?[->[?Hd]]].
    by f_equal; eapply N.divide_1_r.
  Qed.
  Lemma align_of_void : align_of Tvoid = Some 1%N.
  Proof.
    destruct (align_of_size_of' Tvoid 1 size_of_void) as [?[->[?Hd]]].
    by f_equal; eapply N.divide_1_r.
  Qed.

  (* NOTE: the following three axioms equate the size and alignment of
     certain fundamental types. This does not seem to be sanctioned by
     the standard, but does seem to be true in practice.
   *)

  Axiom UNSAFE_align_is_size_int : forall sz sgn, align_of (Tnum sz sgn) = size_of σ (Tnum sz sgn).
  Axiom UNSAFE_align_is_size_char : forall c, align_of (Tchar_ c) = size_of σ (Tchar_ c).
  Axiom UNSAFE_align_is_size_ptr : forall t, align_of (Tptr t) = size_of σ (Tptr t).

  Lemma align_of_qualified : ∀ t q,
      align_of (Tqualified q t) = align_of t.
  Proof.
    intros.
    rewrite -{1}align_of_erase_qualifiers. simpl. by rewrite align_of_erase_qualifiers.
  Qed.

  Axiom Proper_align_of : Proper (genv_leq ==> eq ==> Roption_leq eq) (@align_of).
  #[global] Existing Instance Proper_align_of.

  Lemma align_of_genv_compat tu gn st
        (Hσ : tu ⊧ σ)
        (Hl : tu.(types) !! gn = Some (Gstruct st)) :
    valid_alignment st.(s_size) st.(s_alignment) ->
    align_of (Tnamed gn) = GlobDecl_align_of (Gstruct st).
  Proof.
    intros Hvalid. apply align_of_named.
    rewrite (glob_def_genv_compat_struct st Hl) /GlobDecl_valid_align_of /=.
    by rewrite bool_decide_true.
  Qed.

As for a struct, an opaque record's alignment is only trusted once validated against its size.
  Lemma align_of_genv_compat_opaque tu gn o
        (Hσ : tu ⊧ σ)
        (Hl : tu.(types) !! gn = Some (Gopaque o)) :
    valid_alignment o.(o_size) o.(o_alignment) ->
    align_of (Tnamed gn) = GlobDecl_align_of (Gopaque o).
  Proof.
    intros Hvalid. apply align_of_named.
    rewrite (glob_def_genv_compat_opaque o Hl) /GlobDecl_valid_align_of /=.
    by rewrite bool_decide_true.
  Qed.

  Lemma align_of_genv_leq σ1 σ2 ty align :
    @align_of σ1 ty = Some align ->
    genv_leq σ1 σ2 ->
    @align_of σ2 ty = Some align.
  Proof.
    move=> /[swap] /Proper_align_of /(_ ty ty eq_refl) /=.
    by inversion 1; naive_solver.
  Qed.
End with_genv.

Sufficient metadata for projecting complete-object pointer typing to a base. This concerns pointer extent and alignment, not ownership of base bytes.
Definition base_layout_compatible (σ : genv) (derived base : name) : Prop :=
  exists dsz bsz dal bal z,
    size_of σ (Tnamed derived) = Some dsz /\
    size_of σ (Tnamed base) = Some bsz /\
    @align_of σ (Tnamed derived) = Some dal /\
    @align_of σ (Tnamed base) = Some bal /\
    parent_offset σ derived base = Some z /\
    (bal | dal)%N /\ (Z.of_N bal | z)%Z /\
    (0 <= z)%Z /\ (z = 0 \/ z < Z.of_N dsz)%Z /\
    (z + Z.of_N bsz <= Z.of_N dsz)%Z.

Definition tu_base_layout_compatible (tu : translation_unit) (derived base : name) : bool :=
  match tu.(types) !! derived, tu.(types) !! base, parent_offset_tu tu derived base with
  | Some (Gstruct ds), Some (Gstruct bs), Some z =>
      bool_decide (
        valid_alignment ds.(s_size) ds.(s_alignment) /\
        valid_alignment bs.(s_size) bs.(s_alignment) /\
        (bs.(s_alignment) | ds.(s_alignment))%N /\
        (Z.of_N bs.(s_alignment) | z)%Z /\
        (0 <= z)%Z /\ (z = 0 \/ z < Z.of_N ds.(s_size))%Z /\
        (z + Z.of_N bs.(s_size) <= Z.of_N ds.(s_size))%Z)
  | _, _, _ => false
  end.

Lemma tu_base_layout_compatible_sound {σ tu} {Hσ : tu ⊧ σ} derived base :
  tu_base_layout_compatible tu derived base = true ->
  base_layout_compatible σ derived base.
Proof.
  rewrite /tu_base_layout_compatible.
  destruct (tu.(types) !! derived) as [gd|] eqn:Hd; last discriminate.
  destruct gd as [| |ds| | | | |]; try discriminate.
  destruct (tu.(types) !! base) as [gb|] eqn:Hb; last discriminate.
  destruct gb as [| |bs| | | | |]; try discriminate.
  destruct (parent_offset_tu tu derived base) as [z|] eqn:Hz; last discriminate.
  intros Hcheck. apply bool_decide_eq_true in Hcheck.
  destruct Hcheck as (Hda & Hba & Hdiv & Hdz & Hnonneg & Hstrict & Hbound).
  exists ds.(s_size), bs.(s_size), ds.(s_alignment), bs.(s_alignment), z.
  repeat split; try assumption.
  - exact (size_of_genv_compat tu σ derived ds Hσ Hd).
  - exact (size_of_genv_compat tu σ base bs Hσ Hb).
  - exact (align_of_genv_compat tu derived ds Hσ Hd Hda).
  - exact (align_of_genv_compat tu base bs Hσ Hb Hba).
  - exact (parent_offset_genv_compat Hz).
Qed.