(* *********************************************************************)
(*                                                                     *)
(*              The Compcert verified compiler                         *)
(*                                                                     *)
(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)
(*                                                                     *)
(*  Copyright Institut National de Recherche en Informatique et en     *)
(*  Automatique.  All rights reserved.  This file is distributed       *)
(*  under the terms of the INRIA Non-Commercial License Agreement.     *)
(*                                                                     *)
(* *********************************************************************)

(** RTL function inlining: relational specification *)

Require Import Coqlib.
Require Import Wfsimpl.
Require Import Errors.
Require Import Maps.
Require Import AST.
Require Import Integers.
Require Import Globalenvs.
Require Import Op.
Require Import Registers.
Require Import RTL.
Require Import Inlining.

(** ** Soundness of function environments. *)

(** A (compile-time) function environment is compatible with a
  (run-time) global environment if the following condition holds. *)

Definition fenv_compat (ge: genv) (fenv: funenv) : Prop :=
  forall id b f,
  fenv!id = Some f -> Genv.find_symbol ge id = Some b ->
  Genv.find_funct_ptr ge b = Some (Internal f).

Remark add_globdef_compat:
  forall ge fenv idg,
  fenv_compat ge fenv ->
  fenv_compat (Genv.add_global ge idg) (Inlining.add_globdef fenv idg).
Proof.
  intros. destruct idg as [id gd]. red; simpl; intros.
  unfold Genv.find_symbol in H1; simpl in H1.
  unfold Genv.find_funct_ptr; simpl.
  rewrite PTree.gsspec in H1. destruct (peq id0 id).
  (* same *)
(** [CompCertX:test-compcert-void-symbols] We now allow a symbol to be
associated to no variable or function. *)
  subst id0. inv H1. destruct gd. destruct g. destruct f0.
  destruct (should_inline id f0).
  rewrite PTree.gss in H0. rewrite PTree.gss. inv H0; auto.
  rewrite PTree.grs in H0; discriminate.
  rewrite PTree.grs in H0; discriminate.
  rewrite PTree.grs in H0; discriminate.
(** [CompCertX:test-compcert-void-symbols] case none *)
  rewrite PTree.grs in H0; discriminate.
  (* different *)
  destruct gd. destruct g. rewrite PTree.gso. eapply H; eauto.
  destruct f0. destruct (should_inline id f0).
  rewrite PTree.gso in H0; auto.
  rewrite PTree.gro in H0; auto.
  rewrite PTree.gro in H0; auto.
  red; intros; subst b. eelim Plt_strict. eapply Genv.genv_symb_range; eauto.
  rewrite PTree.gro in H0; auto. eapply H; eauto.
(** [CompCertX:test-compcert-void-symbols] case none *)
  rewrite PTree.gro in H0; auto. eapply H; eauto.
Qed.

Lemma funenv_program_compat:
  forall p, fenv_compat (Genv.globalenv p) (funenv_program p).
Proof.
  intros.
  unfold Genv.globalenv, funenv_program.
  assert (forall gl ge fenv,
         fenv_compat ge fenv ->
         fenv_compat (Genv.add_globals ge gl) (fold_left add_globdef gl fenv)).
    induction gl; simpl; intros. auto. apply IHgl. apply add_globdef_compat; auto.
  apply H. red; intros. rewrite PTree.gempty in H0; discriminate.
Qed.

(** ** Properties of shifting *)

Lemma shiftpos_eq: forall x y, Zpos (shiftpos x y) = (Zpos x + Zpos y) - 1.
Proof.
  intros. unfold shiftpos. zify.  rewrite Pos2Z.inj_sub. auto.
  zify. omega.
Qed.

Lemma shiftpos_inj:
  forall x y n, shiftpos x n = shiftpos y n -> x = y.
Proof.
  intros.
  assert (Zpos (shiftpos x n) = Zpos (shiftpos y n)) by congruence.
  rewrite ! shiftpos_eq in H0.
  assert (Z.pos x = Z.pos y) by omega.
  congruence.
Qed.

Lemma shiftpos_diff:
  forall x y n, x <> y -> shiftpos x n <> shiftpos y n.
Proof.
  intros; red; intros. elim H. eapply shiftpos_inj; eauto.
Qed.

Lemma shiftpos_above:
  forall x n, Ple n (shiftpos x n).
Proof.
  intros. unfold Ple; zify. rewrite shiftpos_eq. xomega.
Qed.

Lemma shiftpos_not_below:
  forall x n, Plt (shiftpos x n) n -> False.
Proof.
  intros. generalize (shiftpos_above x n). xomega.
Qed.

Lemma shiftpos_below:
  forall x n, Plt (shiftpos x n) (Pplus x n).
Proof.
  intros. unfold Plt; zify. rewrite shiftpos_eq. omega.
Qed.

Lemma shiftpos_le:
  forall x y n, Ple x y -> Ple (shiftpos x n) (shiftpos y n).
Proof.
  intros. unfold Ple in *; zify. rewrite ! shiftpos_eq. omega.
Qed.

(** ** Working with the state monad *)

Remark bind_inversion:
  forall (A B: Type) (f: mon A) (g: A -> mon B)
         (y: B) (s1 s3: state) (i: sincr s1 s3),
  bind f g s1 = R y s3 i ->
  exists x, exists s2, exists i1, exists i2,
  f s1 = R x s2 i1 /\ g x s2 = R y s3 i2.
Proof.
  unfold bind; intros. destruct (f s1). exists x; exists s'; exists I.
  destruct (g x s'). inv H. exists I0; auto.
Qed.

Ltac monadInv1 H :=
  match type of H with
  | (R _ _ _ = R _ _ _) =>
      inversion H; clear H; try subst
  | (ret _ _ = R _ _ _) =>
      inversion H; clear H; try subst
  | (bind ?F ?G ?S = R ?X ?S' ?I) =>
      let x := fresh "x" in (
      let s := fresh "s" in (
      let i1 := fresh "INCR" in (
      let i2 := fresh "INCR" in (
      let EQ1 := fresh "EQ" in (
      let EQ2 := fresh "EQ" in (
      destruct (bind_inversion _ _ F G X S S' I H) as [x [s [i1 [i2 [EQ1 EQ2]]]]];
      clear H;
      try (monadInv1 EQ2)))))))
  end.

Ltac monadInv H :=
  match type of H with
  | (ret _ _ = R _ _ _) => monadInv1 H
  | (bind ?F ?G ?S = R ?X ?S' ?I) => monadInv1 H
  | (?F _ _ _ _ _ _ _ _ = R _ _ _) =>
      ((progress simpl in H) || unfold F in H); monadInv1 H
  | (?F _ _ _ _ _ _ _ = R _ _ _) =>
      ((progress simpl in H) || unfold F in H); monadInv1 H
  | (?F _ _ _ _ _ _ = R _ _ _) =>
      ((progress simpl in H) || unfold F in H); monadInv1 H
  | (?F _ _ _ _ _ = R _ _ _) =>
      ((progress simpl in H) || unfold F in H); monadInv1 H
  | (?F _ _ _ _ = R _ _ _) =>
      ((progress simpl in H) || unfold F in H); monadInv1 H
  | (?F _ _ _ = R _ _ _) =>
      ((progress simpl in H) || unfold F in H); monadInv1 H
  | (?F _ _ = R _ _ _) =>
      ((progress simpl in H) || unfold F in H); monadInv1 H
  | (?F _ = R _ _ _) =>
      ((progress simpl in H) || unfold F in H); monadInv1 H
  end.

Fixpoint mlist_iter2 {A B: Type} (f: A -> B -> mon unit) (l: list (A*B)): mon unit :=
  match l with
  | nil => ret tt
  | (x,y) :: l' => do z <- f x y; mlist_iter2 f l'
  end.

Remark mlist_iter2_fold:
  forall (A B: Type) (f: A -> B -> mon unit) l s,
  exists i,
  mlist_iter2 f l s =
  R tt (fold_left (fun a p => match f (fst p) (snd p) a with R _ s2 _ => s2 end) l s) i.
Proof.
  induction l; simpl; intros.
  exists (sincr_refl s); auto.
  destruct a as [x y]. unfold bind. simpl. destruct (f x y s) as [xx s1 i1].
  destruct (IHl s1) as [i2 EQ]. rewrite EQ. econstructor; eauto.
Qed.

Lemma ptree_mfold_spec:
  forall (A: Type) (f: positive -> A -> mon unit) t s x s' i,
  ptree_mfold f t s = R x s' i ->
  exists i', mlist_iter2 f (PTree.elements t) s = R tt s' i'.
Proof.
  intros.
  destruct (mlist_iter2_fold _ _ f (PTree.elements t) s) as [i' EQ].
  unfold ptree_mfold in H. inv H. rewrite PTree.fold_spec.
  econstructor. eexact EQ.
Qed.

(** ** Relational specification of the translation of moves *)

Inductive tr_moves (c: code) : node -> list reg -> list reg -> node -> Prop :=
  | tr_moves_cons: forall pc1 src srcs dst dsts pc2 pc3,
      tr_moves c pc1 srcs dsts pc2 ->
      c!pc2 = Some(Iop Omove (src :: nil) dst pc3) ->
      tr_moves c pc1 (src :: srcs) (dst :: dsts) pc3
  | tr_moves_nil: forall srcs dsts pc,
      srcs = nil \/ dsts = nil ->
      tr_moves c pc srcs dsts pc.

Lemma add_moves_unchanged:
  forall srcs dsts pc2 s pc1 s' i pc,
  add_moves srcs dsts pc2 s = R pc1 s' i ->
  Plt pc s.(st_nextnode) \/ Ple s'.(st_nextnode) pc ->
  s'.(st_code)!pc = s.(st_code)!pc.
Proof.
  induction srcs; simpl; intros.
  monadInv H. auto.
  destruct dsts; monadInv H. auto.
  transitivity (st_code s0)!pc. eapply IHsrcs; eauto. monadInv EQ; simpl. xomega.
  monadInv EQ; simpl. apply PTree.gso.
  inversion INCR0; simpl in *. xomega.
Qed.

Lemma add_moves_spec:
  forall srcs dsts pc2 s pc1 s' i c,
  add_moves srcs dsts pc2 s = R pc1 s' i ->
  (forall pc, Ple s.(st_nextnode) pc -> Plt pc s'.(st_nextnode) -> c!pc = s'.(st_code)!pc) ->
  tr_moves c pc1 srcs dsts pc2.
Proof.
  induction srcs; simpl; intros.
  monadInv H. apply tr_moves_nil; auto.
  destruct dsts; monadInv H. apply tr_moves_nil; auto.
  apply tr_moves_cons with x. eapply IHsrcs; eauto.
  intros. inversion INCR. apply H0; xomega.
  monadInv EQ.
  rewrite H0. erewrite add_moves_unchanged; eauto.
  simpl. apply PTree.gss.
  simpl. xomega.
  xomega.
  inversion INCR; inversion INCR0; simpl in *; xomega.
Qed.

(** ** Relational specification of CFG expansion *)

Section INLINING_SPEC.

Variable fenv: funenv.

Definition context_below (ctx1 ctx2: context): Prop :=
  Ple (Pplus ctx1.(dreg) ctx1.(mreg)) ctx2.(dreg).

Definition context_stack_call (ctx1 ctx2: context): Prop :=
  ctx1.(mstk) >= 0 /\ ctx1.(dstk) + ctx1.(mstk) <= ctx2.(dstk).

Definition context_stack_tailcall (ctx1: context) (f: function) (ctx2: context) : Prop :=
  ctx2.(dstk) = align ctx1.(dstk) (min_alignment f.(fn_stacksize)).

Section INLINING_BODY_SPEC.

Variable stacksize: Z.

Inductive tr_instr: context -> node -> instruction -> code -> Prop :=
  | tr_nop: forall ctx pc c s,
      c!(spc ctx pc) = Some (Inop (spc ctx s)) ->
      tr_instr ctx pc (Inop s) c
  | tr_op: forall ctx pc c op args res s,
      Ple res ctx.(mreg) ->
      c!(spc ctx pc) = Some (Iop (sop ctx op) (sregs ctx args) (sreg ctx res) (spc ctx s)) ->
      tr_instr ctx pc (Iop op args res s) c
  | tr_load: forall ctx pc c chunk addr args res s,
      Ple res ctx.(mreg) ->
      c!(spc ctx pc) = Some (Iload chunk (saddr ctx addr) (sregs ctx args) (sreg ctx res) (spc ctx s)) ->
      tr_instr ctx pc (Iload chunk addr args res s) c
  | tr_store: forall ctx pc c chunk addr args src s,
      c!(spc ctx pc) = Some (Istore chunk (saddr ctx addr) (sregs ctx args) (sreg ctx src) (spc ctx s)) ->
      tr_instr ctx pc (Istore chunk addr args src s) c
  | tr_call: forall ctx pc c sg ros args res s,
      Ple res ctx.(mreg) ->
      c!(spc ctx pc) = Some (Icall sg (sros ctx ros) (sregs ctx args) (sreg ctx res) (spc ctx s)) ->
      tr_instr ctx pc (Icall sg ros args res s) c
  | tr_call_inlined:forall ctx pc sg id args res s c f pc1 ctx',
      Ple res ctx.(mreg) ->
      fenv!id = Some f ->
      c!(spc ctx pc) = Some(Inop pc1) ->
      tr_moves c pc1 (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)) ->
      tr_funbody ctx' f c ->
      ctx'.(retinfo) = Some(spc ctx s, sreg ctx res) ->
      context_below ctx ctx' ->
      context_stack_call ctx ctx' ->
      tr_instr ctx pc (Icall sg (inr _ id) args res s) c
  | tr_tailcall: forall ctx pc c sg ros args,
      c!(spc ctx pc) = Some (Itailcall sg (sros ctx ros) (sregs ctx args)) ->
      ctx.(retinfo) = None ->
      tr_instr ctx pc (Itailcall sg ros args) c
  | tr_tailcall_call: forall ctx pc c sg ros args res s,
      c!(spc ctx pc) = Some (Icall sg (sros ctx ros) (sregs ctx args) res s) ->
      ctx.(retinfo) = Some(s, res) ->
      tr_instr ctx pc (Itailcall sg ros args) c
  | tr_tailcall_inlined: forall ctx pc sg id args c f pc1 ctx',
      fenv!id = Some f ->
      c!(spc ctx pc) = Some(Inop pc1) ->
      tr_moves c pc1 (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)) ->
      tr_funbody ctx' f c ->
      ctx'.(retinfo) = ctx.(retinfo) ->
      context_below ctx ctx' ->
      context_stack_tailcall ctx f ctx' ->
      tr_instr ctx pc (Itailcall sg (inr _ id) args) c
  | tr_builtin: forall ctx pc c ef args res s,
      Ple res ctx.(mreg) ->
      c!(spc ctx pc) = Some (Ibuiltin ef (sregs ctx args) (sreg ctx res) (spc ctx s)) ->
      tr_instr ctx pc (Ibuiltin ef args res s) c
  | tr_cond: forall ctx pc cond args s1 s2 c,
      c!(spc ctx pc) = Some (Icond cond (sregs ctx args) (spc ctx s1) (spc ctx s2)) ->
      tr_instr ctx pc (Icond cond args s1 s2) c
  | tr_jumptable: forall ctx pc r tbl c,
      c!(spc ctx pc) = Some (Ijumptable (sreg ctx r) (List.map (spc ctx) tbl)) ->
      tr_instr ctx pc (Ijumptable r tbl) c
  | tr_return: forall ctx pc or c,
      c!(spc ctx pc) = Some (Ireturn (option_map (sreg ctx) or)) ->
      ctx.(retinfo) = None ->
      tr_instr ctx pc (Ireturn or) c
  | tr_return_inlined: forall ctx pc or c rinfo,
      c!(spc ctx pc) = Some (inline_return ctx or rinfo) ->
      ctx.(retinfo) = Some rinfo ->
      tr_instr ctx pc (Ireturn or) c

with tr_funbody: context -> function -> code -> Prop :=
  | tr_funbody_intro: forall ctx f c,
      (forall r, In r f.(fn_params) -> Ple r ctx.(mreg)) ->
      (forall pc i, f.(fn_code)!pc = Some i -> tr_instr ctx pc i c) ->
      ctx.(mstk) = Zmax f.(fn_stacksize) 0 ->
      (min_alignment f.(fn_stacksize) | ctx.(dstk)) ->
      ctx.(dstk) >= 0 -> ctx.(dstk) + ctx.(mstk) <= stacksize ->
      tr_funbody ctx f c.

Definition fenv_agree (fe: funenv) : Prop :=
  forall id f, fe!id = Some f -> fenv!id = Some f.

Section EXPAND_INSTR.

Variable fe: funenv.
Hypothesis FE: fenv_agree fe.

Variable rec: forall fe', (size_fenv fe' < size_fenv fe)%nat -> context -> function -> mon unit.

Hypothesis rec_unchanged:
  forall fe' (L: (size_fenv fe' < size_fenv fe)%nat) ctx f s x s' i pc,
  rec fe' L ctx f s = R x s' i ->
  Ple ctx.(dpc) s.(st_nextnode) ->
  Plt pc ctx.(dpc) ->
  s'.(st_code)!pc = s.(st_code)!pc.

Remark set_instr_other:
  forall pc instr s x s' i pc',
  set_instr pc instr s = R x s' i ->
  pc' <> pc ->
  s'.(st_code)!pc' = s.(st_code)!pc'.
Proof.
  intros. monadInv H; simpl. apply PTree.gso; auto.
Qed.

Remark set_instr_same:
  forall pc instr s x s' i c,
  set_instr pc instr s = R x s' i ->
  c!(pc) = s'.(st_code)!pc ->
  c!(pc) = Some instr.
Proof.
  intros. rewrite H0. monadInv H; simpl. apply PTree.gss.
Qed.

Lemma expand_instr_unchanged:
  forall ctx pc instr s x s' i pc',
  expand_instr fe rec ctx pc instr s = R x s' i ->
  Ple ctx.(dpc) s.(st_nextnode) ->
  Plt pc' s.(st_nextnode) ->
  pc' <> spc ctx pc ->
  s'.(st_code)!pc' = s.(st_code)!pc'.
Proof.
  generalize set_instr_other; intros A.
  intros. unfold expand_instr in H; destruct instr; eauto.
(* call *)
  destruct (can_inline fe s1). eauto.
  monadInv H. unfold inline_function in EQ. monadInv EQ.
  transitivity (s2.(st_code)!pc'). eauto.
  transitivity (s5.(st_code)!pc'). eapply add_moves_unchanged; eauto.
    left. inversion INCR5. inversion INCR3. monadInv EQ1; simpl in *. xomega.
  transitivity (s4.(st_code)!pc'). eapply rec_unchanged; eauto.
    simpl. monadInv EQ; simpl. monadInv EQ1; simpl. xomega.
    simpl. monadInv EQ1; simpl. auto.
  monadInv EQ; simpl. monadInv EQ1; simpl. auto.
(* tailcall *)
  destruct (can_inline fe s1).
  destruct (retinfo ctx) as [[rpc rreg]|]; eauto.
  monadInv H. unfold inline_tail_function in EQ. monadInv EQ.
  transitivity (s2.(st_code)!pc'). eauto.
  transitivity (s5.(st_code)!pc'). eapply add_moves_unchanged; eauto.
    left. inversion INCR5. inversion INCR3. monadInv EQ1; simpl in *. xomega.
  transitivity (s4.(st_code)!pc'). eapply rec_unchanged; eauto.
    simpl. monadInv EQ; simpl. monadInv EQ1; simpl. xomega.
    simpl. monadInv EQ1; simpl. auto.
  monadInv EQ; simpl. monadInv EQ1; simpl. auto.
(* return *)
  destruct (retinfo ctx) as [[rpc rreg]|]; eauto.
Qed.

Lemma iter_expand_instr_unchanged:
  forall ctx pc l s x s' i,
  mlist_iter2 (expand_instr fe rec ctx) l s = R x s' i ->
  Ple ctx.(dpc) s.(st_nextnode) ->
  Plt pc s.(st_nextnode) ->
  ~In pc (List.map (spc ctx) (List.map (@fst _ _) l)) ->
  list_norepet (List.map (@fst _ _) l) ->
  s'.(st_code)!pc = s.(st_code)!pc.
Proof.
  induction l; simpl; intros.
  (* base case *)
  monadInv H. auto.
  (* inductive case *)
  destruct a as [pc1 instr1]; simpl in *.
  monadInv H. inv H3.
  transitivity ((st_code s0)!pc).
  eapply IHl; eauto. destruct INCR; xomega. destruct INCR; xomega.
  eapply expand_instr_unchanged; eauto.
Qed.

Lemma expand_cfg_rec_unchanged:
  forall ctx f s x s' i pc,
  expand_cfg_rec fe rec ctx f s = R x s' i ->
  Ple ctx.(dpc) s.(st_nextnode) ->
  Plt pc ctx.(dpc) ->
  s'.(st_code)!pc = s.(st_code)!pc.
Proof.
  intros. unfold expand_cfg_rec in H. monadInv H. inversion EQ.
  transitivity ((st_code s0)!pc).
  exploit ptree_mfold_spec; eauto. intros [INCR' ITER].
  eapply iter_expand_instr_unchanged; eauto.
    subst s0; auto.
    subst s0; simpl. xomega.
    red; intros. exploit list_in_map_inv; eauto. intros [pc1 [A B]].
    subst pc. unfold spc in H1. eapply shiftpos_not_below; eauto.
    apply PTree.elements_keys_norepet.
  subst s0; auto.
Qed.

Hypothesis rec_spec:
  forall fe' (L: (size_fenv fe' < size_fenv fe)%nat) ctx f s x s' i c,
  rec fe' L ctx f s = R x s' i ->
  fenv_agree fe' ->
  Ple (ctx.(dpc) + max_pc_function f) s.(st_nextnode) ->
  ctx.(mreg) = max_reg_function f ->
  Ple (Pplus ctx.(dreg) ctx.(mreg)) s.(st_nextreg) ->
  ctx.(mstk) >= 0 ->
  ctx.(mstk) = Zmax (fn_stacksize f) 0 ->
  (min_alignment (fn_stacksize f) | ctx.(dstk)) ->
  ctx.(dstk) >= 0 ->
  s'.(st_stksize) <= stacksize ->
  (forall pc, Ple ctx.(dpc) pc -> Plt pc s'.(st_nextnode) -> c!pc = s'.(st_code)!pc) ->
  tr_funbody ctx f c.

Remark min_alignment_pos:
  forall sz, min_alignment sz > 0.
Proof.
  intros; unfold min_alignment.
  destruct (zle sz 1). omega. destruct (zle sz 2). omega. destruct (zle sz 4); omega.
Qed.

Ltac inv_incr :=
  match goal with
  | [ H: sincr _ _ |- _ ] => destruct H; inv_incr
  | _ => idtac
  end.

Lemma expand_instr_spec:
  forall ctx pc instr s x s' i c,
  expand_instr fe rec ctx pc instr s = R x s' i ->
  (forall r, instr_defs instr = Some r -> Ple r ctx.(mreg)) ->
  Plt (spc ctx pc) s.(st_nextnode) ->
  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->
  ctx.(mstk) >= 0 -> ctx.(dstk) >= 0 ->
  s'.(st_stksize) <= stacksize ->
  (forall pc', Ple s.(st_nextnode) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->
  c!(spc ctx pc) = s'.(st_code)!(spc ctx pc) ->
  tr_instr ctx pc instr c.
Proof.
  intros until c; intros EXP DEFS OPC OREG STK1 STK2 STK3 S1 S2.
  generalize set_instr_same; intros BASE.
  unfold expand_instr in EXP; destruct instr; simpl in DEFS;
  try (econstructor; eauto; fail).
(* call *)
  destruct (can_inline fe s1) as [|id f P Q].
  (* not inlined *)
  eapply tr_call; eauto.
  (* inlined *)
  subst s1.
  monadInv EXP. unfold inline_function in EQ; monadInv EQ.
  set (ctx' := callcontext ctx x1 x2 (max_reg_function f) (fn_stacksize f) n r).
  inversion EQ0; inversion EQ1; inversion EQ. inv_incr.
  apply tr_call_inlined with (pc1 := x0) (ctx' := ctx') (f := f); auto.
  eapply BASE; eauto.
  eapply add_moves_spec; eauto.
    intros. rewrite S1. eapply set_instr_other; eauto. unfold node; xomega.
    xomega. xomega.
  eapply rec_spec; eauto.
    red; intros. rewrite PTree.grspec in H. destruct (PTree.elt_eq id0 id); try discriminate. auto.
    simpl. subst s2; simpl in *; xomega.
    simpl. subst s3; simpl in *; xomega.
    simpl. xomega.
    simpl. apply align_divides. apply min_alignment_pos.
    assert (dstk ctx + mstk ctx <= dstk ctx'). simpl. apply align_le. apply min_alignment_pos. omega.
    omega.
    intros. simpl in H. rewrite S1.
    transitivity s1.(st_code)!pc0. eapply set_instr_other; eauto. unfold node in *; xomega.
    eapply add_moves_unchanged; eauto. unfold node in *; xomega. xomega.
  red; simpl. subst s2; simpl in *. xomega.
  red; simpl. split. auto. apply align_le. apply min_alignment_pos.
(* tailcall *)
  destruct (can_inline fe s1) as [|id f P Q].
  (* not inlined *)
  destruct (retinfo ctx) as [[rpc rreg] | ] eqn:?.
  (* turned into a call *)
  eapply tr_tailcall_call; eauto.
  (* preserved *)
  eapply tr_tailcall; eauto.
  (* inlined *)
  subst s1.
  monadInv EXP. unfold inline_function in EQ; monadInv EQ.
  set (ctx' := tailcontext ctx x1 x2 (max_reg_function f) (fn_stacksize f)) in *.
  inversion EQ0; inversion EQ1; inversion EQ. inv_incr.
  apply tr_tailcall_inlined with (pc1 := x0) (ctx' := ctx') (f := f); auto.
  eapply BASE; eauto.
  eapply add_moves_spec; eauto.
    intros. rewrite S1. eapply set_instr_other; eauto. unfold node; xomega. xomega. xomega.
  eapply rec_spec; eauto.
    red; intros. rewrite PTree.grspec in H. destruct (PTree.elt_eq id0 id); try discriminate. auto.
    simpl. subst s3; simpl in *. subst s2; simpl in *. xomega.
    simpl. subst s3; simpl in *; xomega.
    simpl. xomega.
    simpl. apply align_divides. apply min_alignment_pos.
    assert (dstk ctx <= dstk ctx'). simpl. apply align_le. apply min_alignment_pos. omega.
    omega.
    intros. simpl in H. rewrite S1.
    transitivity s1.(st_code)!pc0. eapply set_instr_other; eauto. unfold node in *; xomega.
    eapply add_moves_unchanged; eauto. unfold node in *; xomega. xomega.
  red; simpl.
subst s2; simpl in *; xomega.
  red; auto.
(* return *)
  destruct (retinfo ctx) as [[rpc rreg] | ] eqn:?.
  (* inlined *)
  eapply tr_return_inlined; eauto.
  (* unchanged *)
  eapply tr_return; eauto.
Qed.

Lemma iter_expand_instr_spec:
  forall ctx l s x s' i c,
  mlist_iter2 (expand_instr fe rec ctx) l s = R x s' i ->
  list_norepet (List.map (@fst _ _) l) ->
  (forall pc instr r, In (pc, instr) l -> instr_defs instr = Some r -> Ple r ctx.(mreg)) ->
  (forall pc instr, In (pc, instr) l -> Plt (spc ctx pc) s.(st_nextnode)) ->
  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->
  ctx.(mstk) >= 0 -> ctx.(dstk) >= 0 ->
  s'.(st_stksize) <= stacksize ->
  (forall pc', Ple s.(st_nextnode) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->
  (forall pc instr, In (pc, instr) l -> c!(spc ctx pc) = s'.(st_code)!(spc ctx pc)) ->
  forall pc instr, In (pc, instr) l -> tr_instr ctx pc instr c.
Proof.
  induction l; simpl; intros.
  (* base case *)
  contradiction.
  (* inductive case *)
  destruct a as [pc1 instr1]; simpl in *. inv H0. monadInv H. inv_incr.
  assert (A: Ple ctx.(dpc) s0.(st_nextnode)).
    assert (B: Plt (spc ctx pc) (st_nextnode s)) by eauto.
    unfold spc in B. generalize (shiftpos_above pc (dpc ctx)). xomega.
  destruct H9. inv H.
  (* same pc *)
  eapply expand_instr_spec; eauto.
  omega.
  intros.
    transitivity ((st_code s')!pc').
    apply H7. auto. xomega.
    eapply iter_expand_instr_unchanged; eauto.
    red; intros. rewrite list_map_compose in H9. exploit list_in_map_inv; eauto.
    intros [[pc0 instr0] [P Q]]. simpl in P.
    assert (Plt (spc ctx pc0) (st_nextnode s)) by eauto. xomega.
  transitivity ((st_code s')!(spc ctx pc)).
    eapply H8; eauto.
    eapply iter_expand_instr_unchanged; eauto.
    assert (Plt (spc ctx pc) (st_nextnode s)) by eauto. xomega.
    red; intros. rewrite list_map_compose in H. exploit list_in_map_inv; eauto.
    intros [[pc0 instr0] [P Q]]. simpl in P.
    assert (pc = pc0) by (eapply shiftpos_inj; eauto). subst pc0.
    elim H12. change pc with (fst (pc, instr0)). apply List.in_map; auto.
  (* older pc *)
  inv_incr. eapply IHl; eauto.
  intros. eapply Plt_le_trans. eapply H2. right; eauto. xomega.
  intros; eapply Ple_trans; eauto.
  intros. apply H7; auto. xomega.
Qed.

Lemma expand_cfg_rec_spec:
  forall ctx f s x s' i c,
  expand_cfg_rec fe rec ctx f s = R x s' i ->
  Ple (ctx.(dpc) + max_pc_function f) s.(st_nextnode) ->
  ctx.(mreg) = max_reg_function f ->
  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->
  ctx.(mstk) >= 0 ->
  ctx.(mstk) = Zmax (fn_stacksize f) 0 ->
  (min_alignment (fn_stacksize f) | ctx.(dstk)) ->
  ctx.(dstk) >= 0 ->
  s'.(st_stksize) <= stacksize ->
  (forall pc', Ple ctx.(dpc) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->
  tr_funbody ctx f c.
Proof.
  intros. unfold expand_cfg_rec in H. monadInv H. inversion EQ.
  constructor.
  intros. rewrite H1. eapply max_reg_function_params; eauto.
  intros. exploit ptree_mfold_spec; eauto. intros [INCR' ITER].
  eapply iter_expand_instr_spec; eauto.
    apply PTree.elements_keys_norepet.
    intros. rewrite H1. eapply max_reg_function_def with (i := instr); eauto.
    eapply PTree.elements_complete; eauto.
  intros.
    assert (Ple pc0 (max_pc_function f)).
      eapply max_pc_function_sound. eapply PTree.elements_complete; eauto.
      eapply Plt_le_trans. apply shiftpos_below. subst s0; simpl; xomega.
  subst s0; simpl; auto.
  intros. apply H8; auto. subst s0; simpl in H11; xomega.
  intros. apply H8. apply shiftpos_above.
  assert (Ple pc0 (max_pc_function f)).
    eapply max_pc_function_sound. eapply PTree.elements_complete; eauto.
  eapply Plt_le_trans. apply shiftpos_below. inversion i; xomega.
  apply PTree.elements_correct; auto.
  auto. auto. auto.
  inversion INCR0. subst s0; simpl in STKSIZE; xomega.
Qed.

End EXPAND_INSTR.

Lemma expand_cfg_unchanged:
  forall fe ctx f s x s' i pc,
  expand_cfg fe ctx f s = R x s' i ->
  Ple ctx.(dpc) s.(st_nextnode) ->
  Plt pc ctx.(dpc) ->
  s'.(st_code)!pc = s.(st_code)!pc.
Proof.
  intros fe0; pattern fe0. apply well_founded_ind with (R := ltof _ size_fenv).
  apply well_founded_ltof.
  intros. unfold expand_cfg in H0. rewrite unroll_Fixm in H0.
  eapply expand_cfg_rec_unchanged; eauto. assumption.
Qed.

Lemma expand_cfg_spec:
  forall fe ctx f s x s' i c,
  expand_cfg fe ctx f s = R x s' i ->
  fenv_agree fe ->
  Ple (ctx.(dpc) + max_pc_function f) s.(st_nextnode) ->
  ctx.(mreg) = max_reg_function f ->
  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->
  ctx.(mstk) >= 0 ->
  ctx.(mstk) = Zmax (fn_stacksize f) 0 ->
  (min_alignment (fn_stacksize f) | ctx.(dstk)) ->
  ctx.(dstk) >= 0 ->
  s'.(st_stksize) <= stacksize ->
  (forall pc', Ple ctx.(dpc) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->
  tr_funbody ctx f c.
Proof.
  intros fe0; pattern fe0. apply well_founded_ind with (R := ltof _ size_fenv).
  apply well_founded_ltof.
  intros. unfold expand_cfg in H0. rewrite unroll_Fixm in H0.
  eapply expand_cfg_rec_spec; eauto.
  simpl. intros. eapply expand_cfg_unchanged; eauto. assumption.
Qed.

End INLINING_BODY_SPEC.

(** ** Relational specification of the translation of a function *)

Inductive tr_function: function -> function -> Prop :=
  | tr_function_intro: forall f f' ctx,
      tr_funbody f'.(fn_stacksize) ctx f f'.(fn_code) ->
      ctx.(dstk) = 0 ->
      ctx.(retinfo) = None ->
      f'.(fn_sig) = f.(fn_sig) ->
      f'.(fn_params) = sregs ctx f.(fn_params) ->
      f'.(fn_entrypoint) = spc ctx f.(fn_entrypoint) ->
      0 <= fn_stacksize f' < Int.max_unsigned ->
      tr_function f f'.

Lemma transf_function_spec:
  forall f f', transf_function fenv f = OK f' -> tr_function f f'.
Proof.
  intros. unfold transf_function in H.
  destruct (expand_function fenv f initstate) as [ctx s i] eqn:?.
  destruct (zlt (st_stksize s) Int.max_unsigned); inv H.
  monadInv Heqr. set (ctx := initcontext x x0 (max_reg_function f) (fn_stacksize f)) in *.
Opaque initstate.
  destruct INCR3. inversion EQ1. inversion EQ.
  apply tr_function_intro with ctx; auto.
  eapply expand_cfg_spec with (fe := fenv); eauto.
    red; auto.
    unfold ctx; rewrite <- H1; rewrite <- H2; rewrite <- H3; simpl. xomega.
    unfold ctx; rewrite <- H0; rewrite <- H1; simpl. xomega.
    simpl. xomega.
    simpl. apply Zdivide_0.
    simpl. omega.
  simpl. omega.
  simpl. split; auto. destruct INCR2. destruct INCR1. destruct INCR0. destruct INCR.
  simpl. change 0 with (st_stksize initstate). omega.
Qed.

End INLINING_SPEC.


Require Import LibTactics.
Require Import Metalib.Metatheory.

Require Import
        syntax_ott
        syntaxb_ott
        rules_inf
        rulesb_inf
        Infrastructure
        Infrastructure_b
        Deterministic
        Typing_b
        Type_Safety
        ttyping.

Require Import List. Import ListNotations.
Require Import Arith Omega.
Require Import Strings.String.

Require Import Omega.

Ltac size_ind_auto :=
  ( eapply_first_lt_hyp ;
    try reflexivity;
    try omega ;
    try eauto ).

Lemma principle_if: forall v A t,
    value v -> ttyping nil v Inf A t -> principal_type v = A.
Proof.
     introv H typ.
     inductions H; inverts* typ; eauto.
Qed.

Lemma value_valueb: forall e t A,
 ttyping nil e Inf A t -> value e ->
 valueb t.
Proof.
  introv typ H. gen t A.
  inductions H; intros;
  try solve [inverts* typ].
  - inverts typ.
    pick fresh x.
    forwards*: H2.
    forwards*: lc_lcb H.
  - inverts typ.
    forwards*: value_lc H.
    forwards*: lc_lcb H3.
    inverts* H3.
    forwards*: IHvalue.
    forwards*: principle_if H4.
    rewrite H7 in H0. inverts H0.
    eapply valueb_fanno; eauto.
  - inverts typ.
    inverts* H3.
    forwards*: IHvalue.
    forwards*: principle_if H1.
    rewrite H5 in H.
    apply valueb_dyn; eauto.
Qed.

Lemma sim_refl: forall A,
 sim A A.
Proof.
  intros.
  inductions A; eauto.
Qed.

Lemma fillb_cast: forall v A B,
  (trm_cast v A B) = (fillb (castCtxb A B)  v).
Proof.
  introv.
  eauto.
Qed.

Lemma Tred_soundness: forall v t v' A,
  ttyping nil (e_anno v A) Inf A t->
  value v ->
  TypedReduce v A (e_exp v') ->
  exists t', t ->* (t_term t') /\ ttyping nil v' Inf A t'.
Proof.
  introv  Typ val Red. gen t.
  inductions Red; intros.
  - inverts Typ.
    inverts H3; try solve[inverts val].
    exists*.
    forwards*: principle_if H1.
  - inverts Typ.
    inverts H2.
    exists* (trm_cast (trm_abs t_dyn t0) (t_arrow t_dyn t_dyn) t_dyn).
    forwards*: principle_if H0.
  - inverts Typ.
    inverts H1.
    inverts H.
    exists. split.
    apply star_one.
    apply bStep_lit; eauto.
    apply ttyp_lit; eauto.
  - inverts Typ.
    inverts H2.
    inverts H0.
    inverts H5.
    exists* (trm_cast (trm_abs t_dyn t) (t_arrow t_dyn t_dyn) t_dyn).
    splits*.
    apply star_one.
    apply bStep_dd; eauto.
    apply valueb_dyn; eauto.
    forwards*: value_valueb val.
    inverts* H2.
    inverts val.
    exists. split.
    apply star_one.
    apply bStep_dd; eauto.
    apply valueb_dyn; eauto.
    forwards*: value_valueb H0.
    forwards*: principle_if H0.
    rewrite H5 in H6.
    auto.
    simpl.
    apply ttyp_anno; eauto.
  - inverts Typ.
    inverts H2.
    exists.
    splits*.
    apply ttyp_anno; eauto.
    apply ttyp_sim; eauto.
    unfold not; intros nt; inverts* nt. inverts H1.
    forwards*: principle_if H0.
    rewrite H2 in H.
    inverts* H.
    inverts H5.
    inverts H6.
    rewrite <- TEMP in H.
    rewrite <- TEMP in H4.
    exists. split.
    apply star_one.
    apply bStep_anyd; eauto.
    forwards*: value_valueb val.
    simpl.
    apply ttyp_anno; eauto.
    apply ttyp_sim; eauto.
    apply ttyp_anno; eauto.
    apply ttyp_sim; eauto.
    rewrite <- TEMP in H0. auto.
    unfold not; intros nt; inverts nt. inverts H2.
    rewrite <- TEMP in H4.
    exfalso. apply H4. reflexivity.
  -
    inverts Typ. inverts H2. inverts H0.
    inverts H6.
    +
    inverts H. inverts H2. inverts* H6.
    destruct(eq_type A0); destruct(eq_type B); substs;
    try solve[exfalso; apply H; eauto].
    exists.
    splits.
    eapply star_trans.
    apply star_one.
    apply bStep_dyna; eauto.
    forwards*: value_valueb val.
    apply star_one.
    rewrite fillb_cast.
    apply do_stepb; eauto.
    apply bStep_vany; eauto.
    forwards*: value_valueb val. inverts* H2.
    simpl.
    apply ttyp_anno; eauto.
    eapply ttyp_sim; eauto.
    unfold not; intros nt; inverts nt. inverts H2.
    exists.
    splits.
    eapply star_trans.
    apply star_one.
    apply bStep_dyna; eauto.
    forwards*: value_valueb val.
    apply star_one.
    rewrite fillb_cast.
    apply do_stepb; eauto.
    apply bStep_vany; eauto.
    forwards*: value_valueb val. inverts* H6.
    simpl.
    apply ttyp_anno; eauto.
    eapply ttyp_sim; eauto.
    unfold not; intros nt; inverts nt. inverts H6.
    exists.
    splits.
    eapply star_trans.
    apply star_one.
    apply bStep_dyna; eauto.
    forwards*: value_valueb val.
    apply star_one.
    rewrite fillb_cast.
    apply do_stepb; eauto.
    apply bStep_vany; eauto.
    forwards*: value_valueb val. inverts* H7.
    simpl.
    apply ttyp_anno; eauto.
    eapply ttyp_sim; eauto.
    unfold not; intros nt; inverts nt. inverts H7.
    +
    exfalso; apply H5; eauto.
  -
    inverts Typ. inverts* H1. inverts* H.
    inverts* H4.
    exists. splits.
    apply star_one.
    apply bStep_vany; eauto.
    forwards*: value_valueb val. inverts* H.
    apply ttyp_anno; eauto.
    exfalso; apply H3; eauto.
  - inverts Typ. inverts val.
    inverts H4. inverts H2. inverts H10.
    exfalso; apply H1; eauto.
    forwards*: principle_if H2.
    rewrite H10 in H0.
    rewrite H10 in H3.
    exists. split.
    eapply bstep_n.
    apply bStep_dyna; eauto.
    apply valueb_dyn; eauto.
    forwards*: value_valueb H5.
    inverts* H. inverts* H. inverts* H.
    rewrite fillb_cast.
    eapply bstep_n.
    apply do_stepb; eauto.
    inverts H. inverts H12. inverts* H13.
    inverts H0. rewrite <- TEMP in H3. inverts H3.
    apply bStep_vany; eauto.
    forwards*: value_valueb H5.
    rewrite <- TEMP in H3. inverts H3.
    apply bstep_refl.
    apply ttyp_anno; eauto.
    inverts H. inverts H12. inverts* H13.
    inverts H0. rewrite <- TEMP in H3. inverts H3.
    rewrite <- TEMP in H2.
    apply ttyp_sim; eauto.
    rewrite <- TEMP in H3. inverts H3.
  - inverts Typ. inverts val.
    inverts H2.
    inverts H0. inverts H7.
    exfalso; apply H; eauto.
    forwards*: principle_if H0.
    exists. split.
    apply star_one.
    rewrite H7. rewrite H7 in H1.
    apply bStep_vany; eauto.
    forwards*: value_valueb H3.
    rewrite H7. auto.
Qed.

Theorem soundness_mul_two: forall e t e' A dir ,
  ttyping nil e dir A t->
  step e (e_exp e') ->
  exists t', t ->* (t_term t') /\ ttyping nil e' dir A t' .
Proof.
  introv Typ Red. gen A t dir.
  inductions Red; intros.
  - destruct E; unfold fill in *.
    + inverts Typ.
      forwards*: IHRed H3. inverts H0. inverts H1.
      exists. split.
      apply multi_red_app2; eauto.
      inverts H.
      forwards*: lc_lcb H4.
      eapply ttyp_app; eauto.
      inverts H0.
      forwards*: IHRed H6. inverts H0. inverts H3.
      exists. split.
      apply star_trans with (b:= trm_cast (trm_app x t2) A0 A).
      apply multi_red_cast; auto.
      apply multi_red_app2; auto.
      inverts H.
      forwards*: lc_lcb H5.
      apply bstep_refl.
      apply ttyp_sim; eauto.
      unfold not; intros nt; inverts nt. inverts H3.
      forwards*: IHRed H6. inverts H0. inverts H3.
      exists. split.
      apply multi_red_cast.
      apply multi_red_app2.
      inverts H.
      forwards*: lc_lcb H5.
      apply multi_red_cast.
      apply H0.
      eapply ttyp_sim;eauto.
      unfold not; intros nt; inverts nt. inverts H3.
      forwards*: IHRed H3. inverts H0. inverts H1.
      exists. split.
      apply multi_red_app2.
      inverts H.
      forwards*: lc_lcb H4.
      apply multi_red_cast.
      apply H0.
      eapply ttyp_appd;eauto.
    + inverts Typ.
      *
      inverts H.
      forwards*: value_valueb H2.
      forwards*: IHRed H7. inverts H0. inverts H4.
      exists. split.
      forwards: multi_red_app H H0.
      apply H4.
      eapply ttyp_app; eauto.
      *
      inverts H. inverts H0.
      forwards*: value_valueb H5.
      forwards*: IHRed H8. inverts H0. inverts H3.
      exists. split.
      apply multi_red_cast.
      forwards: multi_red_app H H0.
      apply H3.
      eapply ttyp_sim; eauto.
      unfold not; intros nt; inverts nt. inverts H3.
      forwards* h1: principle_if H7.
      rewrite h1 in H4. inverts H4.
      *
      inverts H.
      forwards* h1: principle_if H3.
      rewrite h1 in H1. inverts H1.
    + inverts Typ.
      * forwards*: IHRed H6. inverts H0. inverts H1.
        exists. split.
        apply H0.
        apply ttyp_anno; eauto.
      * inverts H0.
        forwards*: IHRed H5. inverts H0. inverts H3.
        exists. split.
        apply multi_red_cast.
        apply H0.
        apply ttyp_sim;eauto.
        unfold not; intros nt; inverts nt. inverts H3.
  - inverts* Typ.
    * inverts H5.
      assert(ttyping nil (e_anno v t_dyn) Inf t_dyn t2).
      apply ttyp_anno; auto.
      inverts H9; try solve[inverts H0].

      forwards*: lc_lcb H.
      inverts H1;
      try solve[inverts* H8].
      exists. splits.
      apply star_one.
      apply bStep_beta; eauto.
      forwards*: value_valueb H0.
      apply ttyp_anno; auto.
      pick fresh y.
      forwards*: H7.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H1.
      eapply ttyp_anno; eauto.
      unfold not; intros nt; inverts nt; inverts H5.

      forwards*: value_valueb H0.
      forwards*: Tred_soundness H1.
      destruct H8. destruct H8.
      exists. split.
      apply star_trans with (b:= (trm_app (trm_abs t_dyn t) x)).
      apply multi_red_app; eauto. forwards*: lc_lcb H.
      apply star_one.
      apply bStep_beta; eauto.
      forwards*: lc_lcb H.
      forwards*: Tred_value H1.
      forwards*: value_valueb H9.
      apply ttyp_anno; eauto.
      pick fresh y.
      forwards*: H7.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H10. auto.
      forwards*: TypedReduce_nlambda2 H1.
    * inverts H2. inverts H8.
      assert(ttyping nil (e_anno v t_dyn) Inf t_dyn t2).
      apply ttyp_anno; auto. inverts H9; try solve[inverts H0].

      exists. split.
      apply star_one.
      rewrite fillb_cast.
      apply do_stepb; eauto.
      apply bStep_beta; eauto.
      forwards*: lc_lcb H.
      forwards*: value_valueb H0.
      apply ttyp_sim; eauto.
      apply ttyp_anno; eauto.
      inverts H1; try solve[inverts* H8].
      pick fresh y.
      forwards*: H10.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H1.
      apply ttyp_anno; eauto.
      unfold not; intros nt; inverts nt. inverts H6.
      unfold not; intros nt; inverts nt. inverts H6.

      forwards*: value_valueb H5.
      forwards*: Tred_soundness H1.
      destruct H9. destruct H9.
      exists. split.
      apply star_trans with (b:= trm_cast (trm_app (trm_abs t_dyn t) x) t_dyn A).
      apply multi_red_cast; eauto.
      apply multi_red_app; eauto. forwards*: lc_lcb H.
      apply star_trans with (b := trm_cast (t ^^' x) t_dyn A).
      apply multi_red_cast; auto.
      apply star_one.
      apply bStep_beta; eauto.
      forwards*: lc_lcb H.
      forwards*: Tred_value H1.
      forwards*: value_valueb H11.
      apply bstep_refl.
      apply ttyp_sim; eauto.
      apply ttyp_anno; eauto.
      pick fresh y.
      forwards*: H10.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H12. auto.
      forwards*: TypedReduce_nlambda2 H1.
      unfold not; intros nt; inverts nt. inverts H12.
      inverts H8.
    *
       inverts* H5.
  -  inverts* Typ.
    * inverts* H5. forwards*: lc_lcb H.
      inverts* H10.
      assert(ttyping nil (e_anno v A1) Inf A1 t2).
      apply ttyp_anno; auto.
      inverts* H9.
      forwards*: value_lc H0.
      forwards*: lc_lcb H5.
      exists*. split.
      apply star_one.
      apply bStep_beta; eauto.
      apply ttyp_anno; eauto.
      pick fresh y.
      forwards*: H7.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H8. inverts H1.
      apply ttyp_anno; eauto.
      inverts* H1.
      unfold not; intros nt; inverts nt. inverts H1.

      forwards*: lc_lcb H.
      inverts H1;
      try solve[inverts* H8].
      exists. splits.
      apply star_one.
      apply bStep_beta; eauto.
      forwards*: value_valueb H0.
      apply ttyp_anno; auto.
      pick fresh y.
      forwards*: H7.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H1.
      eapply ttyp_anno; eauto.
      unfold not; intros nt; inverts nt; inverts H6.
      inverts* H9.

      forwards*: value_valueb H4.
      forwards*: Tred_soundness H3.
      destruct H9. destruct H9.
      exists. split.
      apply star_trans with (b:= trm_app (trm_abs A1 t) x ).
      apply multi_red_app; eauto.
      apply star_one.
      apply bStep_beta; eauto. forwards*: value_valueb H10.
      forwards*: Tred_value H1.
      apply ttyp_anno; eauto.
      pick fresh y.
      forwards*: H7.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H11. auto.
      forwards*: TypedReduce_nlambda2 H1.
      exfalso. apply H5. exists*.
    * inverts* H2. inverts H8. forwards*: lc_lcb H.
      inverts* H12.
      assert(ttyping nil (e_anno v A2) Inf A2 t2).
      apply ttyp_anno; auto.
      inverts* H9.
      forwards*: value_lc H0.
      forwards*: lc_lcb H7.
      exists. split.
      apply multi_red_cast.
      apply star_one.
      apply bStep_beta; eauto.
      eapply ttyp_sim; eauto.
      apply ttyp_anno; eauto.
      pick fresh y.
      forwards*: H10.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H9. inverts H1.
      apply ttyp_anno; eauto.
      inverts* H1.
      unfold not; intros nt; inverts nt. inverts H1.
      unfold not; intros nt; inverts nt. inverts H9.

      exists. split.
      apply multi_red_cast.
      eapply star_trans.
      apply multi_red_app; eauto.
      apply star_one.
      apply bStep_beta; eauto.
      forwards*: value_valueb H0.
      eapply ttyp_sim; eauto.
      apply ttyp_anno; eauto.
      pick fresh y.
      forwards*: H10.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H7.
      inverts* H1; try solve[inverts* H11].
      inverts* H1; try solve[inverts* H11].
      unfold not; intros nt; inverts nt. inverts H1.
      unfold not; intros nt; inverts nt. inverts H7.

      forwards*: value_valueb H6.
      forwards*: Tred_soundness H1.
      destruct H11. destruct H11.
      exists. split.
      apply multi_red_cast.
      apply star_trans with (b:= trm_app (trm_abs A2 t) x ).
      apply multi_red_app; eauto.
      apply star_one.
      apply bStep_beta; eauto. forwards*: value_valueb H12.
      forwards*: Tred_value H1.
      eapply ttyp_sim; eauto.
      apply ttyp_anno; eauto.
      pick fresh y.
      forwards*: H10.
      rewrite (subst_exp_intro y); auto.
      rewrite (subst_term_intro y); auto.
      eapply ttyping_c_subst_simpl; auto.
      apply H13. auto.
      forwards*: TypedReduce_nlambda2 H1.
      unfold not; intros nt; inverts nt. inverts H13.
      exfalso; apply H7; exists*.
      inverts* H8.
    *
     inverts* H5.
  - inverts Typ.
    + inverts H4. inverts H9. inverts H1.
      assert (ttyping nil (e_anno v A1) Inf A1 t2).
      apply ttyp_anno; eauto.
      inverts H8. forwards*: value_lc H.
      forwards*: lc_lcb H6.
      exists. split.
      apply star_one.
      apply bStep_abeta; eauto. inverts H2.
      apply ttyp_anno; eauto. apply ttyp_sim; eauto.
      eapply ttyp_app; eauto.
      inverts H0.
      apply ttyp_sim; eauto. apply BA_AB; auto.
      unfold not; intros nt; inverts nt. inverts H0.
      unfold not; intros nt; inverts nt. inverts H2.

      exists. split.
      eapply star_trans.
      apply multi_red_app; eauto.
     apply star_one.
     apply bStep_abeta; eauto.
     forwards*: value_valueb H.
     apply ttyp_anno; eauto.
     apply ttyp_sim; eauto.
     eapply ttyp_app; eauto.
     inverts* H0; try solve[inverts* H8].
     apply ttyp_sim; eauto.
     unfold not; intros nt; inverts nt. inverts H0.
     inverts* H2.
     unfold not; intros nt; inverts nt. inverts H6.

      forwards*: Tred_soundness H0. inverts* H8. inverts H9.
      exists. split.
      eapply star_trans.
      apply multi_red_app; eauto.
     apply star_one.
     apply bStep_abeta; eauto.
     forwards*: value_valueb H10.
     forwards*: Tred_value H0.  inverts* H2.
     apply ttyp_anno; eauto.
     apply ttyp_sim; eauto.
     eapply ttyp_app; eauto.
     apply ttyp_sim; eauto.
     apply BA_AB; auto.
     forwards*: TypedReduce_nlambda2 H0.
     unfold not; intros nt; inverts nt. inverts H2.
    +
      inverts H1. inverts H7. inverts H11. inverts H1. inverts H4.
      assert (ttyping nil (e_anno v A2) Inf A2 t2).
      apply ttyp_anno; eauto.
      inverts H8. forwards*: value_lc H.
      forwards*: lc_lcb H7.
      exists. split. apply multi_red_cast.
      apply star_one.
      apply bStep_abeta; eauto.
      apply ttyp_sim; eauto.
      apply ttyp_anno; eauto. apply ttyp_sim; eauto.
      eapply ttyp_app; eauto. apply ttyp_sim; eauto.
      inverts H0.
      apply ttyp_anno; eauto. apply BA_AB; auto.
      inverts H0.
      unfold not; intros nt; inverts nt. inverts H0.
      unfold not; intros nt; inverts nt. inverts H9.
      unfold not; intros nt; inverts nt. inverts H9.

      exists. split. apply multi_red_cast.
      eapply star_trans.
      apply multi_red_app; eauto.
     apply star_one.
     apply bStep_abeta; eauto.
     forwards*: value_valueb H.
     inverts* H0; try solve[inverts* H9].
     apply ttyp_sim; eauto.
     apply ttyp_anno; eauto.
     apply ttyp_sim; eauto.
     eapply ttyp_app; eauto.
     apply ttyp_sim; eauto.
     unfold not; intros nt; inverts nt. inverts H0.
     unfold not; intros nt; inverts nt. inverts H0.
     unfold not; intros nt; inverts nt. inverts H0.

      forwards*: Tred_soundness H0. inverts* H8. inverts H11.
      exists. split. apply multi_red_cast.
      eapply star_trans.
      apply multi_red_app; eauto.
     apply star_one.
     apply bStep_abeta; eauto.
     forwards*: value_valueb H13.
     forwards*: Tred_value H0.
     apply ttyp_sim; eauto.
     apply ttyp_anno; eauto.
     apply ttyp_sim; eauto.
     eapply ttyp_app; eauto.
     apply ttyp_sim; eauto.
     apply BA_AB; auto.
     forwards*: TypedReduce_nlambda2 H0.
     unfold not; intros nt; inverts nt. inverts H11.
     unfold not; intros nt; inverts nt. inverts H11.
     inverts* H7.
    +
    inverts* H4.
  - inverts Typ.
    + inverts H4. inverts H9. inverts H1.
      assert (ttyping nil (e_anno v A1) Inf A1 t2).
      apply ttyp_anno; eauto.
      inverts H8. forwards*: value_lc H.
      forwards*: lc_lcb H5.
      exists. split.
      apply star_one.
      apply bStep_abeta; eauto. inverts H2.
      apply ttyp_anno; eauto. apply ttyp_sim; eauto.
      eapply ttyp_app; eauto.
      inverts H0.
      apply ttyp_sim; eauto. apply BA_AB; auto.
      unfold not; intros nt; inverts nt. inverts H0.
      unfold not; intros nt; inverts nt. inverts H2.

      exists. split.
      eapply star_trans.
      apply multi_red_app; eauto.
     apply star_one.
     apply bStep_abeta; eauto.
     forwards*: value_valueb H.
     inverts H0; try solve[inverts* H8].
     apply ttyp_anno; eauto.
     apply ttyp_sim; eauto.
     eapply ttyp_app; eauto.
     apply ttyp_sim; eauto.
     unfold not; intros nt; inverts nt. inverts H0.
     inverts* H2.
     unfold not; intros nt; inverts nt. inverts H0.

      forwards*: Tred_soundness H0. inverts* H8. inverts H9.
      exists. split.
      eapply star_trans.
      apply multi_red_app; eauto.
     apply star_one.
     apply bStep_abeta; eauto.
     forwards*: value_valueb H10.
     forwards*: Tred_value H0.  inverts* H2.
     apply ttyp_anno; eauto.
     apply ttyp_sim; eauto.
     eapply ttyp_app; eauto.
     apply ttyp_sim; eauto.
     apply BA_AB; auto.
     forwards*: TypedReduce_nlambda2 H0.
     unfold not; intros nt; inverts nt. inverts H2.
    +
      inverts H1. inverts H7. inverts H11. inverts H1. inverts H4.
      assert (ttyping nil (e_anno v A2) Inf A2 t2).
      apply ttyp_anno; eauto.
      inverts H8. forwards*: value_lc H.
      forwards*: lc_lcb H6.
      exists. split. apply multi_red_cast.
      apply star_one.
      apply bStep_abeta; eauto.
      apply ttyp_sim; eauto.
      apply ttyp_anno; eauto. apply ttyp_sim; eauto.
      eapply ttyp_app; eauto. apply ttyp_sim; eauto.
      inverts H0.
      apply ttyp_anno; eauto. apply BA_AB; auto.
      inverts H0.
      unfold not; intros nt; inverts nt. inverts H0.
      unfold not; intros nt; inverts nt. inverts H8.
      unfold not; intros nt; inverts nt. inverts H8.

      forwards*: Tred_soundness H0. inverts* H6. inverts H7.
      exists. split. apply multi_red_cast.
      eapply star_trans.
      apply multi_red_app; eauto.
     apply star_one.
     apply bStep_abeta; eauto.
     forwards*: value_valueb H8.
     forwards*: Tred_value H0.
     apply ttyp_sim; eauto.
     apply ttyp_anno; eauto.
     apply ttyp_sim; eauto.
     eapply ttyp_app; eauto.
     apply ttyp_sim; eauto.
     forwards*: TypedReduce_nlambda2 H0.
     unfold not; intros nt; inverts nt. inverts H7.
     unfold not; intros nt; inverts nt. inverts H7.

      forwards*: Tred_soundness H0. inverts* H8. inverts H11.
      exists. split. apply multi_red_cast.
      eapply star_trans.
      apply multi_red_app; eauto.
     apply star_one.
     apply bStep_abeta; eauto.
     forwards*: value_valueb H13.
     forwards*: Tred_value H0.
     apply ttyp_sim; eauto.
     apply ttyp_anno; eauto.
     apply ttyp_sim; eauto.
     eapply ttyp_app; eauto.
     apply ttyp_sim; eauto.
     apply BA_AB; auto.
     forwards*: TypedReduce_nlambda2 H0.
     unfold not; intros nt; inverts nt. inverts H11.
     unfold not; intros nt; inverts nt. inverts H11.
     inverts* H7.
     +
     inverts* H4.
  - inverts Typ.
    assert (ttyping nil (e_anno v A0) Inf A0 t).
    eauto.
    forwards*: Tred_soundness H2.
    inverts H2.
    assert (ttyping nil (e_anno v A1) Inf A1 t0).
    eauto.
    forwards*: Tred_soundness H0.
    inverts H5. inverts H6.
    exists. split.
    apply multi_red_cast; eauto.
    apply ttyp_sim;eauto.
    forwards*: TypedReduce_nlambda2 H0.
  - inverts Typ.
    * inverts H4.
    inverts H8.
    assert(ttyping nil (e_anno v1 t_int) Inf t_int (trm_cast t A t_int)).
    apply ttyp_anno; auto.
    forwards*: value_valueb H1.
    forwards*: Tred_soundness H0. inverts* H7. inverts H8. inverts H9.
     exists. split.
    apply star_trans with (b := (trm_app trm_add (trm_lit i1))).
    apply multi_red_app; eauto. apply star_one.
    apply bStep_add; eauto.
    eapply ttyp_addl; eauto.
    * inverts H1. inverts H7. inverts H8.
    assert(ttyping nil (e_anno v1 t_int) Inf t_int (trm_cast t A0 t_int)).
    apply ttyp_anno; auto.
    forwards*: value_valueb H.
    forwards*: Tred_soundness H0. inverts* H9. inverts H10. inverts H11.
     exists. split.
    apply star_trans with (b := trm_cast (trm_app trm_add (trm_lit i1)) (t_arrow t_int t_int) A).
    apply multi_red_cast; eauto.
    apply multi_red_app; eauto.
    apply star_trans with (b := trm_cast ((trm_addl i1)) (t_arrow t_int t_int) A).
    apply multi_red_cast; auto.
    apply bstep_refl.
    apply ttyp_sim; eauto.
    unfold not ; intros nt ; inverts nt. inverts H10.
    inverts* H7.
    *
    inverts* H4.
  - inverts Typ.
    *
    inverts H4. inverts H8.
    assert(ttyping nil (e_anno v2 t_int) Inf t_int (trm_cast t A t_int)).
    apply ttyp_anno; auto.
    forwards*: value_valueb H1.
    forwards*: Tred_soundness H0. inverts* H7. inverts H8.
    exists. split.
    apply star_trans with (b := (trm_app (trm_addl i1) x)).
    apply multi_red_app; eauto. apply star_one. inverts H9.
    apply bStep_addl; eauto.
    eapply ttyp_lit; eauto.
    *
    inverts H1. inverts H7. inverts H8.
    assert(ttyping nil (e_anno v2 t_int) Inf t_int (trm_cast t A0 t_int)).
    apply ttyp_anno; auto.
    forwards*: value_valueb H.
    forwards*: Tred_soundness H0. inverts* H8. inverts H10.
    exists. split.
    apply star_trans with (b := (trm_cast (trm_app (trm_addl i1) x) t_int A)).
    apply multi_red_cast; eauto.
    apply multi_red_app; eauto.
    apply star_trans with (b:= (trm_cast (trm_lit (i1 + i2)) t_int A)).
    apply multi_red_cast; eauto. inverts H11.
    apply star_one.
    apply bStep_addl; eauto. apply bstep_refl.
    apply ttyp_sim; eauto.
    unfold not ; intros nt ; inverts nt. inverts H10.
    inverts* H7.
    *
    inverts* H4.
  -
    inverts Typ.
    * inverts H5.
    assert(ttyping nil (e_anno v2 A1) Inf A1 t2).
    apply ttyp_anno; auto. inverts H10; try solve[inverts H2].
    inverts H3. inverts H8.
    forwards*: Tred_soundness H0.
    destruct H3. destruct H3.
    inverts H. forwards*: value_lc H10. forwards*: lc_lcb H.
    exists. split.
    apply star_trans with (b:= (trm_app (trm_cast (trm_abs A t0) (t_arrow A B) (t_arrow A1 A0)) x)).
    apply multi_red_app; eauto.
    apply star_one.
    apply bStep_abeta; eauto. forwards*: value_valueb H6.
    forwards*: Tred_value H0.
    inverts H4.
    apply ttyp_anno; eauto. apply ttyp_sim; eauto. eapply ttyp_app; eauto.
    apply ttyp_sim; eauto. apply BA_AB; auto.
    forwards*: TypedReduce_nlambda2 H0.
    unfold not ; intros nt ; inverts nt. inverts H4.
    inverts H.
    forwards*: value_valueb H3.
    forwards*: Tred_soundness H2.
    destruct H8. destruct H8.
    forwards*: principle_if H3. rewrite H12 in H13. inverts H13.
    exists. split.
    apply star_trans with (b:= (trm_app (trm_cast (trm_cast t0 (t_arrow C D) (t_arrow A B)) (t_arrow A B) (t_arrow A1 A0)) x)).
    apply multi_red_app; eauto.
    apply star_one.
    apply bStep_abeta; eauto. forwards*: value_valueb H10.
    forwards*: Tred_value H1.
    inverts H4.
    apply ttyp_anno; eauto. apply ttyp_sim; eauto. eapply ttyp_app; eauto.
    apply ttyp_sim; eauto. apply BA_AB; auto.
    forwards*: TypedReduce_nlambda2 H0.
    unfold not ; intros nt ; inverts nt. inverts H4.
    *
    inverts H2. inverts H8. inverts H12. inverts H2.
    assert(ttyping nil (e_anno v2 A2) Inf A2 t2).
    apply ttyp_anno; auto.
    inverts H10; try solve[inverts H2].
    forwards*: Tred_soundness H0.
    destruct H7. destruct H7.
    inverts H. forwards*: value_lc H12. forwards*: lc_lcb H.
    exists. split.
    apply multi_red_cast.
    apply star_trans with (b:= (trm_app (trm_cast (trm_abs A t0) (t_arrow A B) (t_arrow A2 A1)) x)).
    apply multi_red_app; eauto.
    apply star_one.
    apply bStep_abeta; eauto. forwards*: value_valueb H8.
    forwards*: Tred_value H0.
    inverts H5.
    apply ttyp_sim; eauto.
    apply ttyp_anno; eauto. apply ttyp_sim; eauto. eapply ttyp_app; eauto.
    apply ttyp_sim; eauto. apply BA_AB; auto.
    forwards*: TypedReduce_nlambda2 H0.
    unfold not ; intros nt ; inverts nt. inverts H5.
    unfold not ; intros nt ; inverts nt. inverts H5.
    inverts H.
    forwards*: value_valueb H13.
    forwards*: Tred_soundness H0.
    destruct H10. destruct H10.
    forwards*: principle_if H7. rewrite H14 in H15. inverts H15.
    exists. split.
    apply multi_red_cast.
    apply star_trans with (b:= (trm_app (trm_cast (trm_cast t0 (t_arrow C D) (t_arrow A B)) (t_arrow A B) (t_arrow A2 A1)) x)).
    apply multi_red_app; eauto.
    apply star_one.
    apply bStep_abeta; eauto. forwards*: value_valueb H12.
    forwards*: Tred_value H1.
    inverts H5.
    apply ttyp_sim; eauto.
    apply ttyp_anno; eauto. apply ttyp_sim; eauto. eapply ttyp_app; eauto.
    apply ttyp_sim; eauto. apply BA_AB; auto.
    forwards*: TypedReduce_nlambda2 H0.
    unfold not ; intros nt ; inverts nt. inverts H5.
    unfold not ; intros nt ; inverts nt. inverts H5.
    inverts* H8.
    *
    inverts* H5.
  -
    inverts* Typ; try solve[inverts* H3].
    +
    inverts* H0; try solve[inverts* H6].
    exists. splits*.
    eapply ttyp_sim;eauto.
    eapply ttyp_app; eauto.
    eapply ttyp_anno;eauto.
    eapply ttyp_sim;eauto.
    unfold not ; intros nt ; inverts nt. inverts H0.
    unfold not ; intros nt ; inverts nt. inverts H0.
    +
    exists. splits*.
    eapply ttyp_app; eauto.
    eapply ttyp_anno;eauto.
    eapply ttyp_sim;eauto.
    unfold not ; intros nt ; inverts nt. inverts H0.
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 VMM                                          *)
(*                                                                     *)
(*          Refinement proof for PTIntro layer                         *)
(*                                                                     *)
(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)
(*                                                                     *)
(*          Yale Flint Group                                           *)
(*                                                                     *)
(* *********************************************************************)

(** This file provide the contextual refinement proof between MAL layer and MPTIntro layer*)
Require Import PTIntroGenDef.

(** * Definition of the refinement relation*)
Section Refinement.

  Context `{real_params: RealParams}.

  Section WITHMEM.

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

    Lemma flatmem_store_exists:
      forall hadt ladt hadt' t v v' f m s ofs,
        flatmem_store hadt t ofs v = Some hadt'
        -> relate_RData f hadt ladt
        -> match_RData s hadt m f
        -> val_inject f v v'
        -> ofs mod PgSize <= PgSize - size_chunk t
        -> exists ladt',
             flatmem_store ladt t ofs v' = Some ladt'
             /\ relate_RData f hadt' ladt'
             /\ PT hadt' = PT hadt
             /\ ptpool hadt' = ptpool hadt
             /\ CR3 ladt' = CR3 ladt
             /\ pperm hadt' = pperm hadt
             /\ idpde hadt' = idpde hadt.
    Proof.
      unfold flatmem_store, flatmem_store. intros.
      revert H. inv H0. subrewrite. pose proof pperm_re as Hpp.
      specialize (pperm_re (PageI ofs)).
      destruct (ZMap.get (PageI ofs) (pperm hadt)) eqn:Hp'; contra_inv.
      assert (HW: ZMap.get (PageI ofs) (pperm ladt) = PGAlloc (*PGFreeable*)).
      {
        inv pperm_re; reflexivity.
      }
      rewrite HW. inv HQ; simpl.
      refine_split'; eauto.
      constructor; trivial; simpl.
      - (* flatmem *)
        eapply (FlatMem.store_mapped_inj f); eauto 1.
      - (* PMap *)
        constructor; intros. inv relate_PMap_re.
        erewrite FlatMem.load_store_other; eauto 2. simpl.
        assert (~ pi * PgSize + vadr * 4 - size_chunk t < ofs < pi * PgSize + vadr * 4 + 4).
        {
          red; intros.
          assert (PageI ofs = pi).
          {
            revert H7 H5 H3. clear; intros.
            exploit  (Z_mod_lt ofs PgSize). omega.
            intros Hofs.
            rewrite (Z_div_mod_eq ofs PgSize) in H7 |-*; try omega.
            assert (HW: (ofs / 4096) = pi).
            {
              destruct (zeq pi (ofs / 4096)); subst; trivial.
              destruct (zle (pi + 1) (ofs / 4096)); rewrite_omega.
            }
            subst. unfold PageI.
            replace (PgSize * (ofs / PgSize)) with ((ofs / PgSize) * PgSize) by omega.
            rewrite Z_div_plus_full_l; [| omega].
            rewrite (Zdiv_small (ofs mod PgSize) PgSize); omega.
          }
          subst.
          inv H1. inv H8.
          specialize (H1 _ H). inv H1.
          specialize (H8 _ H0). destruct H8 as (v0 & _ & _ & HMAT).
          unfold PMap, ZMap.t, PMap.t in H4, HMAT. rewrite H4 in HMAT.
          inv HMAT. congruence.
        }
        omega.
    Qed.

    Lemma fstore_exist:
      forall habd habd' labd i v f m s,
        fstore_spec i v habd = Some habd'
        -> relate_RData f habd labd
        -> match_RData s habd m f
        -> exists labd', fstore0_spec i v labd = Some labd' /\ relate_RData f habd' labd'
                         /\ PT habd' = PT habd
                         /\ ptpool habd' = ptpool habd
                         /\ CR3 labd' = CR3 labd
                         /\ pperm habd' = pperm habd
                         /\ idpde habd' = idpde habd.
    Proof.
      unfold fstore_spec, fstore0_spec; intros.
      revert H. pose proof H0 as HR.
      inv H0. subrewrite.
      subdestruct.
      eapply flatmem_store_exists; eauto.
      change 4096 with (1024 * 4).
      rewrite Zmult_mod_distr_r.
      apply mod_chunk.
    Qed.

    Global Instance: (LoadStoreProp (hflatmem_store:= flatmem_store) (lflatmem_store:= flatmem_store)).
    Proof.
      accessor_prop_tac.
      - exploit flatmem_store_exists; eauto.
        intros (ladt' & HST & Hre & _).
        refine_split'; eauto.
      - functional inversion H6. constructor; simpl; assumption.
    Qed.

  End WITHMEM.

End Refinement.


Definition rs2 :=
let mo' := (`mo)%rel in
  ⦗IsRel⦘ ⨾ mo'^? \ (mo' \ sb^⋈) ⨾ ⦗set_compl IsRMW⦘ ⨾ mo'^?.

Definition rs3 :=
let mo' := (` (immediate mo))%rel in
fun x =>
  (⦗eq x⦘ ⨾ ⦗IsRel⦘ ⨾ (((mo' ⨾ ⦗IsRMW⦘)＊ ⨾ mo') ⨾ ⦗sb^⋈ x⦘)＊ ⨾ (mo' ⨾ ⦗IsRMW⦘)＊) x.

Lemma rs_rs2: rs ≡ rs2.
Proof.
unfold rs, rs2, same_relation, inclusion, seq, minus_rel, eqv_rel, not, clos_refl, set_compl.
all: repeat (intros; des; try split).
1,4: exists z; auto.
1-4: specialize (H0 z0); subst z z1; tauto.
1,4: shelve.
all: subst z.
all: apply NNPP; unfold not; intros; apply H0.
all: exists z0; split; auto; exists z0; tauto.
Unshelve.
all: subst z.
all: exists x.
all: tauto.
Qed.

Lemma rs_rs3: rs ≡ rs3.
Proof.
unfold rs, rs3.
all: autounfold with unfolderDb.
set (mo' := (`mo)%rel).
assert (mo_mo': forall x y, mo x y <-> mo' (`x) (`y)).
  split.
  intros moxy.
  eexists; eexists; split; try split.
  1-3: eauto.
  intros moxy.
  destruct moxy as (e' & f' & moxy' & ex & fy).
  apply sig_ext in ex.
  apply sig_ext in fy.
  subst e' f'.
  auto.
assert (mo'_mo: forall x y, mo' x y <-> exists x' y', `x' = x /\ `y' = y /\ mo x' y').
  intros x y.
  split.
  intros moxy.
  destruct moxy as (e' & f' & moxy' & <- & <-).
  eexists; esplit; try esplit; eauto.
  intros (e & f & <- & <- & moxy).
  apply mo_mo'; auto.
assert (spo: strict_partial_order mo).
  specialize (mo_total_order_per_loc (0)).
  intros sto; apply sto.
assert (spo': strict_partial_order mo').
  destruct spo as [irr tra].
  split.
  intros x mxx.
  apply mo'_mo in mxx.
  destruct mxx as (e & f & ex & <- & moxy).
  apply sig_ext in ex; subst f.
  eapply irr; eauto.
  intros x y z moxy moyz.
  apply mo'_mo in moxy as (e & f & <- & <- & moxy).
  apply mo'_mo in moyz as (f' & g & ff & <- & moyz).
  apply sig_ext in ff.
  subst f'.
  apply mo_mo'.
  eapply tra; eauto.
split.
- intros x y [[z [[xz xIsRel] moxy]] rsCond].
  subst z.
  eexists; split; try split; auto;
    eexists; split; try split; auto.
  destruct moxy as [xy|(x' & y' & moxy & <- & <-)].
  eexists; esplit; rewrite clos_refl_transE.
  1, 2: left; auto.
  clear xIsRel.
  apply mo_mo' in moxy.
  apply (imm_trans mo' spo') in moxy.
  set (base := x') in rsCond at 2 3.
  fold base.
  unfold base at 3.
  assert (base_x: (`base) = (`x') \/
                  mo' (`base) (`x') /\ (sb^⋈ (`base) (`x') \/
                                        IsRMW (`x'))).
    constructor 1; auto.
  clearbody base.
  induction moxy.
  destruct H as [moxy' imm].
  pose (moxy := moxy'); apply mo'_mo in moxy; destruct moxy as (x'' & y'' & <- & <- & moxy'').
  assert (sb^⋈ (`base) (`y'') \/ IsRMW (`y'')).
    eapply rsCond.
    eexists; eexists; split; try split.
    2,3: eauto.
    auto.
    destruct base_x as [bx|[mobx]].
    apply sig_ext in bx; subst x''; auto.
    apply mo'_mo in mobx; destruct mobx as (e & f & e1 & e2 & mobx).
    apply sig_ext in e1; subst e.
    apply sig_ext in e2; subst f.
    left; auto.
  destruct H, base_x as [bx|[mobx [x_sb|x_rmw]]].
  1-6: eexists; esplit; erewrite clos_refl_transE.

  (* base = x, sb x y*)
  right; econstructor 1; esplit.
  eexists; esplit.
  erewrite clos_refl_transE; esplit.
  left; auto.
  eexists; eexists; split; split.
  1-5: eauto.
  intros c moxc mocy.
  eapply imm.
  1-2: eapply mo_mo'; eauto.
  auto.
  left; auto.

  (* mo base x, sb base x, sb base y*)
  right; econstructor 1; eexists; esplit; try erewrite clos_refl_transE; try esplit.
  1, 2: eexists; try esplit; try esplit; try esplit;
    try erewrite clos_refl_transE; try left; try esplit.
  3,4,5: eauto.
  auto.
  intros c moxc mocy.
  eapply imm.
  1-2: eapply mo_mo'; eauto.
  left; auto.

  (*  mo base x, isrmw x, sb base y*)
  right; econstructor 1; eexists; esplit; try erewrite clos_refl_transE; try esplit.
  1, 2: eexists; try esplit; try esplit; try esplit;
    try erewrite clos_refl_transE; try left; try esplit.
  3,4,5: eauto.
  auto.
  intros c moxc mocy.
  eapply imm.
  1-2: eapply mo_mo'; eauto.
  left; auto.

  (* base = x, isrmw y *)
  left; auto.
  right; econstructor 1; esplit; eexists; esplit; try eexists; try esplit; try esplit;
    try esplit.
  1-3: auto.
  intros c moxc mocy.
  eapply imm.
  1-2: eapply mo_mo'; eauto.

  (* mo base x, sb base x, isrmw y *)
  left; auto.
  right; econstructor 1; eexists; esplit; try erewrite clos_refl_transE; try esplit.
  1, 2: eexists; try esplit; try esplit; try esplit;
    try erewrite clos_refl_transE; try left; try esplit.
  1-3: eauto.
  intros c moxc mocy.
  eapply imm.
  1-2: eapply mo_mo'; eauto.

  (* mo base x, isrmw x, isrmw y *)
  left; auto.
  right; econstructor 1; eexists; esplit; try erewrite clos_refl_transE; try esplit.
  1, 2: eexists; try esplit; try esplit; try esplit;
    try erewrite clos_refl_transE; try left; try esplit.
  1-3: eauto.
  intros c moxc mocy.
  eapply imm.
  1-2: eapply mo_mo'; eauto.

  apply imm_trans in moxy1.
  apply mo'_mo in moxy1 as (e & f & <- & <- & moxy1).
  apply mo_mo' in moxy1.
  apply imm_trans in moxy2.
  apply mo'_mo in moxy2 as (e' & f' & ef & fz & moxy2).
  apply sig_ext in ef.
  subst e' z.
  apply mo_mo' in moxy2.

  eassert (s1 := IHmoxy1 ?[f] ?[g]).
  [f]: {
    intros z' (e'' & f'' & moef & ee & fz) [fz'|(e''' & f''' & moef' & ez & fy)].
    all: subst z'.
    all: apply sig_ext in ee.
    apply sig_ext in fz'.
    subst e'' f''.
    apply rsCond.
    eexists; eexists; esplit; try esplit.
    1-4: eauto.
    apply sig_ext in ez.
    apply sig_ext in fy.
    subst e'' e''' f'''.
    apply rsCond.
    eexists; eexists; esplit; try esplit.
    2-3: eauto.
    auto.
    right.
    eexists; eexists; esplit; try esplit.
    2-3: eauto.
    apply spo with f; auto.
    apply mo_mo'; auto.
  }
  [g]: {
    apply base_x.
  }
  eassert (s2 := IHmoxy2 ?[f]).
  [f]: {
    intros z' (e'' & f'' & moef & ee' & fz) [fz'|(e''' & f''' & moef' & ez & fy)].
    all: subst z'.
    all: apply sig_ext in ee'.
    apply sig_ext in fz'.
    2: apply sig_ext in ez; apply sig_ext in fy.
    all: subst e'' f''.
    apply rsCond.
    eexists; eexists; esplit; try esplit.
    2-3: eauto.
    apply mo_mo'; apply spo' with (`f); auto.
    left; auto.
    subst f'''.
    apply rsCond.
    eexists; eexists; esplit; try esplit.
    2-3: eauto.
    apply mo_mo' in moef.
    apply mo_mo'.
    apply spo' with (`f); auto.
    right.
    eexists; eexists; esplit; try esplit.
    2-3: eauto.
    auto.
  }
  2-3: auto.

  destruct s1 as [e' [s11 s12]].
  apply clos_refl_transE in s11.
  apply clos_refl_transE in s12.
  destruct s11 as [ee|s11], s12 as [ef|s12].
  1-3: subst e'.
  apply sig_ext in ef.
  subst f.
  exfalso; revert moxy1; apply spo'.

  all: lapply s2; clear s2.
  1,3,5: intros s2.
  1-3: destruct s2 as [e'' [s21 s22]].
  1-3: apply clos_refl_transE in s21.
  1-3: apply clos_refl_transE in s22.
  1-3: destruct s21 as [ee|s21], s22 as [ef|s22].
  1-3,5-7,9-11: subst e''.
  1,4,7: apply sig_ext in ef.
  1-3: subst f.
  1-3: exfalso; revert moxy2; apply spo'.

  (* left: rmw. right: rmw *)
  eexists; esplit; apply clos_refl_transE.
  left; auto.
  right; econstructor 2.
  apply s12.
  apply s22.

  (* left: rmw. right: sb *)
  eexists; esplit; apply clos_refl_transE.
  2: left; auto.
  right.
  apply t_step_rt in s21 as [e' [[y'' [[e'' [s21p (p & p' & [mopp ppimm] & xe & yy)]] [ey sbb]]] s21]].
  subst e' e'' y''.
  apply clos_refl_transE in s21p; destruct s21p as [pp|s21p].
  apply sig_ext in pp; subst p.
  1-2: apply clos_refl_transE in s21; destruct s21 as [pp|s21].
  1,3: apply sig_ext in pp; subst p'.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right; apply s12.
  1-3: auto.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right; econstructor 2.
  apply s12.
  apply s21p.
  1-3: auto.
  econstructor 2.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right.
  apply s12.
  apply mopp.
  1-3: auto.
  econstructor 2.
  2: apply s21.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right; econstructor 2.
  apply s12.
  apply s21p.
  1-3: auto.

  (* left: sb. right: rmw *)
  eexists; esplit; apply clos_refl_transE; right.
  apply s11.
  apply s22.

  (* left: sb. right: sb *)
  eexists; esplit; apply clos_refl_transE.
  right; econstructor 2.
  apply s11.
  apply s21.
  auto.

  (* left: sb;rmw. right: rmw *)
  eexists; esplit; apply clos_refl_transE.
  right.
  apply s11.
  right.
  econstructor 2.
  apply s12.
  apply s22.

  (* left: sb;rmw. right: sb *)
  apply t_step_rt in s21 as [e''' [[y'' [[e'' [s21p (p & p' & [mopp ppimm] & xe & yy)]] [ey sbb]]] s21]].
  subst e''' e'' y''.
  apply clos_refl_transE in s21p; destruct s21p as [pp|s21p].
  apply sig_ext in pp; subst p.
  1-2: apply clos_refl_transE in s21; destruct s21 as [pp|s21].
  1,3: apply sig_ext in pp; subst p'.
  1-4: eexists; esplit; eapply clos_refl_transE.
  2,4,6,8: left; auto.
  1-4: right; econstructor 2.
  apply s11.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right; apply s12.
  1-3: auto.
  apply s11.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right; econstructor 2.
  apply s12.
  apply s21p.
  1-3: auto.
  2: apply s21.
  econstructor 2.
  apply s11.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right.
  apply s12.
  1-3: auto.
  2: apply s21.
  econstructor 2.
  apply s11.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right; econstructor 2.
  apply s12.
  apply s21p.
  1-3: auto.

  (* left: rmw. right: sb;rmw *)
  apply t_step_rt in s21 as [e''' [[y'' [[e' [s21p (p & p' & [mopp ppimm] & xe & yy)]] [ey sbb]]] s21]].
  subst e''' e' y''.
  apply clos_refl_transE in s21p; destruct s21p as [pp|s21p].
  apply sig_ext in pp; subst p.
  1-2: apply clos_refl_transE in s21; destruct s21 as [pp|s21].
  1,3: subst e''.
  1-4: eexists; esplit; eapply clos_refl_transE.
  right; econstructor 1; repeat esplit.
  apply clos_refl_transE; right.
  apply s12.
  apply mopp.
  1-2: auto.
  right; apply s22.
  right; econstructor 1; repeat esplit.
  apply clos_refl_transE; right; econstructor 2.
  apply s12.
  apply s21p.
  apply mopp.
  1-2: auto.
  right; apply s22.
  right; econstructor 2.
  2: apply s21.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right.
  apply s12.
  apply mopp.
  1-2: auto.
  right; apply s22.
  right; econstructor 2.
  2: apply s21.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right; econstructor 2.
  apply s12.
  apply s21p.
  1-3: auto.
  right; apply s22.

  (* left: sb. right: sb;rmw *)
  eexists; esplit; apply clos_refl_transE; right.
  econstructor 2.
  apply s11.
  apply s21.
  apply s22.

  (* left: sb;rmw. right: sb;rmw *)
  apply t_step_rt in s21 as [e''' [[y'' [[e'''' [s21p (p & p' & [mopp ppimm] & xe & yy)]] [ey sbb]]] s21]].
  subst e''' e'''' y''.
  apply clos_refl_transE in s21p; destruct s21p as [pp|s21p].
  apply sig_ext in pp; subst p.
  1-2: apply clos_refl_transE in s21; destruct s21 as [pp|s21].
  1,3: subst e''.
  1-4: eexists; esplit; eapply clos_refl_transE.
  right; econstructor 2.
  apply s11.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right.
  apply s12.
  apply mopp.
  1-2: auto.
  right; apply s22.
  right; econstructor 2.
  apply s11.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right; econstructor 2.
  apply s12.
  apply s21p.
  apply mopp.
  1-2: auto.
  right; apply s22.
  right; econstructor 2.
  2: apply s21.
  econstructor 2.
  apply s11.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right.
  apply s12.
  apply mopp.
  1-2: auto.
  right; apply s22.
  right; econstructor 2.
  2: apply s21.
  econstructor 2.
  apply s11.
  econstructor 1; repeat esplit.
  apply clos_refl_transE; right; econstructor 2.
  apply s12.
  apply s21p.
  1-3: auto.
  right; apply s22.

  apply t_rt_step in s12 as [p [_ [p' [_ [pf rmwf]]]]].
  subst p'.
  destruct base_x as [be | [mobe]].
  apply sig_ext in be; subst base.
  right; split.
  auto.
  right; auto.
  right; split.
  apply spo' with (`e); auto.
  right; auto.

  apply t_rt_step in s11 as [p [_ [p' [_ [pf sbf]]]]].
  subst p'.
  destruct base_x as [be | [mobe]].
  apply sig_ext in be; subst base.
  right; split.
  auto.
  auto.
  right; split.
  apply spo' with (`e); auto.
  auto.

  apply t_rt_step in s12 as [p [_ [p' [_ [pf rmwf]]]]].
  subst p'.
  destruct base_x as [be | [mobe]].
  apply sig_ext in be; subst base.
  right; split.
  auto.
  right; auto.
  right; split.
  apply spo' with (`e); auto.
  right; auto.

- assert (tot_mo:
    forall x i c,
      mo'^⋈ x i -> mo'^⋈ x c ->
      i <> c -> mo' i c \/ mo' c i). {
    intros x i c moxi moxc inc.
    destruct moxi as [moxi|moxi], moxc as [moxc|moxc].
    all: apply mo'_mo in moxi as (e & f & xx & yy & moxi).
    all: apply mo'_mo in moxc as (e' & f' & xx' & yy' & moxc).
    all: subst c i x.
    all: try apply sig_ext in xx'.
    all: try apply sig_ext in yy'.
    all: try subst e.
    all: try subst f.
    all: apply mo_same_loc_only in moxi.
    all: apply mo_same_loc_only in moxc.
    all: destruct moxi as [moxi xi], moxc as [moxc xc].
    1,2: rewrite xi in xc; clear xi.
    3,4: rewrite <- xi in xc; clear xi.
    1,3: destruct (mo_total_order_per_loc ((loc ∘ Write_To_ReadWrite) f')) as [_ tot].
    3,4: destruct (mo_total_order_per_loc ((loc ∘ Write_To_ReadWrite) e')) as [_ tot].
    all: edestruct tot.
    2,7,12,17: reflexivity.
    1,5,9,13: try apply xc; try apply (eq_sym xc).
    all: apply mo_mo' in moxi.
    all: apply mo_mo' in moxc.
    1,4,7,10: intros conn; apply inc; apply f_equal; auto.
    all: apply mo_mo' in H.
    all: eauto.
  }
  intros x y [x' [[xz xx] [x'' [[xz' xisrel] [z [xzsb zyrmw]]]]]].
  subst x' x''.
  clear xx.
  remember x as base.
  replace base in xzsb at 1 |-.
  assert (mo_rmw_mo:
    let imo' := (` (immediate mo))%rel in
      (imo' ⨾ ⦗IsRMW⦘)⁺ ⊆ mo' \ (mo' ⨾ ⦗set_compl IsRMW⦘ ⨾ mo'^?)). {
    clear x y z xisrel Heqbase xzsb zyrmw.
    intros imo' x y xyrmw.
    induction xyrmw.
    destruct H as [z' ((x'' & y'' & (moxy & xyimm) & <- & <-) & <- & yrmw)].
    split.
    apply mo_mo'; auto.
    intros (z & moxz & z'' & [<- zrmw] & [->|mozy]).
    auto.
    apply mo'_mo in moxz as (x' & z' & xx & <- & moxz).
    apply mo'_mo in mozy as (z'' & y' & zz & yy & mozy).
    apply sig_ext in xx.
    apply sig_ext in yy.
    apply sig_ext in zz.
    subst x'' y'' z''.
    eapply xyimm; eauto.
    destruct IHxyrmw1 as [moxy yrmw].
    destruct IHxyrmw2 as [moyz zrmw].
    split.
    eapply spo'; eauto.
    intros (y' & moxy' & z'' & [<- allrmw] & [->|moyz']).
    apply zrmw; esplit; esplit.
    2: esplit; esplit.
    3: left; auto.
    2: esplit; eauto.
    auto.
    destruct (classic (y = y')) as [<-|yneq].
    apply yrmw; esplit; esplit.
    2: esplit; esplit.
    3: left; auto.
    2: esplit; eauto.
    auto.
    destruct (tot_mo x y y'); unfold clos_sym; auto.
    apply zrmw; esplit; esplit.
    2: esplit; esplit.
    3: right.
    2: esplit; eauto.
    1-2: eauto.
    apply yrmw; esplit; esplit.
    2: esplit; esplit.
    3: right.
    2: esplit; eauto.
    1-2: eauto.
  }
  assert (mo_sb_mo:
    let imo' := (` (immediate mo))%rel in
      (((imo' ⨾ ⦗IsRMW⦘)＊ ⨾ imo') ⨾ ⦗sb^⋈ base⦘)⁺ ⊆
      mo' \ (mo' ⨾ ⦗set_compl (IsRMW ∪₁ sb^⋈ base)⦘ ⨾ mo'^?)). {
    clear x y z xisrel Heqbase xzsb zyrmw.
    intros imo' x y xyrmw.
    induction xyrmw.
    destruct H as [z' [[z'' [zrmw (z & y' & [moxy imm] & <- & <-)]] [<- zsb]]].
    apply clos_refl_transE in zrmw as [->|zrmw].
    split.
    apply mo_mo'; auto.
    intros (e & moxy' & z'' & [<- allrmw] & [->|moyz']).
    apply allrmw.
    right; auto.
    apply mo'_mo in moxy' as (z' & e' & xx & <- & moxy').
    apply mo'_mo in moyz' as (e'' & y'' & zz & yy & moyz').
    apply sig_ext in xx.
    apply sig_ext in yy.
    apply sig_ext in zz.
    subst z' e'' y''.
    eapply imm; eauto.
    lapply (mo_rmw_mo x (`z)).
    intros (z' & moxz).
    split.
    eapply spo'.
    apply z'.
    apply mo_mo'; auto.
    intros (e & moxy' & z'' & [<- allrmw] & [->|moyz']).
    apply allrmw.
    right; auto.
    destruct (classic (e = `z)) as [->|yneq].
    apply moxz; esplit; esplit.
    2: esplit; esplit.
    3: left; auto.
    2: esplit; eauto.
    2: intros nrmw; apply allrmw; left; auto.
    auto.
    destruct (tot_mo x e (`z)); unfold clos_sym; auto.
    apply moxz; esplit; esplit.
    2: esplit; esplit.
    3: right.
    2: esplit; eauto.
    apply moxy'.
    intros nrmw; apply allrmw; left; auto.
    auto.
    apply mo'_mo in H as (z'' & e' & xx & <- & H).
    apply mo'_mo in moyz' as (e'' & y'' & zz & yy & moyz').
    apply sig_ext in xx.
    apply sig_ext in yy.
    apply sig_ext in zz.
    subst e'' y'' z''.
    eapply imm; eauto.
    auto.
    destruct IHxyrmw1 as [moxy yrmw].
    destruct IHxyrmw2 as [moyz zrmw].
    split.
    eapply spo'; eauto.
    intros (y' & moxy' & z'' & [<- allrmw] & [->|moyz']).
    apply zrmw; esplit; esplit.
    2: esplit; esplit.
    3: left; auto.
    2: esplit; eauto.
    auto.
    destruct (classic (y = y')) as [<-|yneq].
    apply yrmw; esplit; esplit.
    2: esplit; esplit.
    3: left; auto.
    2: esplit; eauto.
    auto.
    destruct (tot_mo x y y'); unfold clos_sym; auto.
    apply zrmw; esplit; esplit.
    2: esplit; esplit.
    3: right.
    2: esplit; eauto.
    1-2: eauto.
    apply yrmw; esplit; esplit.
    2: esplit; esplit.
    3: right.
    2: esplit; eauto.
    1-2: eauto.
  }
  apply clos_refl_transE in xzsb.
  apply clos_refl_transE in zyrmw.
  destruct xzsb as [<-|xzsb], zyrmw as [<-|zyrmw].

  all: repeat try esplit.
  all: auto.
  1,3,5,7: intros z' (e & f & moxy & ee & ff) [<-|(e' & f' & moyz & ff' & gg)].
  1-8:subst base z'.

  apply sig_ext in ff; subst e.
  exfalso; eapply spo; eauto.

  subst x.
  apply sig_ext in ff'; subst e'.
  apply sig_ext in gg; subst e.
  exfalso; eapply spo; eapply spo; eauto.

  subst x.
  lapply (mo_rmw_mo (`e) (`f)).
  intros (moef & allzyrmw).
  apply NNPP; intros nrmw.
  apply allzyrmw.
  esplit; esplit.
  eauto.
  esplit; esplit.
  esplit; eauto.
  intros nrmw2; apply nrmw; auto.
  left; auto.
  auto.

  subst x y.
  apply sig_ext in ff'; subst e'.
  lapply (mo_rmw_mo (`e) (`f')).
  intros (moef & allzyrmw).
  apply NNPP; intros nrmw.
  apply allzyrmw.
  esplit; esplit.
  eapply mo_mo'; eauto.
  esplit; esplit.
  esplit; eauto.
  intros nrmw2; apply nrmw; auto.
  right; eapply mo_mo'; eauto.
  auto.

  subst x.
  lapply (mo_sb_mo (`e) (`f)).
  intros (moef & allxzsb).
  apply NNPP; intros nrmw.
  apply allxzsb.
  esplit; esplit.
  eauto.
  esplit; esplit.
  esplit; eauto.
  intros [nrmw2|nrmw2]; apply nrmw; auto.
  left; auto.
  auto.

  subst x z.
  apply sig_ext in ff'; subst e'.
  lapply (mo_sb_mo (`e) (`f')).
  intros (moef & allxzsb).
  apply NNPP; intros nrmw.
  apply allxzsb.
  esplit; esplit.
  eapply mo_mo'; eauto.
  esplit; esplit.
  esplit; eauto.
  intros [nrmw2|nrmw2]; apply nrmw; auto.
  right; eapply mo_mo'; eauto.
  auto.

  subst x.
  lapply (mo_sb_mo (`e) z).
  intros (moez & allxzsb).
  lapply (mo_rmw_mo z (`f)).
  intros (mozf & allzyrmw).
  apply NNPP; intros nrmw.
  apply allzyrmw.
  esplit; esplit.
  eauto.
  esplit; esplit.
  esplit; eauto.
  intros nrmw2; apply nrmw; auto.
  left; auto.
  1-2: auto.

  subst x y.
  apply sig_ext in ff'; subst e'.
  lapply (mo_sb_mo (`e) z).
  intros (moez & allxzsb).
  lapply (mo_rmw_mo z (`f')).
  intros (mozf & allzyrmw).
  apply NNPP; intros nrmw.
  destruct (classic (`f = z)) as [<-|neq].

  apply allxzsb.
  esplit; esplit.
  eauto.
  esplit; esplit.
  esplit; eauto.
  intros [nrmw2|nrmw2]; apply nrmw; auto.
  left; auto.

  destruct (tot_mo (`e) z (`f)); unfold clos_sym; auto.
  left; apply mo_mo'; auto.
  apply allzyrmw.
  esplit; esplit.
  eauto.
  esplit; esplit.
  esplit; eauto.
  intros nrmw2; apply nrmw; auto.
  right; apply mo_mo'; auto.

  apply allxzsb.
  esplit; esplit.
  eapply mo_mo'; eauto.
  esplit; esplit.
  esplit; eauto.
  intros [nrmw2|nrmw2]; apply nrmw; auto.
  right; auto.
  1-2: auto.

  right.
  lapply (mo_rmw_mo x y).
  intros (moxy & allzyrmw).
  apply mo'_mo in moxy as (z' & e' & <- & <- & moxy).
  eauto.
  auto.

  right.
  lapply (mo_sb_mo x z).
  intros (moxz & allxzsb).
  apply mo'_mo in moxz as (z' & e' & <- & <- & moxy).
  eauto.
  auto.

  right.
  lapply (mo_rmw_mo z y).
  intros (mozy & allzyrmw).
  apply mo'_mo in mozy as (z' & f' & <- & <- & mozy).
  lapply (mo_sb_mo x (`z')).
  intros (moxz & allxzsb).
  apply mo'_mo in moxz as (e' & z'' & <- & yy & moxz).
  apply sig_ext in yy; subst z''.
  cut (mo e' f').
  intros moef; eauto.
  eapply spo; eauto.
  1-2: auto.
Qed.