From sflib Require Import sflib.
From Paco Require Import paco.

From PromisingLib Require Import Axioms.
From PromisingLib Require Import Basic.
From PromisingLib Require Import Loc.
From PromisingLib Require Import DataStructure.
From PromisingLib Require Import DenseOrder.
From PromisingLib Require Import Language.
From PromisingLib Require Import Event.

Require Import Time.
Require Import View.
Require Import BoolMap.
Require Import Promises.
Require Import Cell.
Require Import Memory.
Require Import Global.
Require Import TView.
Require Import Local.
Require Import Thread.
Require Import Configuration.

Require Import SimLocal.
Require Import SimMemory.
Require Import SimGlobal.
Require Import SimThread.
Require Import Compatibility.

Require Import SimLocalAdvance.

Require Import ITreeLang.
Require Import ITreeLib.

Set Implicit Arguments.

Variant split_release: forall R (i1: MemE.t R) (i2: MemE.t R), Prop :=
| split_release_store
    l v:
    split_release (MemE.write l v Ordering.acqrel) (MemE.write l v Ordering.strong_relaxed)
| split_release_update
    l rmw or
    (OR: Ordering.le or Ordering.strong_relaxed):
    split_release (MemE.update l rmw or Ordering.acqrel) (MemE.update l rmw or Ordering.strong_relaxed)
.

Variant sim_released: forall R
                        (st_src:(Language.state (lang R))) (lc_src:Local.t) (gl1_src:Global.t)
                        (st_tgt:(Language.state (lang R))) (lc_tgt:Local.t) (gl1_tgt:Global.t), Prop :=
| sim_released_intro
    R
    (i_src i_tgt: MemE.t R)
    lc1_src gl1_src
    lc1_tgt gl1_tgt
    (SPLIT: split_release i_src i_tgt)
    (LOCAL: sim_local lc1_src lc1_tgt)
    (RELEASED: forall l, View.le (TView.cur (Local.tview lc1_tgt)) ((TView.rel (Local.tview lc1_tgt)) l))
    (GLOBAL: sim_global gl1_src gl1_tgt)
    (LC_WF_SRC: Local.wf lc1_src gl1_src)
    (LC_WF_TGT: Local.wf lc1_tgt gl1_tgt)
    (GL_WF_SRC: Global.wf gl1_src)
    (GL_WF_TGT: Global.wf gl1_tgt):
    sim_released
      (Vis i_src (fun r => Ret r)) lc1_src gl1_src
      (Vis i_tgt (fun r => Ret r)) lc1_tgt gl1_tgt
.

Lemma sim_released_mon
      R
      st_src lc_src gl1_src
      st_tgt lc_tgt gl1_tgt
      gl2_src
      gl2_tgt
      (SIM1: sim_released st_src lc_src gl1_src
                          st_tgt lc_tgt gl1_tgt)
      (GLOBAL: sim_global gl2_src gl2_tgt)
      (LC_WF_SRC: Local.wf lc_src gl2_src)
      (LC_WF_TGT: Local.wf lc_tgt gl2_tgt)
      (GL_WF_SRC: Global.wf gl2_src)
      (GL_WF_TGT: Global.wf gl2_tgt):
  @sim_released R
                st_src lc_src gl2_src
                st_tgt lc_tgt gl2_tgt.
Proof.
  destruct SIM1. econs; eauto.
Qed.

Lemma sim_released_step
      R
      st1_src lc1_src gl1_src
      st1_tgt lc1_tgt gl1_tgt
      (SIM: @sim_released R
                          st1_src lc1_src gl1_src
                          st1_tgt lc1_tgt gl1_tgt):
  _sim_thread_step (lang R) (lang R)
                   ((@sim_thread (lang R) (lang R) (sim_terminal eq)) \6/ @sim_released R)
                   st1_src lc1_src gl1_src
                   st1_tgt lc1_tgt gl1_tgt.
Proof.
  destruct SIM. ii.
  inv STEP_TGT; [|inv LOCAL0; destruct SPLIT; ss; dependent destruction STATE].
  - (* internal *)
    right.
    exploit Local.internal_step_future; eauto. i. des.
    exploit sim_local_internal; try exact LOCAL; eauto. i. des.
    exploit Local.internal_step_future; eauto. i. des.
    esplits; try exact GL2; eauto.
    + inv LOCAL0; ss.
    + right. econs; eauto.
      inv LOCAL0; inv LOCAL1; ss.
  - (* update-load *)
    right.
    exploit sim_local_read; try exact LOCAL1; eauto; try refl. i. des.
    esplits.
    + ss.
    + refl.
    + econs 2. econs 2; [|econs 2]; eauto. econs; eauto.
    + ss.
    + ss.
    + left. eapply paco9_mon; [apply sim_itree_ret|]; ss.
  - (* write *)
    right.
    hexploit sim_local_write_released; try exact LOCAL1; eauto; try refl.
    { by rewrite <- View.join_l. }
    i. des.
    esplits.
    + ss.
    + refl.
    + econs 2. econs 2; [|econs 3]; eauto. econs. refl.
    + ss.
    + ss.
    + left. eapply paco9_mon; [apply sim_itree_ret|]; ss.
  - (* update *)
    right.
    exploit sim_local_update_released; try exact LOCAL1; try exact LOCAL2; eauto; try refl. i. des.
    esplits.
    + ss.
    + refl.
    + econs 2. econs 2; [|econs 4]; eauto. econs; eauto.
    + ss.
    + ss.
    + left. eapply paco9_mon; [apply sim_itree_ret|]; ss.
  - (* racy read *)
    right.
    exploit sim_local_racy_read; try exact LOCAL1; eauto; try refl. i. des.
    esplits.
    + ss.
    + refl.
    + econs 2. econs 2; [|econs 8]; eauto. econs; eauto.
    + ss.
    + ss.
    + left. eapply paco9_mon; [apply sim_itree_ret|]; ss.
  - (* racy write *)
    left.
    exploit sim_local_racy_write_released; try exact LOCAL1; eauto. i. des.
    econs; try refl.
    + econs 2; [|econs 9]; eauto. econs; eauto.
    + ss.
  - (* racy update *)
    left.
    exploit sim_local_racy_update_released; try exact LOCAL1; eauto. i. des.
    econs; try refl.
    + econs 2; [|econs 10]; eauto. econs; eauto.
    + ss.
Qed.

Lemma sim_released_sim_thread R:
  @sim_released R <6= @sim_thread (lang R) (lang R) (sim_terminal eq).
Proof.
  pcofix CIH. i. pfold. ii. ss. splits; ss; ii.
  - inv TERMINAL_TGT. inv PR; ss.
  - right. esplits; eauto.
    inv PR. eapply sim_local_promises_bot; eauto.
  - exploit sim_released_mon; eauto. i.
    exploit sim_released_step; eauto. i. des; eauto.
    + right. esplits; eauto.
      left. eapply paco9_mon; eauto. ss.
    + right. esplits; eauto.
Qed.

Lemma split_release_sim_itree R
      (i_src i_tgt: MemE.t R)
      (SPLIT: split_release i_src i_tgt):
  sim_itree eq
            (ITree.trigger i_src)
            (ITree.trigger (MemE.fence Ordering.plain Ordering.acqrel);; ITree.trigger i_tgt).
Proof.
  replace (ITree.trigger i_src) with (Vis i_src (fun r => Ret r)).
  2: { unfold ITree.trigger. grind. }
  replace (ITree.trigger (MemE.fence Ordering.plain Ordering.acqrel);; ITree.trigger i_tgt) with
      (Vis (MemE.fence Ordering.plain Ordering.acqrel) (fun _ => Vis i_tgt (fun r => Ret r))).
  2: { unfold ITree.trigger. grind. repeat f_equal. extensionality u. grind. }
  pcofix CIH. ii. subst. pfold. ii. splits; ii.
  { inv TERMINAL_TGT. eapply f_equal with (f:=observe) in H; ss. }
  { right. esplits; eauto.
    eapply sim_local_promises_bot; eauto.
  }
  right.
  inv STEP_TGT; ss.
  - (* internal *)
    exploit sim_local_internal; eauto. i. des.
    esplits; try apply GL2; eauto; ss.
    inv LOCAL0; ss.
  - (* fence *)
    inv LOCAL0; dependent destruction STATE.
    exploit Local.fence_step_future; eauto. i. des.
    esplits.
    + ss.
    + refl.
    + econs 1.
    + ss.
    + exploit Local.fence_step_non_sc; eauto. i. subst. ss.
    + left. eapply paco9_mon; [apply sim_released_sim_thread|]; ss.
      inv LOCAL1. econs; eauto.
      * inv LOCAL. econs; ss. etrans; eauto.
      * s. i. repeat condtac; ss. refl.
      * inv GLOBAL. econs; ss.
Qed.


(* *********************************************************************)
(*                                                                     *)
(*            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: PThread                                  *)
(*                                                                     *)
(*          Provide the initialization and primtives of thread         *)
(*                                                                     *)
(*          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 PThread layer,
which will introduce the primtives of thread*)
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.

(** * 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 -> AbTCBStrong_range (abtcb abd);
        valid_TDQ: pg abd = true -> AbQCorrect_range (abq abd);
        valid_notinQ: pg abd = true -> NotInQ (AC abd) (abtcb abd);
        valid_count: pg abd = true -> QCount (abtcb abd) (abq abd);
        valid_inQ: pg abd = true -> InQ (abtcb abd) (abq abd);
        valid_curid: 0 <= cid abd < num_proc;
        correct_curid: pg abd = true -> CurIDValid (cid abd) (AC abd) (abtcb abd);
        single_curid: pg abd = true -> SingleRun (cid abd) (abtcb abd)

      }.

  (** ** Definition of the abstract state ops *)
  Global Instance pthread_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.
      - repeat rewrite ZMap.gi; intuition.
    Qed.

    (** ** Definition of the abstract state *)
    Global Instance pthread_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.
        - intros; apply NotInQ_gso_true; auto.
        - intros; apply CurIDValid_gss_ac; auto.
      Qed.

      Lemma alloc_low_level_inv:
        forall d d' n i 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.
          - apply NotInQ_gso_true; auto.
          - apply CurIDValid_gss_ac; auto.
        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 sched_init_inv: PreservesInvariants sched_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_abtcb_strong_range'; eauto.
      - apply real_abq_range; auto.
      - eapply real_abtcb_pb_notInQ'; eauto.
      - eapply real_abtcb_abq_QCount'; eauto.
      - eapply real_abq_tcb_inQ; eauto.
      - omega.
      - eapply real_abtcb_AC_CurIDValid; eauto.
      - eapply real_abtcb_SingleRun; eauto.
    Qed.

    Global Instance thread_wakeup_inv: PreservesInvariants thread_wakeup_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      - eapply AbTCBStrong_range_gss_READY; eauto.
      - eapply AbQCorrect_range_gss_wakeup; eauto.
      - eapply NotInQ_InQ_gss_wakeup; eauto.
      - eapply QCount_gss_wakeup; eauto.
      - eapply InQ_gss_wakeup; eauto.
      - eapply CurIDValid_gso_tcb; eauto.
        eapply last_neq_cid; eauto. omega.
      - eapply SingleRun_gso_state_READY; eauto.
    Qed.

    Global Instance thread_spawn_inv: DNewInvariants thread_spawn_spec.
    Proof.
      constructor; intros; inv H0;
      unfold thread_spawn_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.
        + eapply AbTCBStrong_range_gss_READY; eauto.
        + eapply AbQCorrect_range_gss_enqueue; eauto.
        + unfold update_cusage, update_cchildren; apply NotInQ_gso_ac_true; eauto.
          zmap_simpl; repeat apply NotInQ_gso_true; auto.
        + eapply QCount_gss_spawn; eauto.
          eapply AbTCBStrong_range_impl; eauto.
          split; [|split; [|eauto]].
          assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.
          apply cvalid_unused_next_child; auto.
        + eapply InQ_gss_spawn; eauto.
          eapply AbTCBStrong_range_impl; eauto.
          split; [|split; [|eauto]].
          assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.
          apply cvalid_unused_next_child; auto.
        + unfold update_cusage, update_cchildren; apply CurIDValid_gso_neq_true; auto.
          zmap_simpl; repeat apply CurIDValid_gss_ac; auto.
          assert (Hneq:= cvalid_child_id_neq _ valid_container0 _ Hdestruct3); zmap_simpl.
          apply cvalid_unused_next_child; auto.
        + eapply SingleRun_gso_state_READY; eauto.
    Qed.

    Local Opaque remove.

    Global Instance thread_yield_inv: ThreadScheduleInvariants thread_yield_spec.
    Proof.
      constructor; intros; functional inversion H.
      - inv H1. constructor; trivial.
        eapply kctxt_inject_neutral_gss_mem; eauto.
      - inv H0. subst.
        assert (HOS: 0<= num_chan <= num_chan) by omega.
        exploit last_range_AbQ; eauto. intros Hrange.
        constructor; auto; simpl in *; intros; try congruence.
        + eapply AbTCBStrong_range_gss_RUN; eauto.
          eapply AbTCBStrong_range_gss_READY; eauto.
        + eapply AbQCorrect_range_gss_remove'; eauto.
          eapply list_range_enqueue; eauto.
          eapply AbQCorrect_range_impl; eauto.
        + eapply NotInQ_gso_neg; eauto.
          eapply NotInQ_gso_ac; eauto.
          eapply correct_curid0; eauto.
        + eapply QCount_gss_yield; eauto.
        + eapply InQ_gss_yield; eauto.
        + eapply CurIDValid_gss_last; eauto.
        + eapply SingleRun_gss_gso_cid; eauto. congruence.
    Qed.

    Global Instance thread_sleep_inv: ThreadTransferInvariants thread_sleep_spec.
    Proof.
      constructor; intros; functional inversion H.
      - inv H1. constructor; trivial.
        eapply kctxt_inject_neutral_gss_mem; eauto.
      - inv H0. subst.
        assert (HOS: 0<= num_chan <= num_chan) by omega.
        assert (HNeq: 64 <> n') by omega.
        exploit last_range_AbQ; eauto. intros Hrange.
        assert (HOS': 0 <= n' <= num_proc) by omega.
        assert (Hcid: ZMap.get (cid d) (abtcb d) = AbTCBValid RUN (-1))
          by (eapply correct_curid0; eauto).
        constructor; auto; simpl in *; intros; try congruence.
        + eapply AbTCBStrong_range_gss_RUN; eauto.
          eapply AbTCBStrong_range_gss_SLEEP; eauto.
        + eapply AbQCorrect_range_gss_remove; eauto.
          * eapply AbQCorrect_range_gss_enqueue; eauto.
          * rewrite ZMap.gso; eauto.
        + eapply NotInQ_gso_neg; eauto.
          eapply NotInQ_gso_ac; eauto.
          eapply correct_curid0; eauto.
        + eapply QCount_gss_remove; eauto.
          * eapply QCount_gss_enqueue; eauto.
          * rewrite ZMap.gso; eauto.
        + eapply InQ_gss_remove; eauto.
          * eapply InQ_gss_enqueue; eauto.
          * eapply QCount_gss_enqueue; eauto.
          * rewrite ZMap.gso; eauto.
          * apply last_correct; eauto.
        + eapply CurIDValid_gss_last; eauto.
        + eapply SingleRun_gss_gso_cid; eauto. congruence.
    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 pthread_fresh : compatlayer (cdata RData) :=
    thread_yield ↦ primcall_thread_schedule_compatsem thread_yield_spec (prim_ident:= thread_yield)
                 ⊕ thread_sleep ↦ primcall_thread_transfer_compatsem thread_sleep_spec.

  Definition pthread_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
          ⊕ shared_mem_status ↦ gensem shared_mem_status_spec
          ⊕ offer_shared_mem ↦ gensem offer_shared_mem_spec
          ⊕ get_state ↦ gensem get_state0_spec
          ⊕ get_curid ↦ gensem get_curid_spec
          ⊕ thread_spawn ↦ dnew_compatsem thread_spawn_spec
          ⊕ thread_wakeup ↦ gensem thread_wakeup_spec
          ⊕ sched_init ↦ gensem sched_init_spec

          ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)
          ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)
          ⊕ 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
          ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.

  Definition pthread : compatlayer (cdata RData) := pthread_fresh ⊕ pthread_passthrough.

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

End WITHMEM.


Require Import Wellfounded CoqlibC Maps AST Linking.
Require Import Integers ValuesC Memory Events Smallstep Globalenvs.
Require Import Switch Registers Cminor Op CminorSelC RTLC.
Require Import RTLgen RTLgenspec.
Require Import sflib.
(** newly added **)
Require Export RTLgenproof.
Require Import Simulation.
Require Import Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem AsmregsC MatchSimModSem.
Require SimMemExt.
Require SoundTop.

Set Implicit Arguments.

Section SIMMODSEM.

Variable skenv_link: SkEnv.t.
Variable sm_link: SimMem.t.
Variable prog: CminorSel.program.
Variable tprog: RTL.program.
Let md_src: Mod.t := (CminorSelC.module prog).
Let md_tgt: Mod.t := (RTLC.module tprog).
Hypothesis (INCLSRC: SkEnv.includes skenv_link (Mod.sk md_src)).
Hypothesis (INCLTGT: SkEnv.includes skenv_link (Mod.sk md_tgt)).
Hypothesis (WF: SkEnv.wf skenv_link).

Hypothesis TRANSL: match_prog prog tprog.
Let ge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_src)) prog).
Let tge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_tgt)) tprog).
Definition msp: ModSemPair.t := ModSemPair.mk (md_src skenv_link) (md_tgt skenv_link) (SimSymbId.mk md_src md_tgt) sm_link.

Inductive match_states
          (idx: nat * nat) (st_src0: CminorSel.state) (st_tgt0: RTL.state) (sm0: SimMem.t): Prop :=
| match_states_intro
    (MATCHST: RTLgenproof.match_states st_src0 st_tgt0)
    (MCOMPATSRC: (CminorSelC.get_mem st_src0) = sm0.(SimMem.src))
    (MCOMPATTGT: (get_mem st_tgt0) = sm0.(SimMem.tgt))
    (MEASRUE: idx = measure_state st_src0).

Theorem make_match_genvs :
  SimSymbId.sim_skenv (SkEnv.project skenv_link (Mod.sk md_src))
                      (SkEnv.project skenv_link (Mod.sk md_tgt)) ->
  Genv.match_genvs (match_globdef (fun cu f tf => transl_fundef f = Errors.OK tf) eq prog) ge tge.
Proof. subst_locals. eapply SimSymbId.sim_skenv_revive; eauto. Qed.

Let SEGESRC: senv_genv_compat skenv_link ge. Proof. eapply SkEnv.senv_genv_compat; et. Qed.
Let SEGETGT: senv_genv_compat skenv_link tge. Proof. eapply SkEnv.senv_genv_compat; et. Qed.

Inductive match_states_at: Cminor.state -> CminorSel.state -> SimMem.t -> SimMem.t -> Prop :=
| match_states_at_intro
    fptr sg vs k m st_tgt sm_at sm_arg
    (ATEXT: Genv.find_funct ge fptr = None):
    match_states_at (Cminor.Callstate fptr sg vs k m) st_tgt sm_at sm_arg.

Theorem sim_modsem: ModSemPair.sim msp.
Proof.
  eapply match_states_sim with (match_states := match_states) (match_states_at := top4);
    eauto; ii; ss.
  - eapply wf_lex_ord; eauto; apply lt_wf.
  - eapply SoundTop.sound_state_local_preservation; eauto.
  - (* init bsim *)
    destruct sm_arg; ss. clarify.
    inv INITTGT. inv SIMARGS; ss. clarify.
    exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE. des.
    eexists. eexists (SimMemExt.mk _ _). esplits; eauto.
    + econs; eauto; ss.
      * inv TYP. rpapply match_callstate; eauto.
        { econs; eauto. }
        { eapply lessdef_list_typify_list; try apply VALS; eauto. rewrite <- LEN.
          symmetry. eapply lessdef_list_length; eauto. }
        folder. inv SAFESRC. inv TYP.
        exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. folder.
        inv FPTR; ss.
        rr in H0. des. ss. unfold Errors.bind in *. des_ifs.
        unfold fundef in *. clarify.
        assert(SGEQ: CminorSel.fn_sig fd0 = fn_sig fd).
        { destruct fd0; ss. unfold transl_function in *. ss. unfold bind in *. des_ifs. }
        f_equal; try congruence.
  - (* init progress *)
    des. inv SAFESRC. inv SIMARGS; ss. inv FPTR; ss.
    exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE.
    exploit (Genv.find_funct_match_genv SIMGE); eauto. i; des. ss. unfold bind in *. folder. des_ifs.
    inv TYP. rr in H0. des. ss. unfold Errors.bind in *. des_ifs.
    assert(SGEQ: (CminorSel.fn_sig fd) = f.(fn_sig)).
    { destruct fd; ss. unfold transl_function in *. ss. unfold bind in *. des_ifs. }
    esplits; eauto. econs; eauto.
    + ss. rewrite <- SGEQ. ss.
    + econs; eauto with congruence.
      erewrite <- lessdef_list_length; eauto. etrans; eauto with congruence.
    + erewrite <- lessdef_list_length; eauto. etrans; eauto with congruence.
  - (* call wf *)
    inv MATCH; ss. destruct sm0; ss. clarify. u in CALLSRC. des. inv CALLSRC. inv MATCHST; ss.
  - (* call fsim *)
    inv MATCH; ss. destruct sm0; ss. clarify.
    inv CALLSRC. inv MATCHST; ss; cycle 1.
    folder. esplits; eauto.
    + econs; eauto.
      * folder. des. r in TRANSL. r in TRANSL.
        exploit (SimSymbId.sim_skenv_revive TRANSL); eauto.
        { apply SIMSKENV. }
        intro GE. apply (fsim_external_funct_id GE); ss.
        folder. inv FPTR; ss.
      * des. esplits; eauto. eapply SimSymb.simskenv_func_fsim; eauto; ss. unfold Sk.get_csig in *. des_ifs.
    + econs; ss; eauto.
      * instantiate (1:= SimMemExt.mk _ _). ss.
      * ss.
    + ss.
  - (* after fsim *)
    inv AFTERSRC. inv SIMRET; ss. exists sm_ret. destruct sm_ret; ss. clarify.
    inv MATCH; ss. inv MATCHST; ss. esplits; eauto.
    + econs; eauto.
    + econs; ss; eauto. econs; eauto.
      eapply lessdef_typify; ss.
  - (* final fsim *)
    inv MATCH. inv FINALSRC; inv MATCHST; ss.
    inv MS. destruct sm0; ss. clarify.
    eexists (SimMemExt.mk _ _). esplits; ss; eauto. econs; eauto.
  - left; i. esplits; eauto.
    { apply CminorSelC.modsem_receptive; et. }
    inv MATCH. ii. hexploit (@transl_step_correct prog skenv_link skenv_link); eauto.
    { inv SIMSKENV. ss. }
    { apply make_match_genvs; eauto. apply SIMSKENV. }
    i; des_safe. folder. des.
    + esplits; eauto.
      * left. eapply ModSemProps.spread_dplus; et. apply modsem_determinate; et.
      * instantiate (1:= (SimMemExt.mk _ _)). ss.
    + clarify. esplits; eauto.
      * right. esplits; eauto. { instantiate (1:= R2). eapply ModSemProps.spread_dstar; eauto. eapply modsem_determinate; eauto. }
      * instantiate (1:= (SimMemExt.mk _ _)). ss.
Unshelve.
  all: ss. apply msp.
Qed.

End SIMMODSEM.

Section SIMMOD.

Variable prog: CminorSel.program.
Variable tprog: RTL.program.
Hypothesis TRANSL: match_prog prog tprog.

Definition mp: ModPair.t := SimSymbId.mk_mp (CminorSelC.module prog) (RTLC.module tprog).

Theorem sim_mod: ModPair.sim mp.
Proof.
  econs; ss.
  - r. eapply Sk.match_program_eq; eauto.
    ii. destruct f1; ss.
    + clarify. right. unfold bind in MATCH. inv MATCH. des. unfold Errors.bind, transl_function in *. ss. des_ifs. esplits; eauto.
    + clarify. left. esplits; eauto.
  - ii. inv SIMSKENVLINK. eapply sim_modsem; eauto.
Qed.

End SIMMOD.


Require Import Program.

Require Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.
Require Import AsmC.
Require SimMemInjInvC.
Require Import CoqlibC.
Require Import ValuesC.
Require Import LinkingC.
Require Import MapsC.
Require Import AxiomsC.
Require Import Ord.
Require Import MemoryC.
Require Import SmallstepC.
Require Import Events.
Require Import Preservation.
Require Import Integers.
Require Import LocationsC Conventions.
Require Import Conventions1C.

Require Import AsmregsC.
Require Import MatchSimModSem.
Require Import StoreArguments StoreArgumentsProps.
Require Import AsmStepInj IntegersC.
Require Import Coq.Logic.PropExtensionality.
Require Import AsmExtra IdSimExtra IdSimAsmExtra IdSimInvExtra.

Require Import MatchSimModSemExcl2.
Require Import Conventions1C.

Require Import mktac.

Set Implicit Arguments.

Local Opaque Z.mul Z.add Z.sub Z.div.

Section INJINV.

Variable P: SimMemInjInv.memblk_invariant.

Local Instance SimMemP: SimMem.class := SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv P.
Local Instance SimSymbP: SimSymb.class SimMemP := SimMemInjInvC.SimSymbIdInv P.
Local Existing Instance SoundTop.Top.

Lemma asm_inj_inv_id
      (asm: Asm.program)
      (WF: Sk.wf (module asm))
  :
    exists mp,
      (<<SIM: ModPair.sim mp>>)
      /\ (<<SRC: mp.(ModPair.src) = (AsmC.module asm)>>)
      /\ (<<TGT: mp.(ModPair.tgt) = (AsmC.module asm)>>)
.
Proof.
  eexists (ModPair.mk _ _ _); s.
  esplits; eauto. instantiate (1:=SimMemInjInvC.mk bot1 _ _).
  econs; ss; i.
  { econs; ss; i; clarify. }
  eapply MatchSimModSemExcl2.match_states_sim with
      (match_states :=
         @match_states
           SimMemInjInv.top_inv P
           skenv_link_tgt
           (SkEnv.revive (SkEnv.project skenv_link_src (Sk.of_program fn_sig asm)) asm)
           (SkEnv.revive (SkEnv.project skenv_link_tgt (Sk.of_program fn_sig asm)) asm))
      (match_states_at := top4)
      (sidx := unit); ss; eauto; ii.
  - apply lt_wf.
  - eapply SoundTop.sound_state_local_preservation.

  - (** ******************* initial **********************************)
    destruct sm_arg as [sm_arg mem_inv_src mem_inv_tgt].
    dup MWF. rename MWF0 into MINVWF.
    destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.
    exploit SimSymbIdInv_match_globals.
    { inv SIMSKENV. ss. eauto. } intros GEMATCH.
    inv SIMARGS.
    { ss. clarify.
      inv INITTGT; clarify. ss. inv TYP. cinv STORE.

      exploit store_arguments_parallel; eauto.
      { eapply typify_has_type_list; eauto. }
      { exploit SkEnv.revive_incl_skenv; try eapply FINDF; eauto. i. des.
        inv WFTGT. rpapply WFPARAM; eauto; ss. }
      { eapply inject_list_typify_list; try eassumption.
        erewrite inject_list_length; eauto. } i. des.
      hexploit (assign_junk_blocks_parallel n); eauto. i. des.
      eexists (AsmC.mkstate (((to_pregset (set_regset_junk (SimMemInj.src sm1) m0 n rs_src (to_mregset rs) (fn_sig fd))) # PC <- fptr_src)
                               # RA <- (src_junk_val (SimMemInj.src sm1) m0 n (rs RA)))
                            # RSP <- (Vptr (Mem.nextblock (SimMemInj.src sm_arg)) Ptrofs.zero)
                            (Asm.State _ _)).
    hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv P sm_arg sm0); eauto.
    { etrans; eauto. }
    { eapply SimMemInjInv.private_unchanged_on_invariant; eauto.
      - ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto.
      - eapply Mem.unchanged_on_implies with (P:=top2); ss. etrans.
        + eapply store_arguments_unchanged_on; eauto.
        + rewrite <- MTGT. rewrite MTGT0.
          eapply JunkBlock.assign_junk_blocks_unchanged_on. } intros MWFINV1.

    eexists (SimMemInjInv.mk sm0 _ _). esplits; eauto.
      { econs; ss; eauto.
        - inv SAFESRC; clarify. ss. des.
          exploit match_globals_find_funct; eauto. i.
          setoid_rewrite FINDF in H. clarify.
        - assert (JUNK: JunkBlock.is_junk_value m0 (JunkBlock.assign_junk_blocks m0 n) (rs RA)).
          { apply NNPP. ii. exploit PTRFREE; eauto. i. des; ss. }
          split.
          + unfold Pregmap.set, src_junk_val. des_ifs.
          + unfold Pregmap.set, src_junk_val. des_ifs; ss; des; eauto.
        - unfold Pregmap.set. des_ifs. unfold src_junk_val, JunkBlock.is_junk_value in *.
          des_ifs. ii. clarify. apply n1.
          assert (PLT: Plt (b + Mem.nextblock (SimMemInj.src sm1) - Mem.nextblock (SimMemInj.tgt sm1)) (Mem.nextblock (SimMemInj.src sm1))).
          { eapply Plt_Ple_trans; eauto.
            inv SIMSKENV. inv SIMSKELINK. ss. inv MLE. inv MWF.
            rewrite NBSRC.
            etrans; eauto. etrans; eauto. eapply Mem.unchanged_on_nextblock; eauto. }
          exfalso. eapply Plt_lemma; eauto.
        - econs; eauto. erewrite inject_list_length; eauto.
        - inv ARGTGT. econs; ss; eauto.
          econs; try eassumption; eauto.
          eapply extcall_arguments_same; eauto. i.
          unfold Pregmap.set, to_mregset, to_pregset, to_preg.
          erewrite to_preg_to_mreg. des_ifs; clarify; ss.
          + unfold preg_of in *; des_ifs.
          + unfold preg_of in *; des_ifs.
          + unfold preg_of in *; des_ifs.
          + unfold set_regset_junk. des_ifs; clarify; eauto.
            exfalso. eapply Loc.notin_not_in in n3. eauto.
        - i. unfold Pregmap.set in *. des_ifs; eauto.
          { exploit PTRFREE.
            - ii. eapply src_junk_val_junk in H; eauto.
            - i. des; clarify. } left.
          unfold to_pregset, set_regset_junk, to_mregset in *. des_ifs; ss.
          + exploit PTRFREE.
            * ii. eapply src_junk_val_junk in H; eauto.
            * i. erewrite to_mreg_some_to_preg in *; eauto. des; ss.
              clarify. esplits; eauto.
          + esplits; eauto. erewrite loc_notin_not_in in n3. tauto. }

      { econs; ss; eauto. etrans; eauto. }

      { assert (AGREE0:
                  AsmStepInj.agree
                    (SimMemInj.inj sm0)
                    (((to_pregset (set_regset_junk (SimMemInj.src sm1) m0 n rs_src (to_mregset rs) (fn_sig fd)))
                        # PC <- fptr_src) # RA <- (src_junk_val (SimMemInj.src sm1) m0 n (rs RA))) # RSP <-
                    (Vptr (Mem.nextblock (SimMemInj.src sm_arg)) Ptrofs.zero) rs).
        { ii. unfold Pregmap.set, to_mregset, to_pregset, to_preg.
          inv MLE0. des_ifs; ss; eauto.
          - eapply val_inject_incr; eauto. rewrite INJ.
            unfold update_meminj. rewrite H1. econs; des_ifs. ss.
          - rewrite MINJ. eapply src_junk_val_inj; eauto. inv MWF0. eauto.
          - inv MLE. eapply val_inject_incr; eauto.
          - unfold set_regset_junk. des_ifs.
            + erewrite to_mreg_preg_of; eauto. rewrite MINJ.
              eapply src_junk_val_inj; eauto. inv MWF0. eauto.
            + eapply val_inject_incr; eauto. rewrite INJ in *.
              specialize (AGREE m). unfold to_mregset in *.
              erewrite to_mreg_preg_of in *; eauto. }
        econs; eauto.
        - rewrite <- MTGT. auto.

        - instantiate (1:=fd). inv SAFESRC; clarify. ss. des.
          exploit match_globals_find_funct; eauto. i.
          setoid_rewrite FINDF in H. clarify.
        - econs.
          + econs; eauto.
            * unfold Pregmap.set. des_ifs.
            * unfold Pregmap.set. des_ifs. unfold src_junk_val. des_ifs.
            * unfold Pregmap.set. des_ifs. unfold src_junk_val.
              assert (JUNK: JunkBlock.is_junk_value (SimMemInj.tgt sm1) (JunkBlock.assign_junk_blocks (SimMemInj.tgt sm1) n) (rs RA)).
              { apply NNPP. ii. exploit PTRFREE; eauto. i. des; clarify. }
              clear - RADEF JUNK.
              unfold JunkBlock.is_junk_value, Mem.valid_block in *. des_ifs; des; eauto.
          + econs; ss. ii. congruence.
          + { unfold to_pregset, set_regset, Pregmap.set. ii.
              rewrite to_preg_to_mreg in *. des_ifs.
              + apply f_equal with (f:=to_mreg) in e.
                rewrite to_preg_to_mreg in  e. ss.
              + apply f_equal with (f:=to_mreg) in e.
                rewrite to_preg_to_mreg in  e. ss.
              + unfold set_regset_junk in *. des_ifs.
                * assert (JUNK: JunkBlock.is_junk_value (SimMemInj.tgt sm1) (JunkBlock.assign_junk_blocks (SimMemInj.tgt sm1) n) (rs (to_preg r))).
                  { apply NNPP. ii. exploit PTRFREE; eauto. i. des; clarify.
                    erewrite to_preg_to_mreg in MR. clarify.
                    eapply Loc.notin_not_in; eauto. }
                  unfold src_junk_val in *. des_ifs_safe.
                  unfold JunkBlock.is_junk_value in *.
                  unfold to_mregset in *. rewrite Heq in *.
                  unfold Mem.valid_block in *. exfalso. des. des_ifs.
                * erewrite loc_notin_not_in in n3. apply NNPP in n3.
                  apply loc_args_callee_save_disjoint in n3. exfalso. eauto. }
          + ss.
        - unfold Genv.find_funct, Genv.find_funct_ptr, Genv.find_def. des_ifs.
          eapply Genv.genv_defs_range in Heq0. exfalso. eapply RANOTFPTR; eauto.
        - unfold Pregmap.set. des_ifs. ii. clarify. rewrite MINJ. rewrite INJ.
          unfold junk_inj, update_meminj. des_ifs; eauto. }
    }
    { ss. inv INITTGT; clarify. ss.
      hexploit (assign_junk_blocks_parallel n); eauto. i. des.

      eexists (AsmC.mkstate
                 (rs_src # RA <- (src_junk_val (SimMemInj.src sm_arg) (SimMemInj.tgt sm_arg) n ra))
                 (Asm.State
                    (rs_src # RA <- (src_junk_val (SimMemInj.src sm_arg) (SimMemInj.tgt sm_arg) n ra))
                    (SimMemInj.src sm1))).
      esplits; eauto.
      - econs 2; ss; eauto.
        + inv SAFESRC; clarify. ss. des.
          exploit match_globals_find_funct; eauto.
          * eapply RS.
          * i. setoid_rewrite FINDF in H. clarify.
        + unfold Pregmap.set. des_ifs. unfold src_junk_val.
          des_ifs; split; ss; eauto; des; clarify.
        + unfold src_junk_val. des_ifs. i. clarify. ii. apply n0.
          assert (PLT: Plt (b + Mem.nextblock (SimMemInj.src sm_arg) - Mem.nextblock (SimMemInj.tgt sm_arg)) (Mem.nextblock (SimMemInj.src sm_arg))).
          { eapply Plt_Ple_trans; eauto.
            inv SIMSKENV. inv SIMSKELINK. ss. inv MLE. inv MWF.
            rewrite NBSRC. etrans; eauto. }
          exfalso. eapply Plt_lemma; eauto.
        + rewrite MSRC. eapply src_junk_val_junk; eauto.
      - instantiate (1:=SimMemInjInv.mk sm1 _ _). econs; ss.
      - cinv MWF. econs; eauto; simpl.
        + eapply AsmStepInj.agree_step; eauto.
          * eapply agree_incr; try apply RS; eauto.
            rewrite MINJ. eapply junk_inj_incr; eauto.
          * rewrite MINJ. eapply src_junk_val_inj; eauto.
        + eapply AsmStepInj.agree_step; eauto.
          * eapply agree_incr; try apply RS; eauto.
            rewrite MINJ. eapply junk_inj_incr; eauto.
          * rewrite MINJ. eapply src_junk_val_inj; eauto.
        + hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv P sm_arg sm1); eauto.
          eapply SimMemInjInv.private_unchanged_on_invariant; eauto.
          { ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto. }
          { eapply Mem.unchanged_on_implies with (P:=top2); ss. rewrite MTGT.
            eapply JunkBlock.assign_junk_blocks_unchanged_on. }
        + rewrite Pregmap.gso; clarify.
          inv SAFESRC; clarify. ss. des.
          exploit match_globals_find_funct; eauto.
          * eapply RS.
          * i. setoid_rewrite FINDF in H. clarify. eauto.
        + econs 2; eauto.
          * unfold src_junk_val. econs; eauto; rewrite Pregmap.gss.
            { des_ifs. }
            { des_ifs; clarify; ss; des; clarify. }
          * econs; eauto; rewrite Pregmap.gss.
        + rewrite Pregmap.gss. unfold Genv.find_funct, Genv.find_funct_ptr. des_ifs.
          eapply Genv.genv_defs_range in Heq. exfalso. eapply RANOTFPTR; eauto.
        + i. des. clarify. }

  - (** ******************* safe **********************************)
    exploit SimSymbIdInv_match_globals.
    { inv SIMSKENV. ss. eauto. } intros GEMATCH. des.
    inv SAFESRC.
    { inv TYP. inv SIMARGS; clarify. ss.
      eapply asm_initial_frame_succeed; eauto.
      + apply inject_list_length in VALS.
        transitivity (Datatypes.length vs_src); eauto.
      + exploit SkEnv.revive_incl_skenv; try eapply FINDF; eauto.
        i. des. inv WFSRC. eapply WFPARAM in H; eauto.
      + exploit match_globals_find_funct; eauto. }
    { inv SIMARGS; clarify. ss.
      eapply asm_initial_frame_succeed_asmstyle; eauto.
      exploit match_globals_find_funct; eauto. eapply RS. }

  - inv MATCH. ss.

  - (** ******************* at external **********************************)
    inv SIMSKENV. inv CALLSRC.
    { inv MATCH.
      destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].
      dup MWF. rename MWF0 into MINVWF.
      destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.
      des; ss; clarify. des_ifs.
      set (INJPC:= AGREE PC). cinv INJPC; rewrite <- H1 in *; ss; clarify.
      assert (delta = 0).
      { psimpl. inv SIMSKELINK. ss. inv INJECT. exploit IMAGE; eauto. rewrite <- H0 in *.
        - left. ss. clear - SIG. unfold Genv.find_funct_ptr in *.
          des_ifs. eapply Genv.genv_defs_range; eauto.
        - i. des. eauto. }
      clarify. psimpl. ss.
      exploit extcall_arguments_inject; eauto.
      { inv MWF. eauto. }
      i. des. cinv (AGREE Asm.RSP); rewrite RSP in *; clarify.

      exploit SimMemInjC.Mem_free_parallel'; eauto. i. des.
      hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv P sm0 sm1); eauto.
      { eapply SimMemInjInv.private_unchanged_on_invariant; eauto.
        - ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto.
        - eapply Mem.free_unchanged_on; eauto. ii.
          exploit INVRANGETGT; eauto. i. des. exploit H6; eauto.
          eapply Mem.perm_cur. eapply Mem.perm_implies.
          + eapply Mem.free_range_perm; eauto.
            instantiate (1:=Ptrofs.unsigned ofs + delta). lia.
          + econs. } intros MWFINV0.

      eexists (Args.mk (Vptr b2 _) _ _). eexists (SimMemInjInv.mk sm1 _ _).
      esplits; eauto; ss; i.
      + econs; auto.
        * eauto.
        * exploit SimSymbIdInv_find_None; try eassumption.
          { ii. rewrite H in *. ss. }
          { unfold Genv.find_funct. des_ifs. }
        * esplits; eauto. inv SIMSKELINK. inv INJECT. inv SIMSKENV. ss.
          rewrite <- H0 in *. inv INJPC. exploit IMAGE; eauto.
          { left. eapply Genv.genv_defs_range; eauto. ss.
            unfold Genv.find_funct_ptr in *. clear EXTERNAL. des_ifs; eauto. }
          { i. des. clarify. }
        * clear - AGREE TPTR RADEF. splits.
          { rename TPTR into TPTR0. unfold Tptr in *.
            des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }
          { rename TPTR into TPTR0. unfold Tptr in *.
            des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }
        * eauto.
        * eauto.
        * destruct (zlt 0 (size_arguments sg)).
          { inv MWF. exploit Mem.mi_representable; eauto.
            - right.
              instantiate (1:=Ptrofs.add ofs (Ptrofs.repr (4 * size_arguments sg))).
              eapply Mem.perm_cur.
              eapply Mem.perm_implies; try eapply Mem.free_range_perm; eauto; [|econs].
              rewrite unsigned_add.
              + clear - ARGSRANGE l. lia.
              + clear- ARGSRANGE. set (size_arguments_above sg).
                set (Ptrofs.unsigned_range_2 ofs). lia.
            - repeat rewrite unsigned_add. i. des.
              + lia.
              + exploit Mem.mi_representable; eauto. left. eapply Mem.perm_cur.
                eapply Mem.perm_implies; try eapply Mem.free_range_perm; eauto; [|econs].
                clear - ARGSRANGE l. lia.
              + clear - ARGSRANGE.
                set (size_arguments_above sg).
                set (Ptrofs.unsigned_range_2 ofs). lia. }
          { set (Ptrofs.unsigned_range_2 (Ptrofs.add ofs (Ptrofs.repr delta))). lia. }
        * inv MWF. i. erewrite Mem.address_inject; eauto; cycle 1.
          { eapply Mem.free_range_perm; eauto.
            set (size_chunk_pos chunk). lia. }
          eapply Z.divide_add_r; eauto.
          inv PUBLIC. inv mi_inj. exploit mi_align; eauto.
          eapply Mem.free_range_perm in FREE.
          intros ofs0 RANGE. exploit FREE; eauto.
          -- instantiate (1:=ofs0). instantiate (1:=Ptrofs.unsigned ofs) in RANGE. nia.
          -- i. eapply Mem.perm_cur_max. eapply Mem.perm_implies; eauto. econs.
        * eauto.
      + inv MLE. econs; s; eauto. rewrite H0. rewrite H1. eauto.
    }
    { ss. inv MATCH.
      des; ss; clarify. des_ifs.
      set (INJPC:= AGREE PC). cinv INJPC; rewrite <- H1 in *; ss; clarify.
      assert (delta = 0).
      { psimpl. inv SIMSKELINK. ss. inv INJECT. exploit IMAGE; eauto. rewrite <- H0 in *.
        - left. ss. clear - SIG. unfold Genv.find_funct_ptr in *.
          des_ifs. eapply Genv.genv_defs_range; eauto.
        - i. des. eauto. } clarify. psimpl. ss.
      exists (Args.Asmstyle rs_tgt (SimMemInj.tgt sm0.(SimMemInjInv.minj))). esplits; eauto.
      - econs 2; eauto.
        + exploit SimSymbIdInv_find_None; try eassumption.
          { ii. rewrite H in *. ss. }
          { unfold Genv.find_funct. des_ifs. }
        + esplits; eauto. inv SIMSKELINK. inv INJECT. inv SIMSKENV. ss.
          rewrite <- H0 in *. inv INJPC. exploit IMAGE; eauto.
          { left. eapply Genv.genv_defs_range; eauto. ss.
            unfold Genv.find_funct_ptr in *. clear EXTERNAL. des_ifs; eauto. }
          { i. des. clarify. rewrite <- H1 in *. auto. }
        + clear - AGREE TPTR RADEF. splits.
          { rename TPTR into TPTR0. unfold Tptr in *.
            des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }
          { rename TPTR into TPTR0. unfold Tptr in *.
            des_ifs; cinv (AGREE RA); ss; rewrite <- H1 in *; ss. }
      - econs 2; eauto.
      - refl. }

  - (** ******************* after external **********************************)
    exploit SimSymbIdInv_match_globals.
    { inv SIMSKENV. ss. eauto. } instantiate (1:=asm). intros GEMATCH.
    inv MATCH. inv AFTERSRC.
    { inv SIMRET; clarify. inv HISTORY; clarify.
      inv CALLSRC; clarify; cycle 1.
      { ss. des. clarify. }
      inv CALLTGT; clarify; cycle 1.
      { ss. des. clarify. ss. inv SIMARGS; clarify. } inv SIMARGS; clarify.
      rewrite RSRSP in *. des. ss. des_ifs. clarify.
      cinv (AGREE Asm.RSP); rewrite RSRSP in *; ss; clarify; rewrite RSP0 in *; clarify.

      assert (SKD: skd1 = skd).
      { inv SIMSKENV. inv SIMSKELINK. ss. inv INJECT.
        cinv (AGREE PC); rewrite <- H1 in *; clarify. eauto.
        exploit IMAGE; eauto.
        - left. rewrite <- H0 in *. ss. clear - SIG0. unfold Genv.find_funct_ptr in *.
          des_ifs. eapply Genv.genv_defs_range; eauto.
        - i. des. clarify. inv SIMSKENVLINK. inv SIMSKENV. clarify.
          rewrite <- H0 in *. ss. des_ifs. } clarify.

      hexploit (@Mem_unfree_parallel P sm0 sm_arg sm_ret); eauto.

      i. des. esplits; eauto. i.
      esplits; ss; eauto.

      + econs; ss; eauto.
      + dup MLE2. rename MLE4 into MINVLE2.
        destruct MLE2 as [MLE2 MINVEQSRC2 MINVEQTGT2].
        econs; try refl; eauto.
        * clarify. inv MLE2. ii.
          unfold set_pair, Pregmap.set, loc_external_result, map_rpair.
          des_ifs; ss; eauto.
          { rewrite MINJ. eauto. }
          { unfold regset_after_external. des_ifs; ss; eauto. }
          { rewrite MINJ. eapply Val.loword_inject. eauto. }
          { rewrite MINJ. eapply Val.hiword_inject. eauto. }
          { unfold regset_after_external. des_ifs; ss; eauto. }
        * inv MLE2. eapply agree_incr; eauto.
        * inv MLE2. i. exploit RSPDELTA; eauto. i. des. esplits; eauto.
    }
    { inv SIMRET; clarify. inv HISTORY; clarify.
      inv CALLSRC; clarify.
      { ss. des. clarify. }
      inv CALLTGT; clarify.
      { ss. des. clarify. ss. inv SIMARGS; clarify. } inv SIMARGS; clarify. ss.
      exists (SimMemInjInvC.unlift' sm_arg sm_ret).
      eexists. eexists (AsmC.mkstate _ (Asm.State _ _)). esplits; eauto.
      - etrans; eauto.
      - clear - MLE0. inv MLE0. inv MLE. ss. econs; ss; eauto. eapply SimMemInj.frozen_refl.
      - i. esplits; eauto.
        + econs 2; eauto.
        + exploit SimMemInjInvC.unlift_wf; try apply MLE0; eauto. i. inv MLE2.
          cinv MLE3. ss.
          econs; try apply H; auto; eauto.
          * eapply AsmStepInj.agree_step; eauto.
          * eapply AsmStepInj.agree_incr; eauto.
          * i. exploit RSPDELTA; eauto. i. des. eauto. }

  - (** ******************* final **********************************)

    exploit SimSymbIdInv_match_globals.
    { inv SIMSKENV. ss. eauto. } intros GEMATCH.
    inv MATCH. inv FINALSRC.
    {
      destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].
      dup MWF. rename MWF0 into MINVWF.
      destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.
      cinv (AGREEINIT RSP); rewrite INITRSP in *; clarify. psimpl.
      exploit SimMemInjC.Mem_free_parallel'; eauto.
      { instantiate (3:=Ptrofs.zero). zsimpl. psimpl. eauto. }
      i. des.
      hexploit (@SimMemInjInv.le_inj_wf_wf SimMemInjInv.top_inv P sm0 sm1); eauto.
      { eapply SimMemInjInv.private_unchanged_on_invariant; eauto.
        - ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto.
        - eapply Mem.free_unchanged_on; eauto.
          ii. exploit INVRANGETGT; eauto. i. des. exploit H3; eauto.
          eapply Mem.perm_cur. eapply Mem.perm_implies.
          + eapply Mem.free_range_perm; eauto.
            instantiate (1:=delta). lia.
          + econs. } intros MWFINV0.

      assert (delta = 0).
      { rewrite FINDF in *. clarify. exploit RSPDELTA; eauto. i. des. clarify. }
      clarify. ss. zsimpl.

      esplits; ss; eauto.
      + cinv (AGREEINIT RSP); rewrite INITRSP in *; clarify. psimpl.
        econs; ss; ii; eauto.
        * des. esplits; eauto.
          eapply match_globals_find_funct; eauto.
        * inv WFINITRS; clarify. clear - EXTERNAL AGREE SIMSKENVLINK SIMSKENV WFINITSRC RSRA.
          unfold external_state, Genv.find_funct, Genv.find_funct_ptr in *.
          cinv (AGREE PC); eauto.
          { rewrite <- H0 in *. des_ifs_safe.
            inv SIMSKENV. ss. inv SIMSKELINK. ss. inv SIMSKENV.
            inv INJECT. exploit IMAGE; eauto.
            - right. eapply Genv.genv_defs_range in Heq0. ss.
            - i. des. clarify. rewrite Heq0 in *. clarify. }
          { exfalso. rewrite <- H1 in *. inv WFINITSRC. eauto. }
        * inv WFINITRS; clarify. inv WFINITSRC. inv WFINITTGT.
          unfold Val.has_type in TPTR. des_ifs.
          -- cinv (AGREEINIT RA); rewrite Heq in *; clarify.
             cinv (AGREE PC); rewrite RSRA in *; clarify.
          -- ss. clear RANOTFPTR. des_ifs.
             cinv (AGREEINIT RA); rewrite Heq in *; clarify.
             cinv (AGREE PC); rewrite RSRA in *; clarify.
        * specialize (CALLEESAVE _ H).
          specialize (AGREEINIT (to_preg mr0)).
          specialize (AGREE (to_preg mr0)). inv WFINITRS; clarify.
          clear - CALLEESAVE AGREEINIT AGREE WFINITSRC WFINITTGT H UNDEF.
          inv WFINITSRC.
          eapply lessdef_commute; eauto.
        * cinv (AGREEINIT RSP); rewrite INITRSP in *; clarify.
          cinv (AGREE RSP); rewrite RSRSP in *; clarify.
      + econs; ss. eapply val_inject_incr; cycle 1; eauto.
        inv MLE. eauto.
      + econs; ss; eauto.
    }
    { exists sm0. exists (Retv.Asmstyle rs_tgt sm0.(SimMemInjInv.minj).(SimMemInj.tgt)).
      esplits; ss; eauto.
      + econs 2; ss; ii; eauto.
        * des. esplits; eauto.
          eapply match_globals_find_funct; eauto.
        * des.
          inv WFINITRS; clarify. clear - EXTERNAL AGREE SIMSKENVLINK SIMSKENV WFINITSRC RSRA.
          unfold external_state, Genv.find_funct, Genv.find_funct_ptr in *.
          cinv (AGREE PC); eauto.
          { rewrite <- H0 in *. des_ifs_safe.
            inv SIMSKENV. ss. inv SIMSKELINK. ss. inv SIMSKENV.
            inv INJECT. exploit IMAGE; eauto.
            - right. eapply Genv.genv_defs_range in Heq0. ss.
            - i. des. clarify. rewrite Heq0 in *. clarify. }
          { exfalso. rewrite <- H1 in *. inv WFINITSRC. eauto. }
        * des. des_ifs. clarify.
          inv WFINITRS; clarify. inv WFINITSRC. inv WFINITTGT.
          unfold Val.has_type in TPTR. des_ifs.
          -- cinv (AGREEINIT RA); rewrite Heq in *; clarify.
             cinv (AGREE PC); rewrite RSRA in *; clarify.
          -- ss. clear RANOTFPTR. des_ifs.
             cinv (AGREEINIT RA); rewrite Heq in *; clarify.
             cinv (AGREE PC); rewrite RSRA in *; clarify.
      + econs 2; ss.
      + refl. }

  - (** ******************* step **********************************)
    left; i.
    esplits; ss; i.
    + apply AsmC.modsem_receptive.
    + exists O.
      { inv STEPSRC. destruct st_src0, st_src1. inv MATCH. ss.
        inv SIMSKENV. destruct st0. ss. clarify.
        destruct sm0 as [sm0 mem_inv_src mem_inv_tgt].
        dup MWF. rename MWF0 into MINVWF.
        destruct MWF as [MWF SATSRC SATTGT INVRANGESRC INVRANGETGT]. ss.

        exploit asm_step_preserve_injection; eauto.
        { exploit SimSymbIdInv_match_globals; eauto.
          intros MATCH. inv MATCH. econs; ss; i; eauto.
          exploit DEFLE; eauto. i. des. clarify. esplits; eauto. }
        { eapply symbols_inject_weak_imply.
          exploit SimMemInjInvC.skenv_inject_symbols_inject; eauto. }
        { cinv MWF. eauto. }

        i. des.
        eexists (AsmC.mkstate init_rs_tgt (Asm.State _ _)).

        exploit SimMemInjC.parallel_gen; eauto.
        { ii. eapply asm_step_max_perm; eauto. }
        { ii. eapply asm_step_max_perm; eauto. }
        i. des.
        hexploit SimMemInjInv.le_inj_wf_wf; eauto.
        { eapply SimMemInjInv.private_unchanged_on_invariant; eauto.
          - ii. exploit INVRANGETGT; eauto. i. des. inv MWF. eapply Plt_Ple_trans; eauto.
          - eapply Mem.unchanged_on_implies; eauto.
            i. exploit INVRANGETGT; eauto. i. des. eauto. } intros MWFINV0.
        eexists (SimMemInjInv.mk _ _ _).

        esplits; eauto.
        - left. econs; cycle 1.
          + apply star_refl.
          + symmetry. apply E0_right.
          + econs.
            * apply AsmC.modsem_determinate.
            * econs; ss; eauto.
        - econs; ss; eauto.
        - econs; ss; eauto.
          + eapply agree_incr; eauto.
          + i. exploit RSPDELTA; eauto. i. des. esplits; eauto.
      }
Unshelve. all: apply 0.
Qed.

End INJINV.


(******************************************************************************)
(** * Sc-per-loc   *)
(******************************************************************************)

Require Import Classical Peano_dec.
From hahn Require Import Hahn.

Require Import Events.
Require Import Execution.

Set Implicit Arguments.
Remove Hints plus_n_O.

Section ECO.
Variable G : execution.

Notation "'E'" := G.(acts_set).
Notation "'sb'" := G.(sb).
Notation "'rf'" := G.(rf).
Notation "'co'" := G.(co).
Notation "'rmw'" := G.(rmw).

Notation "'fr'" := G.(fr).
Notation "'coe'" := G.(coe).
Notation "'coi'" := G.(coi).
Notation "'rfi'" := G.(rfi).
Notation "'rfe'" := G.(rfe).
Notation "'fre'" := G.(fre).
Notation "'fri'" := G.(fri).

Notation "'lab'" := G.(lab).
Notation "'loc'" := (loc lab).
Notation "'val'" := (val lab).
Notation "'mod'" := (mod lab).
Notation "'same_loc'" := (same_loc lab).

Notation "'R'" := (fun a => is_true (is_r lab a)).
Notation "'W'" := (fun a => is_true (is_w lab a)).
Notation "'F'" := (fun a => is_true (is_f lab a)).
Notation "'RW'" := (R ∪₁ W).
Notation "'FR'" := (F ∪₁ R).
Notation "'FW'" := (F ∪₁ W).

Notation "'Pln'" := (is_only_pln lab).
Notation "'Rlx'" := (is_rlx lab).
Notation "'Rel'" := (is_rel lab).
Notation "'Acq'" := (is_acq lab).
Notation "'Acqrel'" := (is_acqrel lab).
Notation "'Sc'" := (is_sc lab).

Implicit Type WF : Wf G.
Implicit Type COMP : complete G.
Implicit Type ATOM : rmw_atomicity G.

(******************************************************************************)
(** ** extended coherence order  *)
(******************************************************************************)

Definition eco := rf ∪ co ⨾ rf^? ∪ fr ⨾ rf^?.

Definition sc_per_loc := irreflexive (sb ⨾ eco).

Implicit Type SC_PER_LOC : sc_per_loc.

(******************************************************************************)
(** ** Basic Properties  *)
(******************************************************************************)

Lemma co_in_eco: co ⊆ eco.
Proof using. unfold eco; basic_solver 6. Qed.

Lemma rf_in_eco: rf ⊆ eco.
Proof using. unfold eco; basic_solver 6. Qed.

Lemma fr_in_eco: fr ⊆ eco.
Proof using. unfold eco; basic_solver 6. Qed.

Lemma co_rf_in_eco: co ;; rf ⊆ eco.
Proof using. unfold eco; basic_solver 6. Qed.

Lemma fr_rf_in_eco: fr ;; rf ⊆ eco.
Proof using. unfold eco; basic_solver 6. Qed.

Lemma rfe_in_eco : rfe ⊆ eco.
Proof using. rewrite rfe_in_rf. apply rf_in_eco. Qed.

Lemma coe_in_eco : coe ⊆ eco.
Proof using. rewrite coe_in_co. apply co_in_eco. Qed.

Lemma fre_in_eco : fre ⊆ eco.
Proof using. rewrite fre_in_fr. apply fr_in_eco. Qed.

Lemma loceq_eco WF : funeq loc eco.
Proof using. destruct WF; desf. eauto 10 with hahn. Qed.

Lemma wf_ecoE WF : eco ≡ ⦗E⦘ ⨾ eco ⨾ ⦗E⦘.
Proof using.
split; [|basic_solver].
unfold eco.
rewrite (wf_rfE WF) at 1 2 3.
rewrite (wf_coE WF) at 1.
rewrite (wf_frE WF) at 1.
basic_solver 42.
Qed.

Lemma wf_ecoD WF : eco ≡ ⦗RW⦘ ⨾ eco ⨾ ⦗RW⦘.
Proof using.
split; [|basic_solver].
unfold eco.
rewrite wf_rfD at 1 2 3; try done.
rewrite wf_coD at 1; try done.
rewrite wf_frD at 1; try done.
type_solver 42.
Qed.

Lemma eco_alt WF: eco ≡ (co ∪ fr) ∪ (co ∪ fr)^? ⨾ rf.
Proof using.
  unfold eco, Execution.fr; basic_solver 42.
Qed.

Lemma eco_alt2 WF: eco ≡ rf ∪ (rf⁻¹)^? ⨾ co ⨾ rf^?.
Proof using.
  unfold eco, Execution.fr; basic_solver 42.
Qed.

Lemma eco_trans WF: transitive eco.
Proof using.
unfold eco.
apply transitiveI.
generalize (rf_rf WF) (rf_fr WF) (co_co WF) (rf_co WF) (co_fr WF) (fr_fr WF) (fr_co WF).
unfolder; ins; desf; try basic_solver 1.
all: try (exfalso; basic_solver).
all: basic_solver 42.
Qed.

Lemma eco_irr WF: irreflexive eco.
Proof using.
unfold eco.
generalize (co_irr WF) (rf_irr WF) (fr_irr WF).
generalize (rf_fr WF) (rf_co WF).
basic_solver 5.
Qed.

Lemma eco_alt3 WF: eco ≡ (rf ∪ co ∪ fr)⁺.
Proof using.
split; eauto 8 using rf_in_eco, co_in_eco, fr_in_eco, eco_trans with hahn.
unfold eco; rewrite !crE; relsf.
unionL; eauto 6 using inclusion_step2_ct with hahn.
Qed.

Lemma eco_f WF : eco ⨾ ⦗F⦘ ⊆ ∅₂.
Proof using.
rewrite (wf_ecoD WF); type_solver.
Qed.

Lemma eco_almost_total WF COMP x y
  (ACTx: E x) (ACTy: E y)
  (RWx: RW x) (RWy: RW y) (LOC: loc x = loc y)
  (NEQ: x <> y):
  eco x y \/ eco y x \/ exists z, rf z x /\ rf z y.
Proof using.
generalize (dom_to_doma (wf_rfE WF)); intro rfE1; unfolder in rfE1.
generalize (dom_to_domb (wf_rfE WF)); intro rfE2; unfolder in rfE2.
generalize (dom_to_doma (wf_rfD WF)); intro rfD1; unfolder in rfD1.
generalize (dom_to_domb (wf_rfD WF)); intro rfD2; unfolder in rfD2.
generalize (loceq_rf WF); intro rfL; unfolder in rfL.
assert (exists l, loc x = l).
by destruct x; eauto.
unfolder in RWx.
unfolder in RWy.
ins; desf.
- assert (exists wx, rf wx x) by (apply COMP; basic_solver).
  assert (exists wy, rf wy y) by (apply COMP; basic_solver).
  desf.
  destruct (classic (wx=wy)); try subst; eauto.
  assert (co wx wy \/ co wy wx); cycle 1.
  by unfold eco, Execution.fr; basic_solver 42.
  eapply WF; unfolder; splits; eauto.
  by apply (loceq_rf WF) in H; apply (loceq_rf WF) in H0; congruence.
- assert (exists wy, rf wy y) by (apply COMP; basic_solver).
  desf.
  destruct (classic (wy=x)); [subst; unfold eco; basic_solver 5|].
  assert (co wy x \/ co x wy); cycle 1.
  by unfold eco, Execution.fr; basic_solver 42.
  eapply WF; unfolder; splits; eauto.
  by apply (loceq_rf WF) in H; congruence.
- assert (exists wx, rf wx x).
  by apply COMP; basic_solver.
  desf.
  destruct (classic (wx=y)); [subst; unfold eco; basic_solver 5|].
  assert (co wx y \/ co y wx); cycle 1.
  by unfold eco, Execution.fr; basic_solver 42.
  eapply WF; unfolder; splits; eauto.
  by apply (loceq_rf WF) in H; congruence.
- assert (co x y \/ co y x); [eapply WF|unfold eco]; basic_solver 10.
Qed.

Lemma transp_rf_rf_eco_in_eco WF : rf⁻¹ ⨾ rf ⨾ eco ⊆ eco.
Proof using.
unfold eco, Execution.fr; relsf.
rewrite rf_rf; auto.
seq_rewrite rf_co; auto.
rewrite !seqA.
sin_rewrite rf_transp_rf; basic_solver 10.
Qed.

Lemma eco_transp_rf_rf_in_eco WF : eco ⨾ rf⁻¹ ⨾ rf ⊆ eco.
Proof using.
unfold eco, Execution.fr; relsf.
rewrite !seqA, !crE; relsf.
arewrite_false (co ⨾ rf⁻¹).
by rewrite (wf_coD WF), (wf_rfD WF); type_solver.
sin_rewrite !rf_transp_rf; auto.
basic_solver 8.
Qed.

(******************************************************************************)
(** ** implications of SC_PER_LOC  *)
(******************************************************************************)

Lemma no_co_to_init WF SC_PER_LOC : co ⊆ co ⨾  ⦗fun x => ~ is_init x⦘.
Proof using.
rewrite wf_coE at 1; try done.
unfolder; ins; splits; auto; desf; intro.
eapply SC_PER_LOC; exists x; splits; [|eby apply co_in_eco].
unfold Execution.sb; unfolder; splits; try done.
cut (~ is_init x).
by destruct x, y; ins.
intro.
assert (x=y).
eby apply (loceq_co WF) in H0; eapply init_same_loc.
eby subst; eapply (co_irr WF).
Qed.

Lemma no_fr_to_init WF SC_PER_LOC : fr ⊆ fr ⨾  ⦗fun x => ~ is_init x⦘.
Proof using.
unfold Execution.fr.
rewrite no_co_to_init at 1; try done.
basic_solver.
Qed.

Lemma co_from_init WF SC_PER_LOC :
  ⦗fun x => is_init x⦘ ⨾ (same_loc \ (fun x y => x = y)) ⨾ ⦗E ∩₁ W⦘ ⊆ co.
Proof using.
unfolder; ins; desf.
generalize (init_w WF H); intro Wx.
generalize (is_w_loc lab x Wx).
unfold Events.same_loc in *; ins; desf.
eapply tot_ex.
- eapply WF.
- basic_solver.
- unfolder; splits; try edone.
  destruct x; [|unfold is_init in *; desf].
  eapply (wf_init WF); exists y; splits; eauto.
  unfold Events.loc in *.
  rewrite (wf_init_lab WF) in *.
  congruence.
- intro A.
  hahn_rewrite (no_co_to_init WF SC_PER_LOC) in A.
  unfolder in *; desf.
- intro; eauto.
Qed.

Lemma atomicity_alt WF SC_PER_LOC ATOM : rmw ∩ (fr ⨾ co) ⊆ ∅₂.
Proof using.
rewrite rmw_from_non_init, no_fr_to_init; eauto.
unfolder; red in ATOM; red in SC_PER_LOC; ins; desf.
destruct (classic (sb x z));
destruct (classic (sb z y)); eauto 8.
- by eapply wf_rmwi; eauto.
- eapply sb_semi_total_l with (y:=y) in H4; eauto.
  desf.
  eapply SC_PER_LOC.
  by eexists; splits; [eauto| apply co_in_eco].
  eby intro; subst; eapply (co_irr WF).
  eby apply rmw_in_sb.
- eapply sb_semi_total_r with (x:=y) (y:=x) in H5; eauto.
  desf.
  eapply SC_PER_LOC.
  by eexists; splits; [eauto| apply fr_in_eco].
  eby intro; subst; eapply fr_irr.
  eby apply rmw_in_sb.
- by eapply ATOM; unfolder; splits; eauto.
Qed.

Lemma BasicRMW WF SC_PER_LOC: irreflexive (co^? ⨾ rf ⨾ rmw).
Proof using.
rewrite rmw_in_sb; try done.
unfold sc_per_loc, eco in *; unfolder in *; basic_solver 10.
Qed.

Lemma w_r_loc_w_in_co WF r
  (rE: r ≡ ⦗E⦘ ⨾ r ⨾  ⦗E⦘) (IRR: irreflexive r)
  (A: irreflexive (r ⨾ eco)):
  ⦗W⦘ ⨾ r ∩ same_loc ⨾ ⦗W⦘ ⊆ co.
Proof using.
rewrite rE.
unfolder; ins; desf.
eapply tot_ex.
- eapply WF.
- unfolder; splits; try edone.
- unfolder; splits; try edone.
- intro; eapply A; unfold eco; basic_solver 12.
- intro; subst; eapply IRR; eauto.
Qed.

Lemma w_r_loc_r_in_co_rf WF r
  (rE: r ≡ ⦗E⦘ ⨾ r ⨾  ⦗E⦘)
  (A: irreflexive (r ⨾ eco)) COMP :
  ⦗W⦘ ⨾ r ∩ same_loc ⨾ ⦗R⦘ ⊆ co^? ⨾ rf.
Proof using.
rewrite rE.
cut (⦗W⦘ ⨾  ⦗E⦘ ⨾ r ∩ same_loc ⨾ ⦗E ∩₁ R⦘ ⊆ co^? ⨾ rf).
by basic_solver 12.
red in COMP; rewrite COMP.
rewrite (dom_l (wf_rfD WF)) at 1.
rewrite (dom_l (wf_rfE WF)) at 1.
rewrite (loceq_same_loc (loceq_rf WF)) at 1.
unfolder; ins; desf; eexists; splits; [|edone].
destruct (classic (x=z)); [eauto|].
right; eapply tot_ex.
- eapply WF.
- splits; try edone.
- splits; try edone.
- intro; eapply A.
unfold eco, Execution.fr; basic_solver 22.
- congruence.
Qed.

Lemma r_r_loc_w_in_fr WF r
  (rE: r ≡ ⦗E⦘ ⨾ r ⨾  ⦗E⦘)
  (A: irreflexive (r ⨾ eco)) COMP :
  ⦗R⦘ ⨾ r ∩ same_loc ⨾ ⦗W⦘ ⊆ fr.
Proof using.
rewrite rE.
cut (⦗E ∩₁ R⦘ ⨾ r ∩ same_loc ⨾ ⦗E ∩₁ W⦘ ⊆ fr).
by basic_solver 12.
red in COMP; rewrite COMP.
rewrite (dom_l (wf_rfD WF)) at 1.
rewrite (dom_l (wf_rfE WF)) at 1.
rewrite (loceq_same_loc (loceq_rf WF)) at 1.
unfolder; ins; desf; eexists; splits; [edone|].
(* destruct (classic (x=z)); [eauto|]. *)
eapply tot_ex.
- eapply WF.
- splits; try edone.
- unfolder; splits; [done | done | unfolder in *; congruence].
- intro; eapply A.
unfold eco; basic_solver 22.
- intro; subst.
eapply A.
unfold eco; basic_solver 22.
Qed.

Lemma r_r_loc_r_in_fr_rf WF r
  (rE: r ≡ ⦗E⦘ ⨾ r ⨾  ⦗E⦘)
  (A: irreflexive (r ⨾ eco)) COMP :
  ⦗R⦘ ⨾ r ∩ same_loc ⨾ ⦗R⦘ ⊆ fr ⨾ rf ∪ rf^{-1} ⨾ rf.
Proof using.
rewrite rE.
cut (⦗E ∩₁ R⦘ ⨾ r ∩ same_loc ⨾ ⦗E ∩₁ R⦘ ⊆ fr ⨾ rf ∪ rf^{-1} ⨾ rf).
by basic_solver 12.
red in COMP; rewrite COMP.
rewrite (dom_l (wf_rfD WF)) at 1 2.
rewrite (dom_l (wf_rfE WF)) at 1 2.
rewrite (loceq_same_loc (loceq_rf WF)) at 1 2.
unfolder; ins; desf.
destruct (classic (z0=z)).
by right; eexists; subst; eauto.
left.
unfold Execution.fr; unfolder.
eexists; splits; [|edone].
eexists; splits; [edone|].
eapply tot_ex.
- eapply WF.
- splits; try edone.
- unfolder; splits; [done | done | unfolder in *; congruence].
- intro; eapply A.
unfold eco, Execution.fr; basic_solver 22.
- intro; subst; eauto.
Qed.

Lemma w_sb_loc_w_in_coi WF SC_PER_LOC:
  ⦗W⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘ ⊆ coi.
Proof using.
arewrite (⦗W⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘ ⊆ (⦗W⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘) ∩ sb).
basic_solver.
rewrite (w_r_loc_w_in_co WF (@wf_sbE G) (@sb_irr G) SC_PER_LOC).
by ie_unfolder.
Qed.

Lemma w_sb_loc_r_in_co_rf WF SC_PER_LOC COMP:
  ⦗W⦘ ⨾ sb ∩ same_loc ⨾ ⦗R⦘ ⊆ co^? ⨾ rf.
Proof using.
apply (w_r_loc_r_in_co_rf WF (@wf_sbE G) SC_PER_LOC COMP).
Qed.

Lemma r_sb_loc_w_in_fri WF SC_PER_LOC COMP:
  ⦗R⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘ ⊆ fri.
Proof using.
arewrite (⦗R⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘ ⊆ (⦗R⦘ ⨾ sb ∩ same_loc ⨾ ⦗W⦘) ∩ sb).
basic_solver.
rewrite (r_r_loc_w_in_fr WF (@wf_sbE G) SC_PER_LOC COMP).
by ie_unfolder.
Qed.

Lemma r_sb_loc_r_in_fr_rf WF SC_PER_LOC COMP:
  ⦗R⦘ ⨾ sb ∩ same_loc ⨾ ⦗R⦘ ⊆ fr ⨾ rf ∪ rf^{-1} ⨾ rf.
Proof using.
apply (r_r_loc_r_in_fr_rf WF (@wf_sbE G) SC_PER_LOC COMP).
Qed.

Lemma rmw_in_fri WF SC_PER_LOC COMP : rmw ⊆ fri.
Proof using.
rewrite (wf_rmwD WF), (rmw_in_sb_loc WF).
rewrite (r_sb_loc_w_in_fri WF SC_PER_LOC COMP).
ie_unfolder; basic_solver.
Qed.

Lemma rmw_in_fr WF SC_PER_LOC COMP : rmw ⊆ fr.
Proof using.
  rewrite rmw_in_fri; auto. apply fri_in_fr.
Qed.

Lemma rf_rmw_in_co_helper WF SC_PER_LOC: rf ⨾ rmw ⊆ co ∪ co^{-1}.
Proof using.
rewrite (dom_l WF.(wf_rfE)).
rewrite (dom_r WF.(wf_rmwE)).
rewrite (dom_l WF.(wf_rfD)).
rewrite (dom_r WF.(wf_rmwD)).
unfolder; ins; desf.
eapply WF.(wf_co_total); [basic_solver| |].
{ unfolder; ins; desf; splits; eauto.
  apply WF.(wf_rfl) in H0.
  apply WF.(wf_rmwl) in H1.
  unfold Events.same_loc in *; congruence. }
intro; subst.
eapply SC_PER_LOC.
exists y; splits; eauto.
eapply WF.(rmw_in_sb); edone.
eapply rf_in_eco; edone.
Qed.

Lemma rf_rmw_in_co WF SC_PER_LOC : rf ⨾ rmw ⊆ co.
Proof using.
arewrite (rf ⨾ rmw ⊆ (rf ⨾ rmw) ∩ (rf ;; rmw)).
rewrite rf_rmw_in_co_helper at 1; eauto.
rewrite inter_union_l; unionL; [basic_solver|].
transitivity (fun _ _ : actid => False); [|basic_solver].
unfolder; ins; desf.
eapply SC_PER_LOC.
exists y; splits; eauto.
eapply WF.(rmw_in_sb); edone.
eapply co_rf_in_eco; basic_solver.
Qed.

Lemma rf_rmw_ct_in_co WF SC_PER_LOC : (rf ⨾ rmw)⁺ ⊆ co.
Proof using. by rewrite rf_rmw_in_co, (ct_of_trans (co_trans WF)). Qed.

Lemma rf_rmw_rt_in_co WF SC_PER_LOC : (rf ⨾ rmw)＊ ⊆ co^?.
Proof using. by rewrite rf_rmw_in_co, (rt_of_trans (co_trans WF)). Qed.

Lemma rf_rmw_in_coimm WF SC_PER_LOC ATOM: rf ⨾ rmw ⊆ immediate co.
Proof using.
ins; split; [by apply rf_rmw_in_co|].
ins; unfolder in *; desf.
eapply atomicity_alt; try done.
unfold Execution.fr; basic_solver 10.
Qed.

(******************************************************************************)
(** ** properties of external/internal relations *)
(******************************************************************************)

Lemma coe_coi WF SC_PER_LOC: coe ⨾ coi ⊆ coe.
Proof using.
cut ((co \ sb) ⨾ co ∩ sb ⊆ co ⨾ co \ sb).
by rewrite (co_co WF).
apply re_ri; try done; try by apply no_co_to_init.
by apply co_irr.
rotate 1.
by rewrite co_in_eco.
Qed.

Lemma fre_coi WF SC_PER_LOC : fre ⨾ coi ⊆ fre.
Proof using.
cut ((fr \ sb) ⨾ co ∩ sb ⊆ fr ⨾ co \ sb).
by rewrite (fr_co WF).
apply re_ri; try done; try by apply no_fr_to_init.
by apply fr_irr.
rotate 1.
by rewrite fr_in_eco.
Qed.

Lemma coi_coe WF SC_PER_LOC:
 ⦗fun x => ~ is_init x⦘ ⨾ coi ⨾ coe ⊆ coe.
Proof using.
cut (⦗fun x => ~ is_init x⦘ ⨾ (co ∩ sb) ⨾ (co \ sb) ⊆ co ⨾ co \ sb).
by rewrite (co_co WF).
apply ri_re; try done; try by apply no_co_to_init.
by apply co_irr.
rotate 1.
by rewrite co_in_eco.
Qed.

Lemma rfe_fri WF SC_PER_LOC : rfe ;; fri ⊆ coe.
Proof using.
  cut ((rf \ sb) ⨾ fr ∩ sb ⊆ rf ⨾ fr \ sb).
  { by rewrite (rf_fr WF). }
  apply re_ri; try done; try by apply no_rf_to_init.
  { by apply rf_irr. }
  rotate 1. by rewrite rf_in_eco.
Qed.

Lemma eco_refl :
  eco^? ⊆ ((co ∪ fre)^? ⨾ rf^?) ∪ fri ⨾ rfi^? ∪ fri ⨾ rfe.
Proof using.
unfold eco.
rewrite !(@fri_union_fre G).
rewrite !(@rfi_union_rfe G).
basic_solver 12.
Qed.

Lemma eco_alt4 WF : eco ⊆ ⦗RW⦘ ⨾ sb ∪ rfe ∪ co ⨾ rf^? ∪ fre ⨾ rf^? ∪ fri ⨾ rfe.
Proof using.
unfold eco.
rewrite (dom_l (wf_rfD WF)) at 1.
rewrite (dom_l (wf_frD WF)) at 1.
rewrite !(@fri_union_fre G); relsf.
unionL.
- rewrite !(@rfi_union_rfe G).
  arewrite (rfi ⊆ sb) at 1.
  basic_solver 12.
- basic_solver 12.
- rewrite !(@rfi_union_rfe G).
  case_refl (rfi ∪ rfe).
  arewrite (fri ⊆ sb); basic_solver 12.
  relsf; unionL; [|basic_solver 12].
  arewrite (fri ⊆ sb); arewrite (rfi ⊆ sb).
  generalize (@sb_trans G).
  basic_solver 12.
- basic_solver 12.
Qed.

Lemma thread_rfe_sb WF SC_PER_LOC : (rfe^{-1} ⨾ sb) ∩ same_tid ⊆ ∅₂.
Proof using.
ie_unfolder; unfolder; unfold same_tid; ins; desf.
hahn_rewrite (@wf_sbE G) in H1; unfolder in H1; desf.
hahn_rewrite (wf_rfE WF) in H; unfolder in H; desf.
hahn_rewrite (no_rf_to_init WF) in H5; unfolder in H5; desf.
apply (@same_thread G) in H0; try done.
desf.
- destruct H0; [subst; auto|].
eapply sb_semi_total_r in H0; try edone.
2:  by intro; subst; eapply (rf_irr WF); edone.
desf; eapply SC_PER_LOC; unfold eco; basic_solver 12.
- eapply H2; eapply (@sb_trans G); edone.
Qed.

Lemma co_sb_loc WF SC_PER_LOC : ⦗W⦘ ⨾ co^? ⨾ (sb ∩ same_loc)^? ⨾ ⦗W⦘ ⊆ co^?.
Proof using.
  case_refl (sb ∩ same_loc); [basic_solver|].
  rewrite (dom_r (wf_coD WF)).
  arewrite (⦗W⦘ ⨾ (co ⨾ ⦗W⦘)^? ⊆ co^? ⨾ ⦗W⦘) by basic_solver.
  rewrite (w_sb_loc_w_in_coi WF SC_PER_LOC), (dom_r (wf_coiD WF)).
  generalize (co_trans WF); ie_unfolder; basic_solver 12.
Qed.

End ECO.