(* *********************************************************************)
(*                                                                     *)
(*            The CertiKOS Certified Kit Operating System              *)
(*                                                                     *)
(*                   The FLINT Group, Yale University                  *)
(*                                                                     *)
(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)
(*  This file is distributed under the terms of the Yale University    *)
(*  Non-Commercial License Agreement.                                  *)
(*                                                                     *)
(* *********************************************************************)
(* *********************************************************************)
(*                                                                     *)
(*              Layers of PM: PThreadInit                              *)
(*                                                                     *)
(*          Provide abstraction of Context                             *)
(*                                                                     *)
(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)
(*          Yu Guo <yu.guo@yale.edu>                                   *)
(*                                                                     *)
(*          Yale Flint Group                                           *)
(*                                                                     *)
(* *********************************************************************)

(** This file defines the abstract data and the primitives for the PThreadInit layer,
which will introduce abstraction of kernel context*)
Require Import Coqlib.
Require Import Maps.
Require Import ASTExtra.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import Events.
Require Import Stacklayout.
Require Import Globalenvs.
Require Import AsmX.
Require Import Smallstep.
Require Import AuxStateDataType.
Require Import Constant.
Require Import GlobIdent.
Require Import FlatMemory.
Require Import CommonTactic.
Require Import AuxLemma.
Require Import RealParams.
Require Import PrimSemantics.
Require Import LAsm.
Require Import LoadStoreSem2.
Require Import XOmega.
Require Import ObservationImpl.

Require Import liblayers.logic.PTreeModules.
Require Import liblayers.logic.LayerLogicImpl.
Require Import liblayers.compat.CompatLayers.
Require Import liblayers.compat.CompatGenSem.

Require Import CalRealPTPool.
Require Import CalRealPT.
Require Import CalRealIDPDE.
Require Import CalRealInitPTE.
Require Import CalRealSMSPool.
Require Import CalRealProcModule.

Require Import INVLemmaContainer.
Require Import INVLemmaMemory.
Require Import INVLemmaThread.

Require Import AbstractDataType.

Require Export ObjCPU.
Require Export ObjFlatMem.
Require Export ObjContainer.
Require Export ObjVMM.
Require Export ObjLMM.
Require Export ObjShareMem.
Require Export ObjThread.
Require Export ObjQueue.

(** * Abstract Data and Primitives at this layer*)
Section WITHMEM.

  Local Open Scope Z_scope.

  Context `{real_params: RealParams}.

  (** **Definition of the invariants at MPTNew layer*)
  (** [0th page map] is reserved for the kernel thread*)
  Record high_level_invariant (abd: RData) :=
    mkInvariant {
        valid_nps: pg abd = true -> kern_low <= nps abd <= maxpage;
        valid_AT_kern: pg abd = true -> LAT_kern (LAT abd) (nps abd);
        valid_AT_usr: pg abd = true -> LAT_usr (LAT abd) (nps abd);
        valid_kern: ipt abd = false -> pg abd = true;
        valid_iptt: ipt abd = true -> ikern abd = true;
        valid_iptf: ikern abd = false -> ipt abd = false;
        valid_ihost: ihost abd = false -> pg abd = true /\ ikern abd = true;
        valid_container: Container_valid (AC abd);
        valid_pperm_ppage: Lconsistent_ppage (LAT abd) (pperm abd) (nps abd);
        init_pperm: pg abd = false -> (pperm abd) = ZMap.init PGUndef;
        valid_PMap: pg abd = true ->
                    (forall i, 0<= i < num_proc ->
                               PMap_valid (ZMap.get i (ptpool abd)));
        (* 0th page map is reserved for the kernel thread*)
        valid_PT_kern: pg abd = true -> ipt abd = true -> (PT abd) = 0;
        valid_PMap_kern: pg abd = true -> PMap_kern (ZMap.get 0 (ptpool abd));
        valid_PT: pg abd = true -> 0<= PT abd < num_proc;
        valid_dirty: dirty_ppage (pperm abd) (HP abd);

        valid_idpde: pg abd = true -> IDPDE_init (idpde abd);
        valid_pperm_pmap: consistent_pmap (ptpool abd) (pperm abd) (LAT abd) (nps abd);
        valid_pmap_domain: consistent_pmap_domain (ptpool abd) (pperm abd) (LAT abd) (nps abd);
        valid_lat_domain: consistent_lat_domain (ptpool abd) (LAT abd) (nps abd);

        valid_root: pg abd = true -> cused (ZMap.get 0 (AC abd)) = true;

        valid_TCB: pg abd = true -> TCBCorrect_range (tcb abd)

      }.

  (** ** Definition of the abstract state ops *)
  Global Instance pthreadinit_data_ops : CompatDataOps RData :=
    {
      empty_data := init_adt;
      high_level_invariant := high_level_invariant;
      low_level_invariant := low_level_invariant;
      kernel_mode adt := ikern adt = true /\ ihost adt = true;
      observe := ObservationImpl.observe
    }.

  (** ** Proofs that the initial abstract_data should satisfy the invariants*)
  Section Property_Abstract_Data.

    Lemma empty_data_high_level_invariant:
      high_level_invariant init_adt.
    Proof.
      constructor; simpl; intros; auto; try inv H.
      - apply empty_container_valid.
      - eapply Lconsistent_ppage_init.
      - eapply dirty_ppage_init.
      - eapply consistent_pmap_init.
      - eapply consistent_pmap_domain_init.
      - eapply consistent_lat_domain_init.
    Qed.

    (** ** Definition of the abstract state *)
    Global Instance pthreadinit_data_prf : CompatData RData.
    Proof.
      constructor.
      - apply low_level_invariant_incr.
      - apply empty_data_low_level_invariant.
      - apply empty_data_high_level_invariant.
    Qed.

  End Property_Abstract_Data.

  Context `{Hstencil: Stencil}.
  Context `{Hmem: Mem.MemoryModel}.
  Context `{Hmwd: UseMemWithData mem}.

  (** * Proofs that the primitives satisfies the invariants at this layer *)
  Section INV.

    Section ALLOC.

      Lemma alloc_high_level_inv:
        forall d d' i n,
          alloc_spec i d = Some (d', n) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; simpl; eauto.
        - intros; eapply LAT_kern_norm; eauto. eapply _x.
        - intros; eapply LAT_usr_norm; eauto.
        - eapply alloc_container_valid'; eauto.
        - eapply Lconsistent_ppage_norm_alloc; eauto.
        - intros; congruence.
        - eapply dirty_ppage_gso_alloc; eauto.
        - eapply consistent_pmap_gso_at_false; eauto. apply _x.
        - eapply consistent_pmap_domain_gso_at_false; eauto. apply _x.
        - eapply consistent_lat_domain_gss_nil; eauto.
        - zmap_solve.
      Qed.

      Lemma alloc_low_level_inv:
        forall d d' i n n',
          alloc_spec i d = Some (d', n) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; eauto.
      Qed.

      Lemma alloc_kernel_mode:
        forall d d' i n,
          alloc_spec i d = Some (d', n) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
      Qed.

      Global Instance alloc_inv: PreservesInvariants alloc_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply alloc_low_level_inv; eassumption.
        - eapply alloc_high_level_inv; eassumption.
        - eapply alloc_kernel_mode; eassumption.
      Qed.

    End ALLOC.

    Global Instance pfree_inv: PreservesInvariants pfree_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      - intros; eapply LAT_kern_norm; eauto.
      - intros; eapply LAT_usr_norm; eauto.
      - eapply Lconsistent_ppage_norm_undef; eauto.
      - eapply dirty_ppage_gso_undef; eauto.
      - eapply consistent_pmap_gso_pperm_alloc; eauto.
      - eapply consistent_pmap_domain_gso_at_0; eauto.
      - eapply consistent_lat_domain_gss_nil; eauto.
    Qed.

    Global Instance trapin_inv: PrimInvariants trapin_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance trapout_inv: PrimInvariants trapout_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance hostin_inv: PrimInvariants hostin_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance hostout_inv: PrimInvariants hostout_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance ptin_inv: PrimInvariants ptin_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance ptout_inv: PrimInvariants ptout_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance fstore_inv: PreservesInvariants fstore_spec.
    Proof.
      split; intros; inv_generic_sem H; inv H0; functional inversion H2.
      - functional inversion H. split; trivial.
      - functional inversion H.
        split; subst; simpl;
        try (eapply dirty_ppage_store_unmaped; try reflexivity; try eassumption); trivial.
      - functional inversion H0.
        split; simpl; try assumption.
    Qed.

    Global Instance setPT_inv: PreservesInvariants setPT_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
    Qed.

    Section PTINSERT.

      Section PTINSERT_PTE.

        Lemma ptInsertPTE_high_level_inv:
          forall d d' n vadr padr p,
            ptInsertPTE0_spec n vadr padr p d = Some d' ->
            high_level_invariant d ->
            high_level_invariant d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0; constructor_gso_simpl_tac; intros.
          - eapply LAT_kern_norm; eauto.
          - eapply LAT_usr_norm; eauto.
          - eapply Lconsistent_ppage_norm; eassumption.
          - eapply PMap_valid_gso_valid; eauto.
          - functional inversion H2. functional inversion H1.
            eapply PMap_kern_gso; eauto.
          - functional inversion H2. functional inversion H0.
            eapply consistent_pmap_ptp_same; try eassumption.
            eapply consistent_pmap_gso_pperm_alloc'; eassumption.
          - functional inversion H2.
            eapply consistent_pmap_domain_append; eauto.
            destruct (ZMap.get pti pdt); try contradiction;
            red; intros (v0 & p0 & He); contra_inv.
          - eapply consistent_lat_domain_gss_append; eauto.
            subst pti; destruct (ZMap.get (PTX vadr) pdt); try contradiction;
            red; intros (v0 & p0 & He); contra_inv.
        Qed.

        Lemma ptInsertPTE_low_level_inv:
          forall d d' n vadr padr p n',
            ptInsertPTE0_spec n vadr padr p d = Some d' ->
            low_level_invariant n' d ->
            low_level_invariant n' d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0. constructor; eauto.
        Qed.

        Lemma ptInsertPTE_kernel_mode:
          forall d d' n vadr padr p,
            ptInsertPTE0_spec n vadr padr p d = Some d' ->
            kernel_mode d ->
            kernel_mode d'.
        Proof.
          intros. functional inversion H; subst; eauto.
        Qed.

      End PTINSERT_PTE.

      Section PTALLOCPDE.

        Lemma ptAllocPDE_high_level_inv:
          forall d d' n vadr v,
            ptAllocPDE0_spec n vadr d = Some (d', v) ->
            high_level_invariant d ->
            high_level_invariant d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0; constructor_gso_simpl_tac; intros.
          - eapply LAT_kern_norm; eauto. eapply _x.
          - eapply LAT_usr_norm; eauto.
          - eapply alloc_container_valid'; eauto.
          - apply Lconsistent_ppage_norm_hide; try assumption.
          - congruence.
          - eapply PMap_valid_gso_pde_unp; eauto.
            eapply real_init_PTE_defined.
          - functional inversion H3.
            eapply PMap_kern_gso; eauto.
          - eapply dirty_ppage_gss; eauto.
          - eapply consistent_pmap_ptp_gss; eauto; apply _x.
          - eapply consistent_pmap_domain_gso_at_false; eauto; try apply _x.
            eapply consistent_pmap_domain_ptp_unp; eauto.
            apply real_init_PTE_unp.
          - apply consistent_lat_domain_gss_nil; eauto.
            apply consistent_lat_domain_gso_p; eauto.
          - zmap_solve.
        Qed.

        Lemma ptAllocPDE_low_level_inv:
          forall d d' n vadr v n',
            ptAllocPDE0_spec n vadr d = Some (d', v) ->
            low_level_invariant n' d ->
            low_level_invariant n' d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0. constructor; eauto.
        Qed.

        Lemma ptAllocPDE_kernel_mode:
          forall d d' n vadr v,
            ptAllocPDE0_spec n vadr d = Some (d', v) ->
            kernel_mode d ->
            kernel_mode d'.
        Proof.
          intros. functional inversion H; subst; eauto.
        Qed.

      End PTALLOCPDE.

      Lemma ptInsert_high_level_inv:
        forall d d' n vadr padr p v,
          ptInsert0_spec n vadr padr p d = Some (d', v) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        - eapply ptInsertPTE_high_level_inv; eassumption.
        - eapply ptAllocPDE_high_level_inv; eassumption.
        - eapply ptInsertPTE_high_level_inv; try eassumption.
          eapply ptAllocPDE_high_level_inv; eassumption.
      Qed.

      Lemma ptInsert_low_level_inv:
        forall d d' n vadr padr p n' v,
          ptInsert0_spec n vadr padr p d = Some (d', v) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        - eapply ptInsertPTE_low_level_inv; eassumption.
        - eapply ptAllocPDE_low_level_inv; eassumption.
        - eapply ptInsertPTE_low_level_inv; try eassumption.
          eapply ptAllocPDE_low_level_inv; eassumption.
      Qed.

      Lemma ptInsert_kernel_mode:
        forall d d' n vadr padr p v,
          ptInsert0_spec n vadr padr p d = Some (d', v) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        - eapply ptInsertPTE_kernel_mode; eassumption.
        - eapply ptAllocPDE_kernel_mode; eassumption.
        - eapply ptInsertPTE_kernel_mode; try eassumption.
          eapply ptAllocPDE_kernel_mode; eassumption.
      Qed.

    End PTINSERT.

    Section PTRESV.

      Lemma ptResv_high_level_inv:
        forall d d' n vadr p v,
          ptResv_spec n vadr p d = Some (d', v) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        eapply ptInsert_high_level_inv; try eassumption.
        eapply alloc_high_level_inv; eassumption.
      Qed.

      Lemma ptResv_low_level_inv:
        forall d d' n vadr p n' v,
          ptResv_spec n vadr p d = Some (d', v) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        eapply ptInsert_low_level_inv; try eassumption.
        eapply alloc_low_level_inv; eassumption.
      Qed.

      Lemma ptResv_kernel_mode:
        forall d d' n vadr p v,
          ptResv_spec n vadr p d = Some (d', v) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        eapply ptInsert_kernel_mode; try eassumption.
        eapply alloc_kernel_mode; eassumption.
      Qed.

      Global Instance ptResv_inv: PreservesInvariants ptResv_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply ptResv_low_level_inv; eassumption.
        - eapply ptResv_high_level_inv; eassumption.
        - eapply ptResv_kernel_mode; eassumption.
      Qed.

    End PTRESV.

    Section OFFER_SHARE.

      Section PTRESV2.

        Lemma ptResv2_high_level_inv:
          forall d d' n vadr p n' vadr' p' v,
            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->
            high_level_invariant d ->
            high_level_invariant d'.
        Proof.
          intros; functional inversion H; subst; eauto;
          eapply ptInsert_high_level_inv; try eassumption.
          - eapply alloc_high_level_inv; eassumption.
          - eapply ptInsert_high_level_inv; try eassumption.
            eapply alloc_high_level_inv; eassumption.
        Qed.

        Lemma ptResv2_low_level_inv:
          forall d d' n vadr p n' vadr' p' l v,
            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->
            low_level_invariant l d ->
            low_level_invariant l d'.
        Proof.
          intros; functional inversion H; subst; eauto;
          eapply ptInsert_low_level_inv; try eassumption.
          - eapply alloc_low_level_inv; eassumption.
          - eapply ptInsert_low_level_inv; try eassumption.
            eapply alloc_low_level_inv; eassumption.
        Qed.

        Lemma ptResv2_kernel_mode:
          forall d d' n vadr p n' vadr' p' v,
            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->
            kernel_mode d ->
            kernel_mode d'.
        Proof.
          intros; functional inversion H; subst; eauto;
          eapply ptInsert_kernel_mode; try eassumption.
          - eapply alloc_kernel_mode; eassumption.
          - eapply ptInsert_kernel_mode; try eassumption.
            eapply alloc_kernel_mode; eassumption.
        Qed.

      End PTRESV2.

      Global Instance offer_shared_mem_inv:
        PreservesInvariants offer_shared_mem_spec.
      Proof.
        preserves_invariants_simpl';
        functional inversion H2; subst; eauto 2; try (inv H0; constructor; trivial; fail).
        - exploit ptResv2_low_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_low_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_high_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_high_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_kernel_mode; eauto.
        - exploit ptResv2_kernel_mode; eauto.
      Qed.

    End OFFER_SHARE.

    Global Instance shared_mem_status_inv:
      PreservesInvariants shared_mem_status_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
    Qed.

    Global Instance kctxt_switch_inv: KCtxtSwitchInvariants kctxt_switch_spec.
    Proof.
      constructor; intros; functional inversion H.
      - inv H1. constructor; trivial.
        eapply kctxt_inject_neutral_gss_mem; eauto.
      - inv H0. subst. constructor; auto; simpl in *; intros; try congruence.
    Qed.

    Global Instance kctxt_new_inv: DNewInvariants ObjThread.kctxt_new_spec.
    Proof.
      constructor; intros; inv H0;
      unfold ObjThread.kctxt_new_spec in *; subdestruct; inv H; simpl; auto.
      - (* low level invariant *)
        constructor; trivial; intros; simpl in *.
        eapply kctxt_inject_neutral_gss_flatinj'; eauto.
        eapply kctxt_inject_neutral_gss_flatinj; eauto.

      - (* high_level_invariant *)
        constructor; simpl; eauto 2; try congruence; intros.
        + exploit split_container_valid; eauto.
          eapply container_split_some; eauto.
          auto.
        + unfold update_cusage, update_cchildren; zmap_solve.
    Qed.

    Global Instance thread_init_inv: PreservesInvariants thread_init_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant.
      - apply real_nps_range.
      - apply real_lat_kern_valid.
      - apply real_lat_usr_valid.
      - apply real_container_valid.
      - rewrite init_pperm0; try assumption.
        apply Lreal_pperm_valid.
      - eapply real_pt_PMap_valid; eauto.
      - apply real_pt_PMap_kern.
      - omega.
      - assumption.
      - apply real_idpde_init.
      - apply real_pt_consistent_pmap.
      - apply real_pt_consistent_pmap_domain.
      - apply Lreal_at_consistent_lat_domain.
      - apply real_TCB_valid.
    Qed.

    Global Instance set_state_inv: PreservesInvariants set_state_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.
      eapply TCBCorrect_range_gso; eauto.
    Qed.

    Global Instance set_prev_inv: PreservesInvariants set_prev_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.
      eapply TCBCorrect_range_gss_prev; eauto.
    Qed.

    Global Instance set_next_inv: PreservesInvariants set_next_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.
      eapply TCBCorrect_range_gss_next; eauto.
    Qed.

    Global Instance clearCR2_inv: PreservesInvariants clearCR2_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.
    Qed.

    (*Global Instance thread_free_inv: PreservesInvariants (fun a d => thread_free_spec d a).
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.
      - destruct (zeq i0 (Int.unsigned i)); subst.
        + rewrite ZMap.gss. apply PT_init_common_pdt_usr.
          apply real_free_pt_valid; apply valid_PT_common0; auto.
        + rewrite ZMap.gso; auto.
      - destruct (zeq (Int.unsigned i) 0); subst. omega.
        rewrite ZMap.gso; auto.
      - destruct (zeq (Int.unsigned i) 0); subst. omega.
        rewrite ZMap.gso; auto.
      - unfold PTB_defined in *; intros.
        destruct (zeq (Int.unsigned i) i0); subst.
        rewrite ZMap.gss.
        red; intros HF; inv HF.
        rewrite ZMap.gso; auto.
      - unfold TCBCorrect_range in *; intros.
        unfold TCBCorrect in *.
        destruct (zeq i0 (Int.unsigned i)); subst.
        + rewrite ZMap.gss.
          refine_split'; eauto; omega.
        + rewrite ZMap.gso; eauto.
    Qed.*)

    Global Instance flatmem_copy_inv: PreservesInvariants flatmem_copy_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant;
      try eapply dirty_ppage_gss_copy; eauto.
    Qed.

    Global Instance device_output_inv: PreservesInvariants device_output_spec.
    Proof.
      preserves_invariants_simpl'' low_level_invariant high_level_invariant; eauto.
    Qed.

  End INV.

  Definition exec_loadex {F V} := exec_loadex2 (F := F) (V := V).

  Definition exec_storeex {F V} :=  exec_storeex2 (flatmem_store:= flatmem_store) (F := F) (V := V).

  Global Instance flatmem_store_inv: FlatmemStoreInvariant (flatmem_store:= flatmem_store).
  Proof.
    split; inversion 1; intros.
    - functional inversion H0. split; trivial.
    - functional inversion H1.
      split; simpl; try (eapply dirty_ppage_store_unmaped'; try reflexivity; try eassumption); trivial.
  Qed.

  Global Instance trapinfo_set_inv: TrapinfoSetInvariant.
  Proof.
    split; inversion 1; intros; constructor; auto.
  Qed.

  (** * Layer Definition *)
  Definition pthreadinit_fresh : compatlayer (cdata RData) :=
    thread_init ↦ gensem thread_init_spec.
    (*⊕ thread_free ↦ gensem thread_free_spec*)

  Definition pthreadinit_passthrough : compatlayer (cdata RData) :=
    fload ↦ gensem fload_spec
          ⊕ fstore ↦ gensem fstore_spec
          ⊕ flatmem_copy ↦ gensem flatmem_copy_spec
          ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec
          ⊕ device_output ↦ gensem device_output_spec
          ⊕ pfree ↦ gensem pfree_spec
          ⊕ set_pt ↦ gensem setPT_spec
          ⊕ pt_read ↦ gensem ptRead_spec
          ⊕ pt_resv ↦ gensem ptResv_spec
          (*⊕ pt_free ↦ gensem pt_free_spec*)
          ⊕ kctxt_new ↦ dnew_compatsem ObjThread.kctxt_new_spec
          ⊕ shared_mem_status ↦ gensem shared_mem_status_spec
          ⊕ offer_shared_mem ↦ gensem offer_shared_mem_spec
          ⊕ get_state ↦ gensem get_state_spec
          ⊕ get_prev ↦ gensem get_prev_spec
          ⊕ get_next ↦ gensem get_next_spec
          ⊕ set_state ↦ gensem set_state_spec
          ⊕ set_prev ↦ gensem set_prev_spec
          ⊕ set_next ↦ gensem set_next_spec

          ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)
          ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)
          ⊕ clear_cr2 ↦ gensem clearCR2_spec
          ⊕ container_get_nchildren ↦ gensem container_get_nchildren_spec
          ⊕ container_get_quota ↦ gensem container_get_quota_spec
          ⊕ container_get_usage ↦ gensem container_get_usage_spec
          ⊕ container_can_consume ↦ gensem container_can_consume_spec
          ⊕ container_alloc ↦ gensem alloc_spec
          ⊕ trap_in ↦ primcall_general_compatsem trapin_spec
          ⊕ trap_out ↦ primcall_general_compatsem trapout_spec
          ⊕ host_in ↦ primcall_general_compatsem hostin_spec
          ⊕ host_out ↦ primcall_general_compatsem hostout_spec
          ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec
          ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec
          ⊕ kctxt_switch ↦ primcall_kctxt_switch_compatsem kctxt_switch_spec
          ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.

  Definition pthreadinit : compatlayer (cdata RData) := pthreadinit_fresh ⊕ pthreadinit_passthrough.

  (*Definition semantics := LAsm.Lsemantics pthreadinit.*)

End WITHMEM.


Require Import VST.concurrency.conclib.
Require Import VST.progs.ghost.
(*Require Import VST.progs.list_dt. Import LsegSpecial.*)
Require Import VST.floyd.library.
Require Import VST.progs.lock_coupling.
Require Import Sorting.

Require Export VST.floyd.Funspec_old_Notation.
#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.
Definition Vprog : varspecs. mk_varspecs prog. Defined.

Definition acquire_spec := DECLARE _acquire acquire_spec.
Definition release_spec := DECLARE _release release_spec.
Definition makelock_spec := DECLARE _makelock (makelock_spec _).
Definition freelock_spec := DECLARE _freelock (freelock_spec _).

Definition surely_malloc_spec :=
 DECLARE _surely_malloc
   WITH n:Z
   PRE [ _n OF tuint ]
       PROP (0 <= n <= Int.max_unsigned)
       LOCAL (temp _n (Vint (Int.repr n)))
       SEP ()
    POST [ tptr tvoid ] EX p:_,
       PROP ()
       LOCAL (temp ret_temp p)
       SEP (malloc_token Tsh n p * memory_block Tsh n p).

Definition tnode := Tstruct _node noattr.

Module ZOrder <: Orders.TotalLeBool.
  Definition t := Z.
  Definition leb x y := Z.leb x y.
  Theorem leb_total : forall x y, leb x y = true \/ leb y x = true.
  Proof. intros; destruct (Zle_bool_total x y); auto. Qed.
End ZOrder.

Module Import ZSort := Sort ZOrder.

Lemma StronglySorted_imp : forall (R R' : Z -> Z -> Prop) l (HR' : forall x y, R x y -> R' x y)
  (HR : StronglySorted R l), StronglySorted R' l.
Proof.
  intros; induction HR; constructor; auto.
  eapply Forall_impl, H; auto.
Qed.

Notation sorted := (StronglySorted Z.le).

Lemma sort_sorted : forall l, sorted (sort l).
Proof.
  intro; eapply StronglySorted_imp, StronglySorted_sort.
  - intros.
    rewrite <- Z.leb_le; auto.
  - intros ???; apply Zle_bool_trans.
Qed.

Inductive set_op := Add (e : Z) | Remove (e : Z).

Fixpoint apply_hist S h :=
  match h with
  | [] => S
  | Add e :: h' => if in_dec Z_eq_dec e S then apply_hist S h' else apply_hist (sort (e :: S)) h'
  | Remove e :: h' => apply_hist (remove Z_eq_dec e S) h'
  end.

Lemma apply_hist_app : forall h1 S h2, apply_hist S (h1 ++ h2) = apply_hist (apply_hist S h1) h2.
Proof.
  induction h1; auto; simpl; intros.
  destruct a; auto.
  destruct (in_dec _ _ _); auto.
Qed.

(* up *)
Lemma In_remove : forall A (a : A) dec l, incl (remove dec a l) l.
Proof.
  induction l; simpl; auto.
  destruct (dec a a0).
  - apply incl_tl; auto.
  - apply incl_same_head; auto.
Qed.

Lemma remove_sorted : forall a l, sorted l -> sorted (remove Z_eq_dec a l).
Proof.
  induction l; auto; simpl; intro.
  inv H.
  destruct (Z.eq_dec a a0); auto.
  constructor; auto.
  rewrite Forall_forall in *; intros ? Hin.
  apply In_remove in Hin; auto.
Qed.

Lemma apply_hist_sorted : forall h S, sorted S -> sorted (apply_hist S h).
Proof.
  induction h; auto; simpl; intros.
  destruct a.
  - destruct (in_dec _ _ _); auto.
    apply IHh, sort_sorted.
  - apply IHh, remove_sorted; auto.
Qed.

Definition hist := hist_part set_op.

(*Definition q_lock_pred' (t : type) P p (vals : list (val * reptype t)) head (addc remc : val) lock gsh h :=
  !!(Zlength vals <= MAX /\ 0 <= head < MAX /\ consistent h [] vals) &&
  (data_at Tsh tqueue (rotate (complete MAX (map fst vals)) head MAX, (vint (Zlength vals),
                      (vint head, (vint ((head + Zlength vals) mod MAX), (addc, remc))))) p *
   cond_var Tsh addc * cond_var Tsh remc * malloc_token Tsh (sizeof tqueue_t) p *
   malloc_token Tsh (sizeof tcond) addc * malloc_token Tsh (sizeof tcond) remc *
   malloc_token Tsh (sizeof tlock) lock * ghost gsh (Tsh, h) p *
   fold_right sepcon emp (map (fun x => let '(p, v) := x in
     !!(P v) && (data_at Tsh t v p * malloc_token Tsh (sizeof t) p)) vals)).

Definition q_lock_pred A P p lock gsh := EX vals : list (val * reptype A), EX head : Z,
  EX addc : val, EX remc : val, EX h : hist _, q_lock_pred' A P p vals head addc remc lock gsh h.*)

Definition node_lock_inv e p := EX n : val, EX l : val,(*EX h : list set_op,*)
  field_at Tsh tnode [StructField _val] (vint e) p *
  field_at Tsh tnode [StructField _next] n p * field_at Tsh tnode [StructField _lock] l n *
  node_lock_inv.

Definition node_pred sh e p := EX l : val,
  !!((*sepalg.join gsh1 gsh2 Tsh /\*) repable_signed e /\ field_compatible tnode [] p) &&
  (field_at sh tnode [StructField _lock] l p *
   lock_inv sh l (node_lock_inv e p) (* * ghost gsh1 (lsh, h) p*)).

Definition new_node_spec :=
 DECLARE _new_node
  WITH e : Z
  PRE [ _e OF tint ]
   PROP (repable_signed e)
   LOCAL (temp _e (vint e))
   SEP ()
  POST [ tptr tnode ]
   EX p : val,
   PROP ()
   LOCAL (temp ret_temp p)
   SEP (node_pred Tsh e p).

Definition del_node_spec :=
 DECLARE _new_node
  WITH e : Z, p : val
  PRE [ _n OF tptr tnode ]
   PROP ()
   LOCAL (temp _n p)
   SEP (node_pred Tsh e p)
  POST [ tvoid ]
   PROP ()
   LOCAL ()
   SEP ().

Definition tnode_pair := Tstruct _node_pair noattr.

Definition list_inv sh H h := node_pred sh Int.min_signed H * ghost_hist h H.

Definition locate_spec :=
 DECLARE _locate
  WITH e : Z, sh : share, H : val, h : hist
  PRE [ _e OF tint ]
   PROP (repable_signed e)
   LOCAL (temp _e (vint e); gvar _head H)
   SEP (list_inv sh H h)
  POST [ tptr tnode_pair ]
   EX h' : hist, EX p : val, EX n1 : val, EX n2 : val, EX e1 : Z, EX e2 : Z, EX sh : share,
   PROP (incl h h'; e1 < e <= e2)
   LOCAL ()
   SEP (list_inv H h'; data_at Tsh tnode_pair (n1, n2) p; node_pred sh e1 n1;
        field_at Tsh tnode [StructField _val] (vint e1) n1; field_at Tsh tnode [StructField _next] n2 n1;
        node_pred sh e2 n2; node_lock_inv e2 n2).

Definition add_spec :=
 DECLARE _add
  WITH e : Z, H : val, h : hist
  PRE [ _e OF tint ]
   PROP (repable_signed e)
   LOCAL (temp _e (vint e); gvar _head H)
   SEP (list_inv H h)
  POST [ tint ]
   EX h' : hist, EX S : list Z, EX t' : nat,
   PROP (incl h h'; apply_hist [] h' = S)
   LOCAL (temp ret_temp (if in_dec Z_eq_dec e S then 0 else 1))
   SEP (list_inv H (h' ++ [(t', Add e)]).

Definition remove_spec :=
 DECLARE _remove
  WITH e : Z, H : val, h : hist
  PRE [ _e OF tint ]
   PROP (repable_signed e)
   LOCAL (temp _e (vint e); gvar _head H)
   SEP (list_inv H h)
  POST [ tint ]
   EX h' : hist, EX S : list Z, EX t' : nat,
   PROP (incl h h'; apply_hist [] h' = S)
   LOCAL (temp ret_temp (if in_dec Z_eq_dec e S then 1 else 0))
   SEP (list_inv H (h' ++ [(t', Remove e)]).

Definition main_spec :=
 DECLARE _main
  WITH u : unit
  PRE  [] main_pre prog tt nil u
  POST [ tint ] main_post prog nil u.

Definition Gprog : funspecs :=   ltac:(with_library prog [acquire_spec; release_spec; makelock_spec;
  freelock_spec; surely_malloc_spec; new_node_spec; del_node_spec; locate_spec; add_spec; remove_spec; main_spec]).

Lemma body_surely_malloc: semax_body Vprog Gprog f_surely_malloc surely_malloc_spec.
Proof.
  start_function.
  forward_call (* p = malloc(n); *)
     n.
  Intros p.
  forward_if
  (PROP ( )
   LOCAL (temp _p p)
   SEP (malloc_token Tsh n p * memory_block Tsh n p)).
*
  if_tac.
    subst p. entailer!.
    entailer!.
*
    forward_call tt.
    contradiction.
*
    if_tac.
    + forward. subst p. inv H0.
    + Intros. forward. entailer!.
*
  forward. Exists p; entailer!.
Qed.

Lemma ctr_inv_precise : forall p,
  precise (cptr_lock_inv p).
Proof.
  intro; eapply derives_precise, data_at__precise with (sh := Ews)(t := tint); auto.
  intros ? (? & H); apply data_at_data_at_ in H; eauto.
Qed.
#[export] Hint Resolve ctr_inv_precise.

Lemma ctr_inv_positive : forall ctr,
  positive_mpred (cptr_lock_inv ctr).
Proof.
  intro; apply ex_positive; auto.
Qed.
#[export] Hint Resolve ctr_inv_positive.

Lemma body_incr: semax_body Vprog Gprog f_incr incr_spec.
Proof.
  start_function.
  forward.
  forward_call (lock, sh, cptr_lock_inv ctr).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  unfold cptr_lock_inv at 2; simpl.
  Intro z.
  forward.
  forward.
  rewrite field_at_isptr; Intros.
  forward_call (lock, sh, cptr_lock_inv ctr).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  { lock_props.
    unfold cptr_lock_inv; Exists (z + 1); entailer!. }
  forward.
Qed.

Lemma body_read : semax_body Vprog Gprog f_read read_spec.
Proof.
  start_function.
  forward_call (lock, sh, cptr_lock_inv ctr).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  unfold cptr_lock_inv at 2; simpl.
  Intro z.
  forward.
  rewrite data_at_isptr; Intros.
  forward_call (lock, sh, cptr_lock_inv ctr).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  { lock_props.
    unfold cptr_lock_inv; Exists z; entailer!. }
  forward.
  Exists z; entailer!.
Qed.

Lemma body_thread_func : semax_body Vprog Gprog f_thread_func thread_func_spec.
Proof.
  start_function.
  Intros.
  forward.
  forward_call (ctr, sh, lock).
  forward_call (lockt, sh, lock_inv sh lock (cptr_lock_inv ctr), thread_lock_inv sh ctr lock lockt).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  { unfold thread_lock_inv; lock_props.
    rewrite selflock_eq at 2; cancel.
    eapply derives_trans; [apply lock_inv_later | cancel]. }
  forward.
Qed.

Lemma lock_struct : forall p, data_at_ Ews (Tstruct _lock_t noattr) p |-- data_at_ Ews tlock p.
Proof.
  intros.
  unfold data_at_, field_at_; unfold_field_at 1%nat.
  unfold field_at; simpl.
  rewrite field_compatible_cons; simpl; entailer.
  (* temporarily broken *)
Admitted.

Lemma body_main:  semax_body Vprog Gprog f_main main_spec.
Proof.
  name ctr _ctr; name lockt _thread_lock; name lock _ctr_lock.
  start_function.
  forward.
  forward.
  forward.
  forward_call (lock, Ews, cptr_lock_inv ctr).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  { rewrite (sepcon_comm _ (fold_right_sepcon _)); apply sepcon_derives; [cancel | apply lock_struct]. }
  rewrite field_at_isptr; Intros.
  forward_call (lock, Ews, cptr_lock_inv ctr).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  { lock_props.
    unfold cptr_lock_inv; Exists 0; cancel. }
  (* need to split off shares for the locks here *)
  destruct split_Ews as (sh1 & sh2 & ? & ? & Hsh).
  forward_call (lockt, Ews, thread_lock_inv sh1 ctr lock lockt).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  { rewrite (sepcon_comm _ (fold_right_sepcon _)); apply sepcon_derives; [cancel | apply lock_struct]. }
  get_global_function'' _thread_func.
  apply extract_exists_pre; intros f_.
  forward_spawn (val * share * val * val)%type (f_, Vint (Int.repr 0), (ctr, sh1, lock, lockt),
    fun (x : (val * share * val * val)) (_ : val) => let '(ctr, sh, lock, lockt) := x in
         !!readable_share sh && emp * lock_inv sh lock (cptr_lock_inv ctr) *
         lock_inv sh lockt (thread_lock_inv sh ctr lock lockt)).
  { simpl spawn_pre; entailer!.
    Exists _args (fun x : val * share * val * val => let '(ctr, sh, lock, lockt) := x in
      [(_ctr, ctr); (_ctr_lock, lock); (_thread_lock, lockt)]); entailer.
    rewrite !sepcon_assoc; apply sepcon_derives.
    { apply derives_refl'. f_equal.
      unfold NDmk_funspec.
      apply mk_funspec_congr; auto.
      apply eq_JMeq.
      extensionality x x0.
      destruct x0 as (?, (((?, ?), ?), ?)); simpl.
      rewrite <- !sepcon_assoc; reflexivity.  }
    erewrite <- lock_inv_share_join; try apply Hsh; auto.
    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto.
    entailer!. }
  forward_call (ctr, sh2, lock).
  forward_call (lockt, sh2, thread_lock_inv sh1 ctr lock lockt).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  forward_call (ctr, sh2, lock).
  Intro z.
  forward_call (lock, sh2, cptr_lock_inv ctr).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  forward_call (lockt, Ews, sh1, |>lock_inv sh1 lock (cptr_lock_inv ctr), |>thread_lock_inv sh1 ctr lock lockt).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  { unfold thread_lock_inv; lock_props.
    - apply later_positive; auto.
    - unfold rec_inv.
      rewrite selflock_eq at 1.
      rewrite later_sepcon; f_equal.
      apply lock_inv_later_eq.
    - rewrite selflock_eq at 2.
      erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; cancel.
      rewrite sepcon_comm, <- !sepcon_assoc, sepcon_comm.
      apply sepcon_derives; [apply lock_inv_later | cancel]. }
  forward_call (lock, Ews, cptr_lock_inv ctr).
  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }
  { lock_props.
    erewrite sepcon_assoc, lock_inv_share_join; eauto; cancel. }
  forward.
Qed.

Definition extlink := ext_link_prog prog.
Definition Espec := add_funspecs (Concurrent_Espec unit _ extlink) extlink Gprog.
#[export] Existing Instance Espec.

Lemma prog_correct:
  semax_prog prog tt Vprog Gprog.
Proof.
prove_semax_prog.
repeat (apply semax_func_cons_ext_vacuous; [reflexivity | reflexivity | ]).
semax_func_cons_ext.
semax_func_cons_ext.
semax_func_cons_ext.
semax_func_cons_ext.
semax_func_cons_ext.
semax_func_cons_ext.
semax_func_cons_ext.
semax_func_cons body_incr.
semax_func_cons body_read.
semax_func_cons body_thread_func.
semax_func_cons body_main.
Qed.


Require Import Fiat.QueryStructure.Automation.MasterPlan.
Require Import Bedrock.Memory.

Instance : Query_eq (Word.word n) :=
  { A_eq_dec := @Word.weq n }.
Opaque Word.weq.
Opaque Word.natToWord.
Opaque Word.wlt_dec.
Definition WordMax (w w' : W) :=
  if Word.wlt_dec w w' then w' else w.
Definition MaxW (rows : Comp (list W)) : Comp (option W) :=
  FoldAggregateOption WordMax rows.

Definition VALUE := "VALUE".
Definition MEASUREMENT_TYPE := "MEASUREMENT_TYPE".
Definition TIME := "TIME".
Definition CELL_ID := "CELL_ID".

Definition STATE := "STATE".
Definition AREA_CODE := "AREA_CODE".
Definition DETAILS := "DETAILS".
Definition DAY := "DAY".

Definition WIND := 0.
Definition HUMIDITY := 1.
Definition TEMPERATURE := 2.
Definition PRESSURE := 3.

Definition MEASUREMENTS := "MEASUREMENTS".
Definition CELLS := "CELLS".

Definition MeasurementType := W.

Definition WeatherSchema :=
  Query Structure Schema
    [ relation CELLS has
              schema <CELL_ID :: W,
                      AREA_CODE :: W,
                      DETAILS :: W>;
      relation MEASUREMENTS has
              schema <CELL_ID :: W,
                      VALUE :: W,
                      MEASUREMENT_TYPE :: MeasurementType,
                      DAY :: W,
                      TIME :: W> ]
    enforcing [attribute CELL_ID for MEASUREMENTS references CELLS].

(* Try with three tables (distribution of areas per state) *)

Definition Init := "Init".
Definition AddCell := "AddCell".
Definition AddMeasurement := "AddMeasurement".
Definition CountCells := "CountCells".
Definition LocalMax := "LocalMax".

Definition WeatherSpec : ADT _ :=
  Eval simpl in
    Def ADT {
      rep := QueryStructure WeatherSchema,
    Def Constructor0 Init : rep := empty,,

    Def Method1 AddCell (r : rep) (cell : WeatherSchema#CELLS) : rep * bool :=
      Insert cell into r!CELLS,

    Def Method1 AddMeasurement (r : rep) (measurement : WeatherSchema#MEASUREMENTS) : rep * bool :=
      Insert measurement into r!MEASUREMENTS,

    Def Method1 CountCells (r : rep) (area : W) : rep * nat :=
      cnt <- Count (For (cell in r!CELLS)
                        Where (area = cell!AREA_CODE)
                        Return 1);
    ret (r, cnt),

    Def Method2 LocalMax (r : rep) (areaC : W) (measType : MeasurementType) : rep * (option W) :=
      max <- MaxW (For (cell in r!CELLS) (measurement in r!MEASUREMENTS)
            Where (cell!AREA_CODE = areaC)
            Where (measurement!MEASUREMENT_TYPE = measType)
            Where (cell!CELL_ID = measurement!CELL_ID)
            Return measurement!VALUE);
    ret (r, max)
}%methDefParsing.

Definition SharpenedWeatherStation :
  MostlySharpened WeatherSpec.
Proof.
  start sharpening ADT.
  simpl; pose_string_hyps; pose_heading_hyps.
  start_honing_QueryStructure'.
  GenerateIndexesForAll EqExpressionAttributeCounter
  ltac:(fun attrlist =>
          let attrlist' := eval compute in (PickIndexes _ (CountAttributes' attrlist)) in
              make_simple_indexes attrlist'
                                  ltac:(LastCombineCase6 BuildEarlyEqualityIndex)
                                         ltac:(LastCombineCase5 BuildLastEqualityIndex)).
  + plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm
         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.
  + plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm
         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.
  + setoid_rewrite refine_For_rev; simplify with monad laws.
    plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm
         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.
  + setoid_rewrite refine_For_rev; simplify with monad laws.
    plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm
         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.
  + setoid_rewrite refine_For_rev; simplify with monad laws.
    plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm
         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.
  + hone method "AddMeasurement".
    { simpl in *; subst.
      setoid_rewrite refine_Count; simplify with monad laws.
      setoid_rewrite app_nil_r;
        setoid_rewrite map_map; simpl.
      unfold ilist2_hd at 1; simpl.
      setoid_rewrite rev_length.
      setoid_rewrite map_length.
      setoid_rewrite refine_pick_eq'; simplify with monad laws.
      repeat setoid_rewrite refine_If_Then_Else_Bind.
      repeat setoid_rewrite refineEquiv_bind_bind.
      repeat setoid_rewrite refineEquiv_bind_unit; simpl.
      unfold H1.
      eapply refine_under_bind; intros; set_evars.
      rewrite (CallBagFind_fst H0); simpl.
      finish honing.
    }
    hone method "CountCells".
    { simpl in *; subst; simplify with monad laws.
      setoid_rewrite refine_Count; simplify with monad laws.
      unfold H1; eapply refine_under_bind; intros; set_evars.
      rewrite (CallBagFind_fst H0); simpl.
      setoid_rewrite refine_pick_eq'; simplify with monad laws.
      rewrite rev_length.
      rewrite !map_length.
      rewrite app_nil_r; simpl.
      rewrite map_length.
      finish honing.
    }
    hone method "LocalMax".
    { simpl in *; subst; simplify with monad laws.
      unfold H1; eapply refine_under_bind; intros; set_evars.
      rewrite (CallBagFind_fst H0); simpl.
      etransitivity.
      eapply refine_under_bind_both.
      eapply (@Join_Comp_Lists_eq WeatherSchema Index (Fin.FS Fin.F1)).
      intros; finish honing.
      simplify with monad laws.
      unfold H2; apply refine_under_bind; set_evars.
      intros.
      apply Join_Comp_Lists_eq' in H4; rewrite H4.
      setoid_rewrite refine_pick_eq'; simplify with monad laws.
      simpl.
      finish honing.
    }
    simpl.

    simpl; eapply reflexivityT.
  + unfold CallBagFind, CallBagInsert.
    pose_headings_all.
    match goal with
    | |- appcontext[ @BuildADT (IndexedQueryStructure ?Schema ?Indexes) ] =>
      FullySharpenQueryStructure Schema Indexes
    end.

Time Defined.

Time Definition WeatherStationImpl :=
  Eval simpl in (fst (projT1 SharpenedWeatherStation)).
Print WeatherStationImpl.


Require Import Coq.Init.Byte Coq.Strings.Byte Coq.Bool.Bvector.
Require Import Coq.Init.Nat.
Require Import Coq.omega.Omega.

Section HelperDataTypesTypes.

Inductive nibble :=
  |n0
  |n1
  |n2
  |n3
  |n4
  |n5
  |n6
  |n7
  |n8
  |n9
  |na
  |nb
  |nc
  |nd
  |ne
  |nf.

Inductive register :=
  |v0
  |v1
  |v2
  |v3
  |v4
  |v5
  |v6
  |v7
  |v8
  |v9
  |va
  |vb
  |vc
  |vd
  |ve
  |vf.

End HelperDataTypesTypes.

Section HelperDataTypesCode.

Definition n_to_nat (n : nibble) : nat :=
  match n with
  |n0 => 0
  |n1 => 1
  |n2 => 2
  |n3 => 3
  |n4 => 4
  |n5 => 5
  |n6 => 6
  |n7 => 7
  |n8 => 8
  |n9 => 9
  |na => 10
  |nb => 11
  |nc => 12
  |nd => 13
  |ne => 14
  |nf => 15
  end.

Definition nib_eq (n1 n2 : nibble) : bool :=
  eqb (n_to_nat n1) (n_to_nat n2).

Local Notation "0" := false.
Local Notation "1" := true.

Definition bits_to_n (n :  bool * (bool * (bool * bool))) : nibble :=
  match n with
  |(0,(0,(0,0))) => n0
  |(1,(0,(0,0))) => n1
  |(0,(1,(0,0))) => n2
  |(1,(1,(0,0))) => n3
  |(0,(0,(1,0))) => n4
  |(1,(0,(1,0))) => n5
  |(0,(1,(1,0))) => n6
  |(1,(1,(1,0))) => n7
  |(0,(0,(0,1))) => n8
  |(1,(0,(0,1))) => n9
  |(0,(1,(0,1))) => na
  |(1,(1,(0,1))) => nb
  |(0,(0,(1,1))) => nc
  |(1,(0,(1,1))) => nd
  |(0,(1,(1,1))) => ne
  |(1,(1,(1,1))) => nf
  end.

Definition byte_to_nib' (data : byte) : (nibble * nibble) :=
  match to_bits data with
  | (a,(b,(c,(d,(e,(f,(g,h))))))) =>
    let low  := (e,(f,(g,h))) in
    let high := (a,(b,(c,d))) in
    (bits_to_n low, bits_to_n high)
  end.

Definition n_to_bits (n : nibble) : bool * (bool * (bool * bool)) :=
  match n with
    |n0 => (0, (0 ,(0 , 0)))
    |n1 => (1 ,(0 ,(0 , 0)))
    |n2 => (0 ,(1 ,(0 , 0)))
    |n3 => (1 ,(1 ,(0 , 0)))
    |n4 => (0 ,(0 ,(1 , 0)))
    |n5 => (1 ,(0 ,(1 , 0)))
    |n6 => (0 ,(1 ,(1 , 0)))
    |n7 => (1 ,(1 ,(1 , 0)))
    |n8 => (0 ,(0 ,(0 , 1)))
    |n9 => (1 ,(0 ,(0 , 1)))
    |na => (0 ,(1 ,(0 , 1)))
    |nb => (1 ,(1 ,(0 , 1)))
    |nc => (0 ,(0 ,(1 , 1)))
    |nd => (1 ,(0 ,(1 , 1)))
    |ne => (0 ,(1 ,(1 , 1)))
    |nf => (1 ,(1 ,(1 , 1)))
  end.

Definition nib_to_byte (nib_pair : (nibble * nibble)) : byte :=
  match nib_pair with
  | (nHigh, nLow) =>
      let '(a, (b, (c, d))) := n_to_bits nHigh in
      let '(e, (f, (g, h))) := n_to_bits nLow in
        of_bits (e,(f,(g,(h,(a,(b,(c,d)))))))
  end.

Definition byte_to_nib (data : byte) : (nibble * nibble) :=
   match data with
     | x00 => (n0, n0)
     | x01 => (n0, n1)
     | x02 => (n0, n2)
     | x03 => (n0, n3)
     | x04 => (n0, n4)
     | x05 => (n0, n5)
     | x06 => (n0, n6)
     | x07 => (n0, n7)
     | x08 => (n0, n8)
     | x09 => (n0, n9)
     | x0a => (n0, na)
     | x0b => (n0, nb)
     | x0c => (n0, nc)
     | x0d => (n0, nd)
     | x0e => (n0, ne)
     | x0f => (n0, nf)
     | x10 => (n1, n0)
     | x11 => (n1, n1)
     | x12 => (n1, n2)
     | x13 => (n1, n3)
     | x14 => (n1, n4)
     | x15 => (n1, n5)
     | x16 => (n1, n6)
     | x17 => (n1, n7)
     | x18 => (n1, n8)
     | x19 => (n1, n9)
     | x1a => (n1, na)
     | x1b => (n1, nb)
     | x1c => (n1, nc)
     | x1d => (n1, nd)
     | x1e => (n1, ne)
     | x1f => (n1, nf)
     | x20 => (n2, n0)
     | x21 => (n2, n1)
     | x22 => (n2, n2)
     | x23 => (n2, n3)
     | x24 => (n2, n4)
     | x25 => (n2, n5)
     | x26 => (n2, n6)
     | x27 => (n2, n7)
     | x28 => (n2, n8)
     | x29 => (n2, n9)
     | x2a => (n2, na)
     | x2b => (n2, nb)
     | x2c => (n2, nc)
     | x2d => (n2, nd)
     | x2e => (n2, ne)
     | x2f => (n2, nf)
     | x30 => (n3, n0)
     | x31 => (n3, n1)
     | x32 => (n3, n2)
     | x33 => (n3, n3)
     | x34 => (n3, n4)
     | x35 => (n3, n5)
     | x36 => (n3, n6)
     | x37 => (n3, n7)
     | x38 => (n3, n8)
     | x39 => (n3, n9)
     | x3a => (n3, na)
     | x3b => (n3, nb)
     | x3c => (n3, nc)
     | x3d => (n3, nd)
     | x3e => (n3, ne)
     | x3f => (n3, nf)
     | x40 => (n4, n0)
     | x41 => (n4, n1)
     | x42 => (n4, n2)
     | x43 => (n4, n3)
     | x44 => (n4, n4)
     | x45 => (n4, n5)
     | x46 => (n4, n6)
     | x47 => (n4, n7)
     | x48 => (n4, n8)
     | x49 => (n4, n9)
     | x4a => (n4, na)
     | x4b => (n4, nb)
     | x4c => (n4, nc)
     | x4d => (n4, nd)
     | x4e => (n4, ne)
     | x4f => (n4, nf)
     | x50 => (n5, n0)
     | x51 => (n5, n1)
     | x52 => (n5, n2)
     | x53 => (n5, n3)
     | x54 => (n5, n4)
     | x55 => (n5, n5)
     | x56 => (n5, n6)
     | x57 => (n5, n7)
     | x58 => (n5, n8)
     | x59 => (n5, n9)
     | x5a => (n5, na)
     | x5b => (n5, nb)
     | x5c => (n5, nc)
     | x5d => (n5, nd)
     | x5e => (n5, ne)
     | x5f => (n5, nf)
     | x60 => (n6, n0)
     | x61 => (n6, n1)
     | x62 => (n6, n2)
     | x63 => (n6, n3)
     | x64 => (n6, n4)
     | x65 => (n6, n5)
     | x66 => (n6, n6)
     | x67 => (n6, n7)
     | x68 => (n6, n8)
     | x69 => (n6, n9)
     | x6a => (n6, na)
     | x6b => (n6, nb)
     | x6c => (n6, nc)
     | x6d => (n6, nd)
     | x6e => (n6, ne)
     | x6f => (n6, nf)
     | x70 => (n7, n0)
     | x71 => (n7, n1)
     | x72 => (n7, n2)
     | x73 => (n7, n3)
     | x74 => (n7, n4)
     | x75 => (n7, n5)
     | x76 => (n7, n6)
     | x77 => (n7, n7)
     | x78 => (n7, n8)
     | x79 => (n7, n9)
     | x7a => (n7, na)
     | x7b => (n7, nb)
     | x7c => (n7, nc)
     | x7d => (n7, nd)
     | x7e => (n7, ne)
     | x7f => (n7, nf)
     | x80 => (n8, n0)
     | x81 => (n8, n1)
     | x82 => (n8, n2)
     | x83 => (n8, n3)
     | x84 => (n8, n4)
     | x85 => (n8, n5)
     | x86 => (n8, n6)
     | x87 => (n8, n7)
     | x88 => (n8, n8)
     | x89 => (n8, n9)
     | x8a => (n8, na)
     | x8b => (n8, nb)
     | x8c => (n8, nc)
     | x8d => (n8, nd)
     | x8e => (n8, ne)
     | x8f => (n8, nf)
     | x90 => (n9, n0)
     | x91 => (n9, n1)
     | x92 => (n9, n2)
     | x93 => (n9, n3)
     | x94 => (n9, n4)
     | x95 => (n9, n5)
     | x96 => (n9, n6)
     | x97 => (n9, n7)
     | x98 => (n9, n8)
     | x99 => (n9, n9)
     | x9a => (n9, na)
     | x9b => (n9, nb)
     | x9c => (n9, nc)
     | x9d => (n9, nd)
     | x9e => (n9, ne)
     | x9f => (n9, nf)
     | xa0 => (na, n0)
     | xa1 => (na, n1)
     | xa2 => (na, n2)
     | xa3 => (na, n3)
     | xa4 => (na, n4)
     | xa5 => (na, n5)
     | xa6 => (na, n6)
     | xa7 => (na, n7)
     | xa8 => (na, n8)
     | xa9 => (na, n9)
     | xaa => (na, na)
     | xab => (na, nb)
     | xac => (na, nc)
     | xad => (na, nd)
     | xae => (na, ne)
     | xaf => (na, nf)
     | xb0 => (nb, n0)
     | xb1 => (nb, n1)
     | xb2 => (nb, n2)
     | xb3 => (nb, n3)
     | xb4 => (nb, n4)
     | xb5 => (nb, n5)
     | xb6 => (nb, n6)
     | xb7 => (nb, n7)
     | xb8 => (nb, n8)
     | xb9 => (nb, n9)
     | xba => (nb, na)
     | xbb => (nb, nb)
     | xbc => (nb, nc)
     | xbd => (nb, nd)
     | xbe => (nb, ne)
     | xbf => (nb, nf)
     | xc0 => (nc, n0)
     | xc1 => (nc, n1)
     | xc2 => (nc, n2)
     | xc3 => (nc, n3)
     | xc4 => (nc, n4)
     | xc5 => (nc, n5)
     | xc6 => (nc, n6)
     | xc7 => (nc, n7)
     | xc8 => (nc, n8)
     | xc9 => (nc, n9)
     | xca => (nc, na)
     | xcb => (nc, nb)
     | xcc => (nc, nc)
     | xcd => (nc, nd)
     | xce => (nc, ne)
     | xcf => (nc, nf)
     | xd0 => (nd, n0)
     | xd1 => (nd, n1)
     | xd2 => (nd, n2)
     | xd3 => (nd, n3)
     | xd4 => (nd, n4)
     | xd5 => (nd, n5)
     | xd6 => (nd, n6)
     | xd7 => (nd, n7)
     | xd8 => (nd, n8)
     | xd9 => (nd, n9)
     | xda => (nd, na)
     | xdb => (nd, nb)
     | xdc => (nd, nc)
     | xdd => (nd, nd)
     | xde => (nd, ne)
     | xdf => (nd, nf)
     | xe0 => (ne, n0)
     | xe1 => (ne, n1)
     | xe2 => (ne, n2)
     | xe3 => (ne, n3)
     | xe4 => (ne, n4)
     | xe5 => (ne, n5)
     | xe6 => (ne, n6)
     | xe7 => (ne, n7)
     | xe8 => (ne, n8)
     | xe9 => (ne, n9)
     | xea => (ne, na)
     | xeb => (ne, nb)
     | xec => (ne, nc)
     | xed => (ne, nd)
     | xee => (ne, ne)
     | xef => (ne, nf)
     | xf0 => (nf, n0)
     | xf1 => (nf, n1)
     | xf2 => (nf, n2)
     | xf3 => (nf, n3)
     | xf4 => (nf, n4)
     | xf5 => (nf, n5)
     | xf6 => (nf, n6)
     | xf7 => (nf, n7)
     | xf8 => (nf, n8)
     | xf9 => (nf, n9)
     | xfa => (nf, na)
     | xfb => (nf, nb)
     | xfc => (nf, nc)
     | xfd => (nf, nd)
     | xfe => (nf, ne)
     | xff => (nf, nf)
     end.

Definition byte_to_Bvector (b : byte) : Bvector 8 :=
  match to_bits b with
  | (a,(b,(c,(d,(e,(f,(g,h))))))) =>
    [a;b;c;d;e;f;g;h]%vector
  end.

Definition Bvector_to_byte (bv : Bvector 8) : byte :=
  match bv with
    | [a;b;c;d;e;f;g;h]%vector =>
      of_bits (a,(b,(c,(d,(e,(f,(g,h)))))))
    | _ => x00
  end.

Definition word_to_nat_le (bv : (byte * byte)) : nat :=
  match bv with
  | (b1, b2) =>
    let n1 := to_nat b1 in
    let n2 := 256 * (to_nat b2) in
    n1 + n2
  end.

Definition word_to_nat_be (bv : (byte * byte)) : nat :=
  match bv with
  | (b1, b2) => word_to_nat_le (b2, b1)
  end.

Definition nat_to_word_le (n : nat) : (byte * byte) :=
  let d := div n 256 in
  let r := modulo n 256 in
  match of_nat r with
  | None => (x00,x00)
  | Some x1 =>
    match of_nat d with
    | None => (x00,x00)
    | Some x2 => (x1, x2)
    end
  end.

Definition nat_to_word_be (n : nat) : (byte * byte) :=
  let nat_to_le := nat_to_word_le n in
  match nat_to_le with
    (a,b) => (b,a)
  end.

Definition register_to_nib (r : register) :=
  match r with
  |v0 => n0
  |v1 => n1
  |v2 => n2
  |v3 => n3
  |v4 => n4
  |v5 => n5
  |v6 => n6
  |v7 => n7
  |v8 => n8
  |v9 => n9
  |va => na
  |vb => nb
  |vc => nc
  |vd => nd
  |ve => ne
  |vf => nf
  end.

Definition nib_to_byte_low (nib : nibble) :=
  nib_to_byte (n0, nib).

Definition nib_to_byte_high (nib : nibble) :=
  nib_to_byte (nib, n0).

End HelperDataTypesCode.

Section HelperDataTypesProof.

Lemma to_nat_less_256 : forall b,
    to_nat b < 256.
Proof.
  intros.
  destruct b ; simpl ; omega.
Qed.

Lemma word_to_nat_aux : forall b b0,
  of_nat ((to_nat b + to_nat b0 * 256) / 256) = Some b0.
Proof.
  intros. rewrite Nat.div_add ; auto.
  rewrite Nat.div_small ; [|destruct b ; simpl ; omega].
  simpl. apply of_to_nat.
Qed.

Lemma word_to_nat_le_soundness : forall w,
    nat_to_word_le (word_to_nat_le w) = w.
Proof.
  intro w. destruct w.
  unfold word_to_nat_le.
  unfold nat_to_word_le.
  rewrite PeanoNat.Nat.add_mod ; auto.
  specialize (PeanoNat.Nat.mod_mul (to_nat b0) 256) as H.
  rewrite PeanoNat.Nat.mul_comm. rewrite PeanoNat.Nat.mod_mul ; auto.
  destruct b eqn:E ; simpl ; specialize (word_to_nat_aux b) as H' ;
  rewrite E in H' ; simpl in H' ; rewrite H' ; reflexivity.
                                     Qed.

Lemma word_to_nat_be_soundness : forall w,
    nat_to_word_be (word_to_nat_be w) = w.
Proof.
  intro w. destruct w.
  unfold word_to_nat_be.
  unfold nat_to_word_be.
  rewrite word_to_nat_le_soundness. reflexivity.
Qed.

Lemma byte_to_nib_equality : forall b,
    byte_to_nib' b = byte_to_nib b.
Proof.
  intros b.
  destruct b ; auto.
Qed.

Lemma byte_nibble_soundness : forall b,
    byte_to_nib' (nib_to_byte b) = b.
Proof.
  intros b. unfold nib_to_byte. unfold byte_to_nib'.
  destruct b eqn:E. destruct n, n10 ; auto.
Qed.

Theorem byte_to_Bvector_inverse : forall b,
    Bvector_to_byte (byte_to_Bvector b) = b.
Proof.
  intros.
  unfold Bvector_to_byte, byte_to_Bvector.
  destruct b ; simpl ; reflexivity.
Qed.

End HelperDataTypesProof.


Require Import Helix.LLVMGen.Correctness_Prelude.
Require Import Helix.LLVMGen.StateCounters.
Require Import Helix.LLVMGen.Correctness_Invariants.
Require Import Helix.LLVMGen.Correctness_NExpr.

Import ListNotations.

Set Implicit Arguments.
Set Strict Implicit.

Typeclasses Opaque equiv.

Section MExpr.

  Import ProofMode.
  Definition invariant_MExpr
             (e : exp typ) : Rel_cfg_T (mem_block * Int64.int) unit :=
    fun '(memH, (mb, mb_sz)) '(memV, (ρ, (g, _))) =>
      exists (ptr : Addr.addr),
        interp_cfg (translate exp_to_instr (denote_exp (Some DTYPE_Pointer) (convert_typ [] e))) g ρ memV ≈
                   Ret (memV,(ρ,(g,UVALUE_Addr ptr))) /\
        (forall (i : Int64.int) v, mem_lookup (MInt64asNT.to_nat i) mb ≡ Some v -> get_array_cell memV ptr (MInt64asNT.to_nat i) DTYPE_Double ≡ inr (UVALUE_Double v)).

  Record genMExpr_post
         (s1 s2 : IRState)
         exp
         (mi : memoryH) (sti : config_cfg)
         (mf : memoryH * _) (stf : config_cfg_T unit)
    : Prop :=
    {
    _is_pure : is_pure mi sti mf stf;
    get_addr : invariant_MExpr exp mf stf ;
    Gamma_cst : s2 ≡ s1
    }.

  Lemma genMExpr_correct :
    forall (* Compiler bits *) (s1 s2: IRState)
      (* Helix  bits *)   (mexp: MExpr) (σ: evalContext) (memH: memoryH)
      (* Vellvm bits *)   (exp: exp typ) (c: code typ) (g : global_env) (l : local_env) (memV : memoryV) (τ: typ),
      genMExpr mexp s1 ≡ inr (s2, (exp, c, τ)) -> (* Compilation succeeds *)
      state_invariant σ s1 memH (memV, (l, g)) ->
      no_failure (interp_helix (E := E_cfg) (denoteMExpr σ mexp) memH) -> (* Source semantics defined *)
      eutt (succ_cfg
              (
                lift_Rel_cfg (
                    state_invariant σ s2) ⩕
                             genMExpr_post s1 s2 exp memH (memV,(l,g)))
           )
           (interp_helix (denoteMExpr σ mexp) memH)
           (interp_cfg (D.denote_code (convert_typ [] c)) g l memV).
  Proof.
    intros * Hgen INV NOFAIL.
    destruct mexp as [[vid] | mblock]; cbn* in Hgen; simp.
    unfold denoteMExpr, denotePExpr in *; cbn* in *.

    simp; try_abs. subst.
    hvred.
    edestruct memory_invariant_Ptr
      as (bkH & ptrV & Mem_LU & MEM & INLG & EQ); eauto.
    cbn.
    hstep.
    solve_lu.
    hvred.
    apply eutt_Ret; split; [ | split]; cbn; auto.
    eexists; split; eauto.
    break_match_goal; cbn.
    all: vstep; eauto; try reflexivity.
  Qed.

  Lemma genMExpr_array : forall {s1 s2 m e c t},
      genMExpr m s1 ≡ inr (s2, (e, c, t)) ->
      exists sz, t ≡ TYPE_Array sz TYPE_Double.
  Proof.
    intros s1 s2 m e c t H.
    destruct m; cbn in H; inv H.
    simp.
    exists sz.
    reflexivity.
  Qed.

End MExpr.


(**************************************************************************)
(*  This file is part of CertrBPF,                                        *)
(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)
(*                                                                        *)
(*  Copyright (C) 2022 Inria                                              *)
(*                                                                        *)
(*  This program is free software; you can redistribute it and/or modify  *)
(*  it under the terms of the GNU General Public License as published by  *)
(*  the Free Software Foundation; either version 2 of the License, or     *)
(*  (at your option) any later version.                                   *)
(*                                                                        *)
(*  This program is distributed in the hope that it will be useful,       *)
(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)
(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)
(*  GNU General Public License for more details.                          *)
(*                                                                        *)
(**************************************************************************)

From compcert Require Import Memory Memtype Integers Values Ctypes AST.
From Coq Require Import ZArith Lia.

From bpf.comm Require Import Flag rBPFValues Regs BinrBPF State Monad MemRegion rBPFAST rBPFMemType rBPFMonadOp.
From bpf.model Require Import Syntax Decode.

Open Scope Z_scope.
Open Scope monad_scope.

Definition eval_src (s:reg+imm): M state val :=
  match s with
  | inl r => eval_reg r
  | inr i => returnM (Val.longofint (sint32_to_vint i)) (**r the immediate is always int *)
  end.

Definition eval_reg32 (r:reg): M state val :=
  do v <- eval_reg r; returnM (val_intuoflongu v).

Definition eval_src32 (s:reg+imm): M state val :=
  match s with
  | inl r => eval_reg32 r
  | inr i => returnM (sint32_to_vint i) (**r the immediate is always int *)
  end.

(*
Definition _to_vlong (v: val): val :=
  match v with
  | Vlong n => Vlong n (**r Mint64 *)
  | Vint  n => Vlong (Int64.repr (Int.unsigned n)) (**r Mint8unsigned, Mint16unsigned, Mint32 *) (* (u64) v *)
  | _       => Vundef
  end.

Definition vlong_to_vint_or_vlong (chunk: memory_chunk) (v: val): val :=
  match v with
  | Vlong n =>
    match chunk with
    | Mint8unsigned | Mint16unsigned | Mint32 => Vint (Int.repr (Int64.unsigned n))
    | Mint64 => Vlong n
    | _      => Vundef
    end
  | _       => Vundef
  end. *)

Lemma intu_to_long_intu_eq:
  forall i j, i = Vint j -> val_intuoflongu (Val.longofintu i) = i.
Proof.
  unfold Val.longofintu, val_intuoflongu.
  intros.
  rewrite H.
  assert (H1: Int64.unsigned (Int64.repr (Int.unsigned j)) = Int.unsigned j).
  - apply Int64.unsigned_repr.
    assert (Hrange: 0 <= Int.unsigned j <= Int.max_unsigned). { apply Int.unsigned_range_2. }
    assert (Hmax: Int.max_unsigned <= Int64.max_unsigned).
    + unfold Int.max_unsigned, Int64.max_unsigned.
    unfold Int.modulus, Int64.modulus.
    unfold Int.wordsize, Int64.wordsize.
    unfold Wordsize_32.wordsize, Wordsize_64.wordsize.
    simpl.
    lia.
    + lia.
  - rewrite H1.
    apply f_equal.
    apply Int.repr_unsigned.
Qed.
Close Scope Z_scope.

Definition val_intuoflonguM (vl: val) : M state val := returnM (val_intuoflongu vl).

Definition step_alu_binary_operation (a: arch) (bop: binOp) (d :reg) (s: reg+imm): M state unit :=
  match a with
  | A32 =>
    do d32 <- eval_reg32 d;
    do s32 <- eval_src32 s; (**r (u32) DST, (u32) SRC/IMM *)
    match bop with
    | BPF_ADD  => upd_reg d (Val.longofintu (Val.add  d32 s32))
    | BPF_SUB  => upd_reg d (Val.longofintu (Val.sub  d32 s32))
    | BPF_MUL  => upd_reg d (Val.longofintu (Val.mul  d32 s32))
    | BPF_DIV  => if comp_ne_32 s32 Vzero then (** run-time checking *)
                    match Val.divu d32 s32 with (**r Val.divu... *)
                    | Some res => upd_reg d (Val.longofintu res)
                    | None     => errorM
                    end
                  else
                    upd_flag BPF_ILLEGAL_DIV
    | BPF_OR   => upd_reg d (Val.longofintu (Val.or   d32 s32))
    | BPF_AND  => upd_reg d (Val.longofintu (Val.and  d32 s32))
    | BPF_LSH  => if compu_lt_32 s32 (Vint (Int.repr 32)) then
                    upd_reg d (Val.longofintu (Val.shl d32 s32))
                  else
                    upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shl d s' is 's > 32', then there is a acceptable error *)
    | BPF_RSH  => if compu_lt_32 s32 (Vint (Int.repr 32)) then
                    upd_reg d (Val.longofintu (Val.shru d32 s32))
                  else
                    upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shru d s' is 's > 32', then there is a acceptable error *)
    | BPF_MOD  => if comp_ne_32 s32 Vzero then (** run-time checking *)
                    match Val.modu d32 s32 with
                    | Some res => upd_reg d (Val.longofintu res)
                    | None     => errorM
                    end
                  else
                    upd_flag BPF_ILLEGAL_DIV
    | BPF_XOR  => upd_reg d (Val.longofintu (Val.xor  d32 s32))
    | BPF_MOV  => upd_reg d (Val.longofintu s32)
    | BPF_ARSH => if compu_lt_32 s32 (Vint (Int.repr 32)) then
                    upd_reg d (Val.longofint (Val.shr  d32 s32))
                  else
                    upd_flag BPF_ILLEGAL_SHIFT (**r if 's' of 'shr d s' is 's > 32', then there is a acceptable error *)
    end
  | A64 =>
      do d64 <- eval_reg d;
      do s64 <- eval_src s;
      match bop with
      | BPF_ADD  => upd_reg d (Val.addl  d64 s64)
      | BPF_SUB  => upd_reg d (Val.subl  d64 s64)
      | BPF_MUL  => upd_reg d (Val.mull  d64 s64)
      | BPF_DIV  => if compl_ne s64 val64_zero then (** run-time checking *)
                      match Val.divlu d64 s64 with (**r run-time checking *)
                      | Some res => upd_reg d res
                      | None     => errorM
                      end
                    else
                      upd_flag BPF_ILLEGAL_DIV
      | BPF_OR   => upd_reg d (Val.orl   d64 s64)
      | BPF_AND  => upd_reg d (Val.andl  d64 s64)
      (**r we must do type-checking of 's64' first, to ensure it is exactly 'vint' *)
      | BPF_LSH  => if compu_lt_32 (val_intuoflongu s64) (Vint (Int.repr 64)) then
                      upd_reg d (Val.shll d64 (val_intuoflongu s64))
                    else
                      upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shl d s' is 's > 64', then there is a acceptable error *)
      | BPF_RSH  => if compu_lt_32 (val_intuoflongu s64) (Vint (Int.repr 64)) then
                      upd_reg d (Val.shrlu d64 (val_intuoflongu s64))
                    else
                      upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shr d s' is 's > 64', then there is a acceptable error *)
      | BPF_MOD  => if compl_ne s64 val64_zero then (** run-time checking *)
                      match Val.modlu d64 s64 with (**r run-time checking *)
                      | Some res => upd_reg d res
                      | None     => errorM
                      end
                    else
                      upd_flag BPF_ILLEGAL_DIV
(**r to avoid translate option type to C, the refinement version defines a new division:
Definition val64_divlu (x y: val): val :=
  match Val.divlu x y with
  | Some res => res
  | None => Vundef
  end.
And the semantics function does:
  | op_BPF_DIV64   =>
    if compl_ne src64 val64_zero then
      do _ <- upd_reg dst (val64_divlu dst64 src64);
        upd_flag BPF_OK
    else
      upd_flag BPF_ILLEGAL_DIV

 *)
      | BPF_XOR  => upd_reg d (Val.xorl  d64 s64)
      | BPF_MOV  => upd_reg d s64
      | BPF_ARSH => if compu_lt_32 (val_intuoflongu s64) (Vint (Int.repr 64)) then
                      upd_reg d (Val.shrl d64 (val_intuoflongu s64))
                    else
                      upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shru d s' is 's > 64', then there is a acceptable error? *)
      end
  end.

Definition step_branch_cond (c: cond) (d: reg) (s: reg+imm): M state bool :=
  do dst <- eval_reg d;
  do src <- eval_src s;
  returnM (match c with
  | Eq  => compl_eq   dst src
  | SEt => complu_set dst src
  | Ne  => compl_ne   dst src
  | Gt sign =>
    match sign with
    | Unsigned => complu_gt dst src
    | Signed   => compl_gt  dst src
    end
  | Ge sign =>
    match sign with
    | Unsigned => complu_ge dst src
    | Signed   => compl_ge  dst src
    end
  | Lt sign =>
    match sign with
    | Unsigned => complu_lt dst src
    | Signed   => compl_lt  dst src
    end
  | Le sign =>
    match sign with
    | Unsigned => complu_le dst src
    | Signed   => compl_le  dst src
    end
  end).

Definition get_add (x y: val): M state val := returnM (Val.add x y).

Definition get_sub (x y: val): M state val := returnM (Val.sub x y).

Definition get_addr_ofs (x: val) (ofs: int): M state val := returnM (val_intuoflongu (Val.addl x (Val.longofint (sint32_to_vint ofs)))).

Definition get_start_addr (mr: memory_region): M state val := returnM (start_addr mr).

Definition get_block_size (mr: memory_region): M state val := returnM (block_size mr).

Definition get_block_perm (mr: memory_region): M state permission := returnM (block_perm mr).

Definition is_well_chunk_bool (chunk: memory_chunk) : M state bool :=
  match chunk with
  | Mint8unsigned | Mint16unsigned | Mint32 | Mint64 => returnM true
  | _ => returnM false
  end.

Definition check_mem_aux2 (mr: memory_region) (perm: permission) (addr: val) (chunk: memory_chunk): M state val := (*
  do well_chunk <- is_well_chunk_bool chunk;
    if well_chunk then *)
  do start  <- get_start_addr mr;
  do size   <- get_block_size mr;
  do mr_perm  <- get_block_perm mr;
  do lo_ofs <- get_sub addr start;
  do hi_ofs <- get_add lo_ofs (memory_chunk_to_valu32 chunk);
    if andb (andb
              (compu_lt_32 hi_ofs size)
              (andb (compu_le_32 lo_ofs (memory_chunk_to_valu32_upbound chunk))
                    (comp_eq_32 Vzero (val32_modu lo_ofs (memory_chunk_to_valu32 chunk)))))
            (perm_ge mr_perm perm) then
            returnM (Val.add (block_ptr mr) lo_ofs) (**r Vptr b lo_ofs *)
    else
      returnM Vnullptr. (*
    else
      returnM Vnullptr. *)

Fixpoint check_mem_aux (num: nat) (perm: permission) (chunk: memory_chunk) (addr: val) (mrs: MyMemRegionsType) {struct num}: M state val :=
  match num with
  | O => returnM Vnullptr
  | S n =>
    do cur_mr   <- get_mem_region n mrs;
    do check_mem <- check_mem_aux2 cur_mr perm addr chunk;
    do is_null   <- cmp_ptr32_nullM check_mem;
      if is_null then
        check_mem_aux n perm chunk addr mrs
      else
        returnM check_mem
  end.

Definition check_mem (perm: permission) (chunk: memory_chunk) (addr: val): M state val :=
  do well_chunk <- is_well_chunk_bool chunk;
    if well_chunk then
      do mem_reg_num <- eval_mrs_num;
      do mrs      <- eval_mrs_regions;
      do check_mem <- check_mem_aux mem_reg_num perm chunk addr mrs;
      do is_null   <- cmp_ptr32_nullM check_mem;
        if is_null then
          returnM Vnullptr
        else
          returnM check_mem
    else
      returnM Vnullptr.

Definition step_load_x_operation (chunk: memory_chunk) (d:reg) (s:reg) (ofs:off): M state unit :=
  do m    <- eval_mem;
  do mrs  <- eval_mem_regions;
  do sv   <- eval_reg s;
  do addr <- get_addr_ofs sv ofs;
  do ptr  <- check_mem Readable chunk addr;
  do is_null   <- cmp_ptr32_nullM ptr;
    if is_null then
      upd_flag BPF_ILLEGAL_MEM
    else
      do v <- load_mem chunk ptr;
      do _ <- upd_reg d v; returnM tt
.

Definition step_store_operation (chunk: memory_chunk) (d: reg) (s: reg+imm) (ofs: off): M state unit :=
  do m    <- eval_mem;
  do mrs  <- eval_mem_regions;
  do dv   <- eval_reg d;
  do addr <- get_addr_ofs dv ofs;

    match s with
    | inl r =>
      do src <- eval_reg r;
      do ptr  <- check_mem Writable chunk addr;
      do is_null   <- cmp_ptr32_nullM ptr;
        if is_null then
          upd_flag BPF_ILLEGAL_MEM
        else
          do _ <- store_mem_reg ptr chunk src; returnM tt
    | inr i =>
      do ptr  <- check_mem Writable chunk addr;
      do is_null   <- cmp_ptr32_nullM ptr;
        if is_null then
          upd_flag BPF_ILLEGAL_MEM
        else
          do _ <- store_mem_imm ptr chunk (sint32_to_vint i); returnM tt
    end
.

Definition decodeM (i: int64) : M state instruction := fun st =>
  match (decode i) with
  | Some ins => Some (ins, st)
  | None => None
  end.

Definition get_immediate (ins:int64): M state int := returnM (get_immediate ins).

Definition step : M state unit :=
  do pc   <- eval_pc;
  do ins64<- eval_ins pc;
  do ins  <- decodeM ins64;
    match ins with
    | BPF_NEG a d =>
      match a with
      | A32 => do d32 <- eval_reg d;
                 upd_reg d (Val.longofintu (Val.neg (val_intuoflongu d32)))
      | A64 => do d64 <- eval_reg d;
                 upd_reg d (Val.negl d64)
      end

    | BPF_BINARY a bop d s =>
      step_alu_binary_operation a bop d s

    | BPF_JA ofs => upd_pc (Int.add pc ofs)
    | BPF_JUMP c d s ofs =>
      do cond <- step_branch_cond c d s;
      if cond then
        upd_pc (Int.add pc ofs)
      else
        returnM tt

    | BPF_LDDW_low d i =>
      do _   <- upd_reg d (Val.longofintu (sint32_to_vint i));
        returnM tt
    | BPF_LDDW_high d i =>
      do d64 <- eval_reg d;
      do _   <- upd_reg d (Val.orl d64 (Val.shll  (Val.longofintu (sint32_to_vint i)) (sint32_to_vint (Int.repr 32))));
        returnM tt
    | BPF_LDX chunk d s ofs =>
      step_load_x_operation chunk d s ofs
    | BPF_ST chunk d s ofs =>
      step_store_operation chunk d s ofs

    | BPF_CALL i => (**r TODO: is this type-casting correct? this style is because of DxInstructions... *)
      do f_ptr    <- _bpf_get_call (Vint ((Int.repr (Int64.unsigned (Int64.repr (Int.signed i))))));
      do is_null  <- cmp_ptr32_nullM f_ptr;
        if is_null then
          upd_flag BPF_ILLEGAL_CALL
        else
          do res  <- exec_function f_ptr;
            upd_reg R0 (Val.longofintu res)
    | BPF_RET    => upd_flag BPF_SUCC_RETURN
    | BPF_ERR    => upd_flag BPF_ILLEGAL_INSTRUCTION
    end.

Fixpoint bpf_interpreter_aux (fuel: nat) {struct fuel}: M state unit :=
  match fuel with
  | O => upd_flag BPF_ILLEGAL_LEN
  | S fuel0 =>
    do len  <- eval_ins_len;
    do pc <- eval_pc;
      if (Int.ltu pc len) then (**r pc < len: pc is less than the length of l *)
        do _ <- step;
        do f <- eval_flag;
          if flag_eq f BPF_OK then
            do len0 <- eval_ins_len;
            do pc0 <- eval_pc; (**r step may modify pc: lddw *)
              if (Int.ltu (Int.add pc0 Int.one) len0) then (**r pc + 1 < len *)
                do _ <- upd_pc_incr;
                  bpf_interpreter_aux fuel0
              else
                upd_flag BPF_ILLEGAL_LEN
          else
            returnM tt
      else
        upd_flag BPF_ILLEGAL_LEN
  end.

Definition bpf_interpreter (fuel: nat): M state val :=
  do _        <- bpf_interpreter_aux fuel;
  do f        <- eval_flag;
    if flag_eq f BPF_SUCC_RETURN then
      do res  <- eval_reg R0;
        returnM res
    else
      returnM val64_zero.

Close Scope monad_scope.


(* an omega groupoid is an omega cat *)
Require Import ssreflect ssrfun ssrbool .

From Modules Require Import HomotopicalEquality untypeduippackrl TypesAreOmegaGroupoids.FunctionalRelation lib Syntax WfSyntaxBrunerieOnlyContr gtype decl omegagroupoids fullomegagroupoids WfSyntaxBrunerieAllCtx.
Set Bullet Behavior "Strict Subproofs".

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

Local Notation "⟦ X ⟧V" := (dTm (w_va X)).

Module B := WfSyntaxBrunerieOnlyContr.
Module FB := WfSyntaxBrunerieAllCtx.

Local Notation SB := (B.syntax).
Local Notation SF := (FB.syntax).

Module Syn := Syntax.
Local Notation "'WC' S" := (@Syn.WC _ S) (at level 0).
Local Notation "'WTy' S" := (@Syn.WTy _ S)(at level 0).
Local Notation "'Wtm' S":= (@Syn.Wtm _ S)(at level 0).
Local Notation "'WS' S":= (@Syn.WS _ S)(at level 0).
Local Notation "'SF_WVar' S":= (FB.WVar S)(at level 0).
Local Notation "'SB_WVar' S":= (B.WVar S)(at level 0).
(*
Local Notation WTy := (@Syn.WTy _).
Local Notation Wtm := (@Syn.Wtm _).
Local Notation WS := (@Syn.WS _).
Local Notation SC_WVar := (WfSyntaxEricSamOnlyPs.WVar).
Local Notation SB_WVar := (WfSyntaxBrunerieOnlyContr.WVar).
*)

(*
Indépendemment du pb d'équivalence dont je parle ensuite, de toute manière, je suis obligé de
redéfinir par récurrence l'interprétation de FB à partir de l'interprétation de B. Donc,
il faut un inductif pour la relation fonctionnelle, etc...

Est-ce que ça vaut le coup de définir une bonne fois pour toute le schéma d'élimination ?

Maintenant, pour transformer un modèle de B (Brunerie) vers FB (full brunerie), je suis confronté au
pb suivant :
- pour B, ⟦ (x : * ) ⟧ = Σ_(γ : ⊤) | G |
- pour FB, ⟦ (x : * ) ⟧ = | G |

Ce qui est un peu relou. Les deux types sont équivalents mais pas égaux strictement.
Du coup j'ai 2 solutions :

+ changer la def de ce que c'est un omega groupoide en demandant non pas une égalité mais une équivalence.
Appelons cette définition une déf wild. Par contre, on demande ⟦ σ , t ⟧ = ⟦ σ ⟧, ⟦ t ⟧ strictement.
Mais pour l'équivalence, on utilise quelle égalité ??

+ avoir les 2 définitions, et montrer qu'un omega groupoide wild induit un omega groupoide normal.

Autre idée :
imposer qu'un omega groupoide s'interpréte dans GhSet plutôt que GType.
En quoi un type est un omega groupoide ? Etant donné un GType G, on peut considérer sa troncation G'
où tous les obj ont été tronqués au niveau hSet. On a un morphisme
Je ne pense pas qu'on puisse tronquer ainsi un GType.

--------------
Il faudrait montrer qu'un omega groupoide sur G induit un omega groupoide sur G'

Mais plus généralement, si on a un morphisme de type globulaire G₁ → G₂, si G₁ est un omega groupoide,
G₂ ne l'est-il pas également ?

Si ça marche, alors pas besoin de 2TT pour la def d'omega groupoide., mais besoin d'une troncation hSet.

Est-ce légitime de demander des égalités strites dans la def d'omega groupoides ? Oui, ou alors il faut demander à ce que le type globulaire est un hset. Mais alors comment montrer que les types sont
des omega groupoides ? Peut-on se passer de 2TT ainsi ? Pas sûr. Mais au moins, cette nouvelle def
serait moins chiante (avec l'axiome d'univalence, ou alors sans mais en demandant une équivalence plutôt qu'une égalité) pour montrer ce que je veux dans ce fichier.

Mais puis je me passer de 2TT ?

Ce qui vient après est idiot. J'avais oublié que isEquiv(f) est hprop mais pas Equiv(A,B)
-----------------------------------------------------------
Notion d'égalité hétérogène hprop dans hott :
t : A, u : B
t ≅ u := ∀ (P : ∀ X:Type, X -> Type), P A t ~ P B u
où '~' est l'équivalence hprop isEquiv
t ≅ u -> A ~ B et t ~ u par cette equivalence (prendre P X x = X ~ B et e(x) = b)

Mais alors, false ≅ true avec cette égalité.

Peut on donner une définition sans 2TT d'un omega groupoide avec cette égalité malgré tout ?

 *)

Fixpoint wCB_C (Γ : Con) (wΓ : WC SC Γ) : WC SB Γ
with wCB_T Γ A (wA : WTy SC Γ A) : WTy SB Γ A
with wCB_Tm Γ A t (wt : Wtm SC Γ A t) : Wtm SB Γ A t
with wCB_V Γ A x (wx : SC_WVar Γ A x) : SB_WVar Γ A x
with wCB_S Γ Δ σ (wσ : WS SC Γ Δ σ) : WS SB Γ Δ σ.
  - destruct wΓ.
    + constructor.
    + constructor.
      * apply:wCB_C => //.
      * apply:wCB_T => //.
      * constructor.
        apply:wCB_V => //.
  - destruct wA.
    + constructor.
      apply:wCB_C => //.
    + constructor.
      * apply:wCB_T => //.
      * apply:wCB_Tm => //.
      * apply:wCB_Tm => //.
  - destruct wt.
    + constructor.
      by apply:wCB_V => //.
    + constructor.
      * apply:wCB_C => //.
      * apply:wCB_T => //.
      * apply:wCB_S => //.
    + rewrite -/((ar  A t u).[σ]T).
      constructor.
      * apply:wCB_C => //.
      * constructor.
        -- apply:wCB_T => //.
        -- apply:wCB_Tm => //.
        -- apply:wCB_Tm => //.
      * apply:wCB_S => //.
 - destruct wx.
   + constructor.
   + constructor.
     * apply:wCB_V => //.
     * apply:wCB_Tm => //.
   + constructor.
     apply:wCB_Tm => //.
   + constructor.
     apply:wCB_Tm => //.
 - destruct wσ.
   + constructor.
     apply:wCB_Tm => //.
   + constructor.
      * apply:wCB_S => //.
      * apply:wCB_T => //.
      * apply:wCB_Tm => //.
      * apply:wCB_Tm => //.
      * apply:wCB_Tm => //.
Defined.

Section GroupoidToCat.
  Context (d : @Decl _ SB).

  Definition d' : @Decl _ SC :=
    {|
      dC := fun Γ  (wΓ : Syn.WC Γ) => ⟦ wCB_C wΓ ⟧C;
      dTy := fun (Γ : Con) (A : Ty) (wΓ : Syn.WC Γ) (wA : Γ ⊢ A) => ⟦ wCB_T wA ⟧T;
      dTm := fun (Γ : Con) (A : Ty) (t : Tm) (wΓ : Syn.WC Γ) (wt : Γ ⊢ t : A) (wA : Γ ⊢ A) =>
               ⟦ wCB_Tm wt ⟧t (wCB_T wA);
      dS := fun (Γ Δ : Con) (σ : sub) (wσ : WfSyntaxEricSamOnlyPs.WS Γ Δ σ) (wΓ : WfSyntaxEricSamOnlyPs.WC Γ) (wΔ : WfSyntaxEricSamOnlyPs.WC Δ) =>
              ⟦ wCB_S wσ ⟧S (wCB_C wΓ)(wCB_C wΔ) |}.

  Import omegagroupoids.
  Lemma isGroupoid_isCat (G : GType)  (gr : isOmegaGroupoid G d) : isOmegaCategory G d'.
    constructor.
    - by apply:dC_astar.
    - intros.
      apply:(dC_ext gr).
    - intros.
      apply:(dT_star gr).
    - intros.
      apply:(dT_ar gr).
    - intros.
      simpl.
      apply:JMeq_trans; last by apply:(sb_dTm gr).
      match goal with
        [ |- ⟦ ?w1 ⟧t ?w2 γ ≅ ⟦ ?w3 ⟧t ?w4 γ ] =>
        rewrite (WTm_hp w1 w3) (WTy_hp w2 w4)
      end.
      easy.
    - apply:(dTm_vstar gr).
    - intros; apply:(dTm_v1 gr).
      eassumption.
    - intros; apply:(dTm_v0 gr) => //.
    - intros; apply:(dTm_vwk gr) => //.
      eassumption.
    - intros;apply:(dS_to_star gr) => //.
    - intros;apply:(dS_to_ext gr) => //.
      exact:H.
      exact:H0.
      exact:H1.
  Qed.

End GroupoidToCat.


From iris.base_logic.lib Require Export fancy_updates.
From iris.program_logic Require Export language.
From iris.bi Require Export weakestpre.
From iris.proofmode Require Import base tactics classes.
Set Default Proof Using "Type".
Import uPred.

Class irisG' (Λstate : Type) (Σ : gFunctors) := IrisG {
  iris_invG :> invG Σ;
  state_interp : Λstate → iProp Σ;
}.
Notation irisG Λ Σ := (irisG' (state Λ) Σ).
Global Opaque iris_invG.

Definition wp_pre `{irisG Λ Σ} (s : stuckness)
    (wp : coPset -c> expr Λ -c> (val Λ -c> iProp Σ) -c> iProp Σ) :
    coPset -c> expr Λ -c> (val Λ -c> iProp Σ) -c> iProp Σ := λ E e1 Φ,
  match to_val e1 with
  | Some v => |={E}=> Φ v
  | None => ∀ σ1,
     state_interp σ1 ={E,∅}=∗ ⌜if s is NotStuck then reducible e1 σ1 else True⌝ ∗
     ∀ e2 σ2 efs, ⌜prim_step e1 σ1 e2 σ2 efs⌝ ={∅,∅,E}▷=∗
       state_interp σ2 ∗ wp E e2 Φ ∗
       [∗ list] ef ∈ efs, wp ⊤ ef (λ _, True)
  end%I.

Local Instance wp_pre_contractive `{irisG Λ Σ} s : Contractive (wp_pre s).
Proof.
  rewrite /wp_pre=> n wp wp' Hwp E e1 Φ.
  repeat (f_contractive || f_equiv); apply Hwp.
Qed.

Definition wp_def `{irisG Λ Σ} (s : stuckness) :
  coPset → expr Λ → (val Λ → iProp Σ) → iProp Σ := fixpoint (wp_pre s).
Definition wp_aux `{irisG Λ Σ} : seal (@wp_def Λ Σ _). by eexists. Qed.
Instance wp' `{irisG Λ Σ} : Wp Λ (iProp Σ) stuckness := wp_aux.(unseal).
Definition wp_eq `{irisG Λ Σ} : wp = @wp_def Λ Σ _ := wp_aux.(seal_eq).

Section wp.
Context `{irisG Λ Σ}.
Implicit Types s : stuckness.
Implicit Types P : iProp Σ.
Implicit Types Φ : val Λ → iProp Σ.
Implicit Types v : val Λ.
Implicit Types e : expr Λ.

(* Weakest pre *)
Lemma wp_unfold s E e Φ :
  WP e @ s; E {{ Φ }} ⊣⊢ wp_pre s (wp (PROP:=iProp Σ)  s) E e Φ.
Proof. rewrite wp_eq. apply (fixpoint_unfold (wp_pre s)). Qed.

Global Instance wp_ne s E e n :
  Proper (pointwise_relation _ (dist n) ==> dist n) (wp (PROP:=iProp Σ) s E e).
Proof.
  revert e. induction (lt_wf n) as [n _ IH]=> e Φ Ψ HΦ.
  rewrite !wp_unfold /wp_pre.
  (* FIXME: figure out a way to properly automate this proof *)
  (* FIXME: reflexivity, as being called many times by f_equiv and f_contractive
  is very slow here *)
  do 18 (f_contractive || f_equiv). apply IH; first lia.
  intros v. eapply dist_le; eauto with lia.
Qed.
Global Instance wp_proper s E e :
  Proper (pointwise_relation _ (≡) ==> (≡)) (wp (PROP:=iProp Σ) s E e).
Proof.
  by intros Φ Φ' ?; apply equiv_dist=>n; apply wp_ne=>v; apply equiv_dist.
Qed.

Lemma wp_value' s E Φ v : Φ v ⊢ WP of_val v @ s; E {{ Φ }}.
Proof. iIntros "HΦ". rewrite wp_unfold /wp_pre to_of_val. auto. Qed.
Lemma wp_value_inv' s E Φ v : WP of_val v @ s; E {{ Φ }} ={E}=∗ Φ v.
Proof. by rewrite wp_unfold /wp_pre to_of_val. Qed.

Lemma wp_strong_mono s1 s2 E1 E2 e Φ Ψ :
  s1 ⊑ s2 → E1 ⊆ E2 →
  WP e @ s1; E1 {{ Φ }} -∗ (∀ v, Φ v ={E2}=∗ Ψ v) -∗ WP e @ s2; E2 {{ Ψ }}.
Proof.
  iIntros (? HE) "H HΦ". iLöb as "IH" forall (e E1 E2 HE Φ Ψ).
  rewrite !wp_unfold /wp_pre.
  destruct (to_val e) as [v|] eqn:?.
  { iApply ("HΦ" with "[> -]"). by iApply (fupd_mask_mono E1 _). }
  iIntros (σ1) "Hσ". iMod (fupd_intro_mask' E2 E1) as "Hclose"; first done.
  iMod ("H" with "[$]") as "[% H]".
  iModIntro. iSplit; [by destruct s1, s2|]. iIntros (e2 σ2 efs Hstep).
  iMod ("H" with "[//]") as "H". iIntros "!> !>". iMod "H" as "($ & H & Hefs)".
  iMod "Hclose" as "_". iModIntro. iSplitR "Hefs".
  - iApply ("IH" with "[//] H HΦ").
  - iApply (big_sepL_impl with "[$Hefs]"); iIntros "!#" (k ef _) "H".
    by iApply ("IH" with "[] H").
Qed.

Lemma fupd_wp s E e Φ : (|={E}=> WP e @ s; E {{ Φ }}) ⊢ WP e @ s; E {{ Φ }}.
Proof.
  rewrite wp_unfold /wp_pre. iIntros "H". destruct (to_val e) as [v|] eqn:?.
  { by iMod "H". }
  iIntros (σ1) "Hσ1". iMod "H". by iApply "H".
Qed.
Lemma wp_fupd s E e Φ : WP e @ s; E {{ v, |={E}=> Φ v }} ⊢ WP e @ s; E {{ Φ }}.
Proof. iIntros "H". iApply (wp_strong_mono s s E with "H"); auto. Qed.

Lemma wp_atomic s E1 E2 e Φ `{!Atomic (stuckness_to_atomicity s) e} :
  (|={E1,E2}=> WP e @ s; E2 {{ v, |={E2,E1}=> Φ v }}) ⊢ WP e @ s; E1 {{ Φ }}.
Proof.
  iIntros "H". rewrite !wp_unfold /wp_pre.
  destruct (to_val e) as [v|] eqn:He.
  { by iDestruct "H" as ">>> $". }
  iIntros (σ1) "Hσ". iMod "H". iMod ("H" $! σ1 with "Hσ") as "[$ H]".
  iModIntro. iIntros (e2 σ2 efs Hstep).
  iMod ("H" with "[//]") as "H". iIntros "!>!>". iMod "H" as "(Hphy & H & $)". destruct s.
  - rewrite !wp_unfold /wp_pre. destruct (to_val e2) as [v2|] eqn:He2.
    + iDestruct "H" as ">> $". by iFrame.
    + iMod ("H" with "[$]") as "[H _]". iDestruct "H" as %(? & ? & ? & ?).
      by edestruct (atomic _ _ _ _ Hstep).
  - destruct (atomic _ _ _ _ Hstep) as [v <-%of_to_val].
    iMod (wp_value_inv' with "H") as ">H". iFrame "Hphy". by iApply wp_value'.
Qed.

Lemma wp_step_fupd s E1 E2 e P Φ :
  to_val e = None → E2 ⊆ E1 →
  (|={E1,E2}▷=> P) -∗ WP e @ s; E2 {{ v, P ={E1}=∗ Φ v }} -∗ WP e @ s; E1 {{ Φ }}.
Proof.
  rewrite !wp_unfold /wp_pre. iIntros (-> ?) "HR H".
  iIntros (σ1) "Hσ". iMod "HR". iMod ("H" with "[$]") as "[$ H]".
  iIntros "!>" (e2 σ2 efs Hstep). iMod ("H" $! e2 σ2 efs with "[% //]") as "H".
  iIntros "!>!>". iMod "H" as "($ & H & $)".
  iMod "HR". iModIntro. iApply (wp_strong_mono s s E2 with "H"); [done..|].
  iIntros (v) "H". by iApply "H".
Qed.

Lemma wp_bind K `{!LanguageCtx K} s E e Φ :
  WP e @ s; E {{ v, WP K (of_val v) @ s; E {{ Φ }} }} ⊢ WP K e @ s; E {{ Φ }}.
Proof.
  iIntros "H". iLöb as "IH" forall (E e Φ). rewrite wp_unfold /wp_pre.
  destruct (to_val e) as [v|] eqn:He.
  { apply of_to_val in He as <-. by iApply fupd_wp. }
  rewrite wp_unfold /wp_pre fill_not_val //.
  iIntros (σ1) "Hσ". iMod ("H" with "[$]") as "[% H]". iModIntro; iSplit.
  { iPureIntro. destruct s; last done.
    unfold reducible in *. naive_solver eauto using fill_step. }
  iIntros (e2 σ2 efs Hstep).
  destruct (fill_step_inv e σ1 e2 σ2 efs) as (e2'&->&?); auto.
  iMod ("H" $! e2' σ2 efs with "[//]") as "H". iIntros "!>!>".
  iMod "H" as "($ & H & $)". by iApply "IH".
Qed.

Lemma wp_bind_inv K `{!LanguageCtx K} s E e Φ :
  WP K e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ v, WP K (of_val v) @ s; E {{ Φ }} }}.
Proof.
  iIntros "H". iLöb as "IH" forall (E e Φ). rewrite !wp_unfold /wp_pre.
  destruct (to_val e) as [v|] eqn:He.
  { apply of_to_val in He as <-. by rewrite !wp_unfold /wp_pre. }
  rewrite fill_not_val //.
  iIntros (σ1) "Hσ". iMod ("H" with "[$]") as "[% H]". iModIntro; iSplit.
  { destruct s; eauto using reducible_fill. }
  iIntros (e2 σ2 efs Hstep).
  iMod ("H" $! (K e2) σ2 efs with "[]") as "H"; [by eauto using fill_step|].
  iIntros "!>!>". iMod "H" as "($ & H & $)". by iApply "IH".
Qed.

(** * Derived rules *)
Lemma wp_mono s E e Φ Ψ : (∀ v, Φ v ⊢ Ψ v) → WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ Ψ }}.
Proof.
  iIntros (HΦ) "H"; iApply (wp_strong_mono with "H"); auto.
  iIntros (v) "?". by iApply HΦ.
Qed.
Lemma wp_stuck_mono s1 s2 E e Φ :
  s1 ⊑ s2 → WP e @ s1; E {{ Φ }} ⊢ WP e @ s2; E {{ Φ }}.
Proof. iIntros (?) "H". iApply (wp_strong_mono with "H"); auto. Qed.
Lemma wp_stuck_weaken s E e Φ :
  WP e @ s; E {{ Φ }} ⊢ WP e @ E ?{{ Φ }}.
Proof. apply wp_stuck_mono. by destruct s. Qed.
Lemma wp_mask_mono s E1 E2 e Φ : E1 ⊆ E2 → WP e @ s; E1 {{ Φ }} ⊢ WP e @ s; E2 {{ Φ }}.
Proof. iIntros (?) "H"; iApply (wp_strong_mono with "H"); auto. Qed.
Global Instance wp_mono' s E e :
  Proper (pointwise_relation _ (⊢) ==> (⊢)) (wp (PROP:=iProp Σ) s E e).
Proof. by intros Φ Φ' ?; apply wp_mono. Qed.

Lemma wp_value s E Φ e v : IntoVal e v → Φ v ⊢ WP e @ s; E {{ Φ }}.
Proof. intros <-. by apply wp_value'. Qed.
Lemma wp_value_fupd' s E Φ v : (|={E}=> Φ v) ⊢ WP of_val v @ s; E {{ Φ }}.
Proof. intros. by rewrite -wp_fupd -wp_value'. Qed.
Lemma wp_value_fupd s E Φ e v `{!IntoVal e v} :
  (|={E}=> Φ v) ⊢ WP e @ s; E {{ Φ }}.
Proof. intros. rewrite -wp_fupd -wp_value //. Qed.
Lemma wp_value_inv s E Φ e v : IntoVal e v → WP e @ s; E {{ Φ }} ={E}=∗ Φ v.
Proof. intros <-. by apply wp_value_inv'. Qed.

Lemma wp_frame_l s E e Φ R : R ∗ WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ v, R ∗ Φ v }}.
Proof. iIntros "[? H]". iApply (wp_strong_mono with "H"); auto with iFrame. Qed.
Lemma wp_frame_r s E e Φ R : WP e @ s; E {{ Φ }} ∗ R ⊢ WP e @ s; E {{ v, Φ v ∗ R }}.
Proof. iIntros "[H ?]". iApply (wp_strong_mono with "H"); auto with iFrame. Qed.

Lemma wp_frame_step_l s E1 E2 e Φ R :
  to_val e = None → E2 ⊆ E1 →
  (|={E1,E2}▷=> R) ∗ WP e @ s; E2 {{ Φ }} ⊢ WP e @ s; E1 {{ v, R ∗ Φ v }}.
Proof.
  iIntros (??) "[Hu Hwp]". iApply (wp_step_fupd with "Hu"); try done.
  iApply (wp_mono with "Hwp"). by iIntros (?) "$$".
Qed.
Lemma wp_frame_step_r s E1 E2 e Φ R :
  to_val e = None → E2 ⊆ E1 →
  WP e @ s; E2 {{ Φ }} ∗ (|={E1,E2}▷=> R) ⊢ WP e @ s; E1 {{ v, Φ v ∗ R }}.
Proof.
  rewrite [(WP _ @ _; _ {{ _ }} ∗ _)%I]comm; setoid_rewrite (comm _ _ R).
  apply wp_frame_step_l.
Qed.
Lemma wp_frame_step_l' s E e Φ R :
  to_val e = None → ▷ R ∗ WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ v, R ∗ Φ v }}.
Proof. iIntros (?) "[??]". iApply (wp_frame_step_l s E E); try iFrame; eauto. Qed.
Lemma wp_frame_step_r' s E e Φ R :
  to_val e = None → WP e @ s; E {{ Φ }} ∗ ▷ R ⊢ WP e @ s; E {{ v, Φ v ∗ R }}.
Proof. iIntros (?) "[??]". iApply (wp_frame_step_r s E E); try iFrame; eauto. Qed.

Lemma wp_wand s E e Φ Ψ :
  WP e @ s; E {{ Φ }} -∗ (∀ v, Φ v -∗ Ψ v) -∗ WP e @ s; E {{ Ψ }}.
Proof.
  iIntros "Hwp H". iApply (wp_strong_mono with "Hwp"); auto.
  iIntros (?) "?". by iApply "H".
Qed.
Lemma wp_wand_l s E e Φ Ψ :
  (∀ v, Φ v -∗ Ψ v) ∗ WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ Ψ }}.
Proof. iIntros "[H Hwp]". iApply (wp_wand with "Hwp H"). Qed.
Lemma wp_wand_r s E e Φ Ψ :
  WP e @ s; E {{ Φ }} ∗ (∀ v, Φ v -∗ Ψ v) ⊢ WP e @ s; E {{ Ψ }}.
Proof. iIntros "[Hwp H]". iApply (wp_wand with "Hwp H"). Qed.
End wp.

(** Proofmode class instances *)
Section proofmode_classes.
  Context `{irisG Λ Σ}.
  Implicit Types P Q : iProp Σ.
  Implicit Types Φ : val Λ → iProp Σ.

  Global Instance frame_wp p s E e R Φ Ψ :
    (∀ v, Frame p R (Φ v) (Ψ v)) →
    Frame p R (WP e @ s; E {{ Φ }}) (WP e @ s; E {{ Ψ }}).
  Proof. rewrite /Frame=> HR. rewrite wp_frame_l. apply wp_mono, HR. Qed.

  Global Instance is_except_0_wp s E e Φ : IsExcept0 (WP e @ s; E {{ Φ }}).
  Proof. by rewrite /IsExcept0 -{2}fupd_wp -except_0_fupd -fupd_intro. Qed.

  Global Instance elim_modal_bupd_wp p s E e P Φ :
    ElimModal True p false (|==> P) P (WP e @ s; E {{ Φ }}) (WP e @ s; E {{ Φ }}).
  Proof.
    by rewrite /ElimModal intuitionistically_if_elim
      (bupd_fupd E) fupd_frame_r wand_elim_r fupd_wp.
  Qed.

  Global Instance elim_modal_fupd_wp p s E e P Φ :
    ElimModal True p false (|={E}=> P) P (WP e @ s; E {{ Φ }}) (WP e @ s; E {{ Φ }}).
  Proof.
    by rewrite /ElimModal intuitionistically_if_elim
      fupd_frame_r wand_elim_r fupd_wp.
  Qed.

  Global Instance elim_modal_fupd_wp_atomic p s E1 E2 e P Φ :
    Atomic (stuckness_to_atomicity s) e →
    ElimModal True p false (|={E1,E2}=> P) P
            (WP e @ s; E1 {{ Φ }}) (WP e @ s; E2 {{ v, |={E2,E1}=> Φ v }})%I.
  Proof.
    intros. by rewrite /ElimModal intuitionistically_if_elim
      fupd_frame_r wand_elim_r wp_atomic.
  Qed.

  Global Instance add_modal_fupd_wp s E e P Φ :
    AddModal (|={E}=> P) P (WP e @ s; E {{ Φ }}).
  Proof. by rewrite /AddModal fupd_frame_r wand_elim_r fupd_wp. Qed.

  Global Instance elim_acc_wp {X} E1 E2 α β γ e s Φ :
    Atomic (stuckness_to_atomicity s) e →
    ElimAcc (X:=X) (fupd E1 E2) (fupd E2 E1)
            α β γ (WP e @ s; E1 {{ Φ }})
            (λ x, WP e @ s; E2 {{ v, |={E2}=> β x ∗ (γ x -∗? Φ v) }})%I.
  Proof.
    intros ?. rewrite /ElimAcc.
    iIntros "Hinner >Hacc". iDestruct "Hacc" as (x) "[Hα Hclose]".
    iApply (wp_wand with "[Hinner Hα]"); first by iApply "Hinner".
    iIntros (v) ">[Hβ HΦ]". iApply "HΦ". by iApply "Hclose".
  Qed.

  Global Instance elim_acc_wp_nonatomic {X} E α β γ e s Φ :
    ElimAcc (X:=X) (fupd E E) (fupd E E)
            α β γ (WP e @ s; E {{ Φ }})
            (λ x, WP e @ s; E {{ v, |={E}=> β x ∗ (γ x -∗? Φ v) }})%I.
  Proof.
    rewrite /ElimAcc.
    iIntros "Hinner >Hacc". iDestruct "Hacc" as (x) "[Hα Hclose]".
    iApply wp_fupd.
    iApply (wp_wand with "[Hinner Hα]"); first by iApply "Hinner".
    iIntros (v) ">[Hβ HΦ]". iApply "HΦ". by iApply "Hclose".
  Qed.
End proofmode_classes.