From machine_program_logic.program_logic Require Import weakestpre.
From HypVeri.algebra Require Import base base_extra mem pagetable trans.
From HypVeri.rules Require Import rules_base mov halt run yield ldr str br.
From HypVeri.examples Require Import instr utils.
From HypVeri.logrel Require Import logrel logrel_extra fundamental logrel_prim logrel_prim_extra fundamental_prim.
From HypVeri Require Import proofmode machine_extra.
Require Import Setoid.

Program Instance up_vmconfig : HypervisorConstants :=
    {vm_count := 4;
     vm_count_pos := _;
     valid_handles := {[W0]}}.

Section up_proof.

Program Definition V1 : VMID := (@nat_to_fin 1 _ _).
Program Definition V2 : VMID := (@nat_to_fin 2 _ _).
Program Definition V3 : VMID := (@nat_to_fin 3 _ _).

Program Definition fortytwo : Imm := I (finz.FinZ 42 _ _) _.

  Context `{hypparams: !HypervisorParameters}.
  Context (pshare:PID) (pshare_i: Imm) (Hpshare_eq: of_pid pshare = pshare_i).
  Context (pprog0 pprog1 pprog2 pprog3:PID).
  Context (ptx1 ptx3 prx1 prx3 :PID).
  Context (ptx0 ptx2 prx0 prx2 :PID).
  Context (Hps_nd: NoDup [pprog0;pprog1;pprog2;pprog3;pshare;ptx0;ptx1;ptx2;ptx3;prx0;prx1;prx2;prx3]).
  Context (pprog3_i : Imm) (Hpprog3_eq : of_pid pprog3 = pprog3_i).

  Definition up_program1 (jump : Imm) : list Word :=
    [
      (* Store 42 to shared page *)
      mov_word_I R1 fortytwo;
      mov_word_I R2 pshare_i;
      str_I R1 R2;
      (* addr to jump *)
      mov_word_I R2 jump;
      mov_word_I R0 yield_I;
      hvc_I;
      br_I R2
    ].

  Definition up_program3 : list Word :=
    [
      (* read 42 from shared page *)
      mov_word_I R2 pshare_i;
      mov_word_I R0 pprog3_i;
      ldr_I R1 R2;
      cmp_word_I R1 fortytwo;
      bne_I R0;
      halt_I
    ].

  Class exclG Σ :=
    excl_G :> inG Σ (exclR unitO).
  Definition exclΣ : gFunctors :=
    #[ GFunctor (exclR unitO)].

  Instance subG_issuedΣ {Σ} : subG exclΣ Σ → exclG Σ.
  Proof. solve_inG. Qed.

  Context `{!gen_VMG Σ, !exclG Σ} (N : namespace).

  Definition EXCL γ : iProp Σ := (own γ (Excl ()))%I.
  Lemma excl_exclusive (γ : gname) : EXCL γ  -∗ EXCL γ  -∗ False.
  Proof.
    iDestruct 1 as  "H1". iDestruct 1 as  "H2".
    iDestruct (own_valid_2 with "H1 H2") as %[].
  Qed.

  (* don't transfer anything if i,j = 1,3 or 3,1 *)
  Definition up_slice_trans trans i j : iProp Σ :=
    match (bool_decide (i = V1)), (bool_decide (j = V3)) with
    | true, true => True
    | _, _ => match (bool_decide (i = V3)), (bool_decide (j = V1)) with
           | true, true => True
           | _, _ => slice_transfer_all trans i j
           end
    end.

  Definition up_slice_rxs i os j : iProp Σ :=
    (match os with
    | None => True
    | Some (_, k) => if (bool_decide (k=V0)) then
                       (if (bool_decide (j = V0)) then
                          slice_rx_state i os
                        else if (bool_decide (i = j)) then
                               slice_rx_state i os
                             else True)
                     else slice_rx_state i os
    end)%I.

  Instance up_slice_trans_wf : SliceTransWf up_slice_trans.
  Proof.
    rewrite /up_slice_trans /=.
    split.
    intros.
    case_bool_decide;
    case_bool_decide;auto.
    subst i. simpl. by apply slice_transfer_all_wf.
    case_bool_decide;auto.
    subst i. simpl. by apply slice_transfer_all_wf.
    by apply slice_transfer_all_wf.
  Qed.

  Instance up_slice_rxs_wf : SliceRxsWf up_slice_rxs.
  Proof.
    rewrite /up_slice_rxs /=.
    split. done.
    intros.
    destruct os;auto.
    destruct p. intros.
    case_bool_decide;auto.
    case_bool_decide;auto.
    done. done.
  Qed.

  Notation VMProp1 := (vmprop_unknown V1 up_slice_trans up_slice_rxs {[W0 := (V1, V3, {[pshare]}, Sharing, true)]}) (only parsing).
  Notation VMProp3 := (vmprop_unknown V3 up_slice_trans up_slice_rxs {[W0 := (V1, V3, {[pshare]}, Sharing, true)]}) (only parsing).

  Class SliceWfPrim Φ_t Φ_r :=
    {
     trans_wf_prim : ∀ i j trans, (i = V0 ∨ j = V0) -> Φ_t trans i j ⊣⊢ slice_transfer_all trans i j;
     rxs_wf_prim_diag : ∀ i os, (match os with
                 | None => True
                 | Some (_,j) => j = V0 -> Φ_r i os i ⊣⊢ slice_rx_state i os
                end);
     rxs_wf_prim_eq: ∀ i os, match os with
               | None => True
               | Some (_ ,k) => k = V0
               end -> Φ_r i os i ⊣⊢ Φ_r i os V0;
     rxs_wf_prim_none : ∀ i j os, (match os with
                 | None => True
                 | Some (_,j) => j = V0
                end) -> j ≠ i -> j ≠ V0 -> Φ_r i os j ⊣⊢ True;
     rxs_wf_prim_zero: ∀ os, (match os with
              | None => True
              | _ => Φ_r V0 os V0 ⊣⊢ slice_rx_state V0 os
              end);
    }.

  Global Instance up_slice_wf: SliceWfPrim up_slice_trans up_slice_rxs.
  Proof.
    split;rewrite /up_slice_trans /up_slice_rxs.
    {
      intros ? ? ? [|].
      case_bool_decide. subst i. done.
      case_bool_decide. subst i. done.
      done.
      case_bool_decide.
      case_bool_decide. subst j. done.
      case_bool_decide. subst j. done.
      done.
      case_bool_decide;auto.
      case_bool_decide;auto.
      subst j. done.
    }
    {
      intros.
      destruct os. destruct p. intro.
      case_bool_decide;auto.
      case_bool_decide;auto.
      case_bool_decide;auto.
      done. done.
    }
    {
      intros.
      destruct os;auto. destruct p.
      case_bool_decide;auto.
      case_bool_decide;auto.
      case_bool_decide;auto.
      done.
    }
    {
      intros.
      destruct os;auto. destruct p.
      case_bool_decide;auto.
      case_bool_decide;auto. done.
      case_bool_decide;auto. done.
      done.
    }
    {
      intros.
      destruct os;auto. destruct p.
      case_bool_decide;auto.
    }
  Qed.

  Definition inv_pshare γ pshare : iProp Σ:=
   inv (N .@ "shared")
     ((∃ w, pshare ->a w) ∨ EXCL γ ∗ pshare ->a (of_imm fortytwo)).

  Lemma up_machine1 jump_i γ :
    let program1 := up_program1 jump_i in
    of_imm (jump_i) = (pprog1 ^+ 4)%f ->
    seq_in_page (of_pid pprog1) (length program1) pprog1->
    inv_pshare γ pshare ∗
    EXCL γ ∗
    (program (program1) (of_pid pprog1)) ∗
    V1 -@A> {[pprog1;pshare;ptx1;prx1]} ∗
    (* TX page *)
    TX@ V1 := (tpa ptx1) ∗
    RX@ V1 := (tpa prx1) ∗
    PC @@ V1 ->r (of_pid pprog1) ∗
    (* Work registers *)
    (∃ r0, R0 @@ V1 ->r r0) ∗
    (∃ r1, R1 @@ V1 ->r r1) ∗
    (∃ r2, R2 @@ V1 ->r r2) ∗
    VMProp V1 (VMProp1) (1/2)%Qp
    ⊢ VMProp_holds V1 (1/2)%Qp -∗ WP ExecI @ V1
          {{ (λ m, False)}}%I.
  Proof.
    intro. rewrite /program1.
    iIntros (Hjump HIn) "(#inv & excl1 & (p_1 & p_2 & p_3 & p_4 & p_5 & p_6 & p7 & _) & acc & tx & rx & pc & (%r0 & r0) & (%r1 & r1) & (%r2 & r2)
                   & vmprop) holds".
    assert (pprog1 ≠ ptx1) as Hneqtx.
    {
      intro.
      feed pose proof (NoDup_lookup _ 1 6 ptx1 Hps_nd).
      simplify_eq /=. done.
      simplify_eq /=. done.
      lia.
    }
    rewrite to_pid_aligned_eq.
    pose proof (seq_in_page_forall2 _ _ _ HIn) as Hforall.
    clear HIn; rename Hforall into HIn.
    rewrite wp_sswp.
    iApply ((mov_word pprog1) with "[p_1 pc acc tx r1]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
    set_solver.
    iNext. iIntros "(pc & _ & acc & tx & r1) _".
    rewrite wp_sswp.
    iApply ((mov_word (pprog1 ^+ 1)%f) with "[p_2 pc acc tx r2]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
    set_solver.
    rewrite HIn. done.
    set_solver +.
    iNext. iIntros "(pc & _ & acc & tx & r2) _".
    rewrite wp_sswp.
    iApply (sswp_fupd_around _ ⊤ (⊤ ∖ ↑(N .@ "shared")) ⊤).
    iInv (N .@ "shared") as ">Inv" "HIClose".
    iDestruct "Inv" as "[(%w & share) | [excl1' share]]".
    2:{
      iExFalso.
      iApply (excl_exclusive with "excl1 excl1'").
    }
    iApply ((str ((pprog1 ^+ 1) ^+ 1)%f) with "[p_3 pc acc tx rx r1 r2 share]");
      rewrite -?Hpshare_eq ?to_pid_aligned_eq; iFrameAutoSolve.
    rewrite (HIn ((pprog1 ^+ 1) ^+ 1)%f).
    rewrite to_pid_aligned_eq.
    set_solver +.
    set_solver +.
    rewrite HIn. done.
    set_solver +.
    {
      rewrite to_pid_aligned_eq.
      intro.
      feed pose proof (NoDup_lookup _ 4 10 prx1 Hps_nd).
      simplify_eq /=. done.
      simplify_eq /=. done.
      lia.
    }
    iModIntro. iNext. iIntros "(pc & _ & r2 & share & r1 & acc & tx & rx)".
    iDestruct ("HIClose" with "[excl1 share]") as "HIClose".
    iNext;iRight;iFrame.
    iMod "HIClose" as "_". iModIntro. iIntros "_".
    rewrite wp_sswp.
    iApply ((mov_word (((pprog1 ^+ 1) ^+ 1) ^+ 1)%f) with "[p_4 pc acc tx r2]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
    rewrite HIn. set_solver +.
    set_solver +.
    rewrite HIn //. set_solver +.
    iNext. iIntros "(pc & _ & acc & tx & r2) _".
    iAssert (∃trans, VMProp V1 (vmprop_unknown V1 up_slice_trans up_slice_rxs trans) (1 / 2))%I with "[vmprop]" as "vmprop".
    {
      iExists _. iExact "vmprop".
    }
    iLöb as "L" forall (r0) "r0".
    iApply wp_sswp.
    iApply (mov_word ((((pprog1 ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f with "[p_5 pc acc tx r0]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
    rewrite HIn. set_solver +.
    set_solver +.
    rewrite HIn //. set_solver +.
    iNext. iIntros "(pc & p5 & acc & tx & r0) _".
    iApply wp_sswp.
    iDestruct "vmprop" as "[% vmprop]".
    iDestruct (VMProp_holds_agree with "[holds vmprop]") as "[P prop1]".
    iSplitR "vmprop".
    iDestruct "holds" as "[% [? vmprop]]". iExists _. iSplitR "vmprop".
    2: iExact "vmprop". done.
    iExact "vmprop".
    iDestruct (vmprop_unknown_eq with "P") as "P".
    rewrite bi.later_exist. iDestruct "P" as "[% P]".
    rewrite bi.later_exist. iDestruct "P" as "[% P]".
    rewrite 9!bi.later_sep.
    iDestruct "P" as "(>P1 & >P2 & P3 & >[% [r0z _]] & >[% [r1z _]] & >P6 & P7 & >P8 & >%P9 & prop0)".
    pose proof (P9 V1). destruct H.
    iApply (yield (((((pprog1 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+1)%f (True) (vmprop_unknown V1 up_slice_trans up_slice_rxs a)
             with "[p_6 pc acc tx r0 prop1 r0z r1z prop0 P1 P2 P3 P6 P7 P8]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
    rewrite HIn. set_solver +.
    set_solver +.
    rewrite HIn //. set_solver +.
    apply decode_encode_hvc_func.
    iSplitL "prop0". iExact "prop0".
    iSplitL "prop1". iExact "prop1".
    iSplitL. iNext. iIntros "[(pc & p_6 & acc & tx & r0 & r0z & r1z) [_ prop1]]".
    iSplitL "P1 P2 P3 P6 P7 P8 prop1 r0z r1z".
    rewrite /vmprop_zero /vmprop_zero_pre.
    iExists a, x.
    iSplit. iPureIntro. apply only_except_disjoint.
    rewrite only_except_union.
    iSplit. iPureIntro. intros. done.
    iFrame "P2 P3".
    iDestruct ("P7" $! x H) as "[$ P7]".
    iSplitL "P7".
    destruct x. destruct p. destruct (decide (v = V0)).
    rewrite rxs_wf_prim_eq //.
    pose proof (slice_rxs_sym up_slice_rxs V1 V0 (i:= V1) (os:=(Some (f, v)))).
    simpl in H0. pose proof n. apply H0 in n. case_bool_decide;auto.
    pose proof (slice_rxs_empty up_slice_rxs V1 V0).
    rewrite H0 //.
    iSplitR "prop1";[|done].
    rewrite /return_reg_rx.
    iLeft. iSplitL "r0z". iLeft. done.
    iFrame "P8 P6 r1z".
    iCombine "pc p_6 acc tx r0" as "R'". iExact "R'".
    done.
    iNext. iIntros "[(pc & p6 & acc & tx & r0) prop1] holds".
    iApply wp_sswp.
    iApply (br ((((((pprog1 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f with "[p7 pc acc tx r2]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
    rewrite HIn. set_solver +.
    set_solver +.
    rewrite HIn //. set_solver +.
    iNext. iIntros "(pc & [p7 r2] & acc & tx) _".
    iApply ("L" with "p5 p6 p7 holds r1 rx [pc] acc tx r2 [prop1] r0").
    assert (((((pprog1 ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f = jump_i) as ->.
    solve_finz + Hjump.
    done.
    iExists _. iExact "prop1".
   Qed.

  Lemma up_machine3 γ :
    let program3 := up_program3 in
    (* Addresses-values connection *)
    seq_in_page (of_pid pprog3) (length program3) pprog3 ->
    inv_pshare γ pshare ∗
    (* Mem for program *)
    (program (program3) (of_pid pprog3)) ∗
    V3 -@A> {[pprog3;pshare;ptx3;prx3]} ∗
    TX@ V3 := (tpa ptx3) ∗
    RX@ V3 := (tpa prx3) ∗
    (* Program counter *)
    PC @@ V3 ->r (of_pid pprog3) ∗
    (∃ nz, NZ @@ V3 ->r nz) ∗
    (* Work registers *)
    (∃ r0, R0 @@ V3 ->r r0) ∗
    (∃ r1, R1 @@ V3 ->r r1) ∗
    (∃ r2, R2 @@ V3 ->r r2) ∗
    VMProp V3 (VMProp3) (1/2)%Qp
    ⊢ VMProp_holds V3 (1/2)%Qp -∗ WP ExecI @ V3
           {{ (λ m, ⌜m = HaltI⌝ ∗ R1 @@ V3 ->r fortytwo)}}%I.
  Proof.
    intro. rewrite /program3.
    iIntros (HIn) "(#inv & (p_1 & p_2 & p_3 & p_4 & p_5 & p_6 & _) & acc & tx & rx & pc & (%nz & nz) & (%r0 & r0) & (%r1 & r1) & (%r2 & r2)
                   & vmprop) holds".
    assert (pprog3 ≠ ptx3) as Hneqtx.
    {
      intro.
      feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).
      simplify_eq /=. done.
      simplify_eq /=. done.
      lia.
    }
    rewrite to_pid_aligned_eq.
    pose proof (seq_in_page_forall2 _ _ _ HIn) as Hforall.
    clear HIn; rename Hforall into HIn.
    iLöb as "L" forall (nz r0 r1 r2) "nz r0 r1 r2".
    iApply wp_sswp.
    iApply ((mov_word pprog3) with "[p_1 pc acc tx r2]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
    set_solver.
    iNext. iIntros "(pc & p_1 & acc & tx & r2) _".
    iApply wp_sswp.
    iApply ((mov_word (pprog3 ^+ 1)%f) with "[p_2 pc acc tx r0]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
    set_solver.
    rewrite HIn.
    {
      intro.
      feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).
      simplify_eq /=. done.
      simplify_eq /=.
    }
    set_solver +.
    iNext. iIntros "(pc & p_2 & acc & tx & r0) _".
    iApply wp_sswp.
    iApply (sswp_fupd_around _ ⊤ (⊤ ∖ ↑(N .@ "shared")) ⊤).
    iInv (N .@ "shared") as ">Inv" "HIClose".
    iDestruct "Inv" as "[ (% & share) | [excl1' share]]".
    {
      iApply ((ldr ((pprog3 ^+ 1) ^+ 1)%f) with "[p_3 pc acc tx r1 r2 share]"); rewrite -?Hpshare_eq ?to_pid_aligned_eq; iFrameAutoSolve.
      rewrite (HIn ((pprog3 ^+ 1) ^+ 1)%f).
      rewrite to_pid_aligned_eq.
      set_solver +.
      set_solver +.
      {
        rewrite to_pid_aligned_eq.
        intro.
        feed pose proof (NoDup_lookup _ 4 8 ptx3 Hps_nd).
        simplify_eq /=. done.
        simplify_eq /=. done.
        lia.
      }
      rewrite HIn. done.
      set_solver +. iModIntro.
      iNext. iIntros "(pc & p_3 & r2 & share & r1 & acc & tx)".
      iDestruct ("HIClose" with "[share]") as ">_".
      iNext;iLeft. iExists _; iFrame.
      iModIntro. iIntros "_".
      iApply wp_sswp.
      iApply ((cmp.cmp_word (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f) with "[p_4 pc nz r1 acc tx]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
      rewrite (HIn (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f).
      set_solver +.
      set_solver +.
      rewrite (HIn (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f).
      {
        intro.
        feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).
        simplify_eq /=. done.
        done.
      }
      set_solver +.
      iNext. iIntros "(pc & p_4 & r1 & acc & nz & tx)".
      (* destruct (decide (w = fortytwo)). *)
      iIntros "_".
      iApply wp_sswp.
      iApply ((bne.bne ((((pprog3 ^+ 1) ^+ 1) ^+ 1) ^+1)%f) with "[p_5 pc nz r0 acc tx]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
      rewrite HIn.
      set_solver +.
      set_solver +.
      rewrite HIn.
      {
        intro.
        feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).
        simplify_eq /=. done.
        done.
      }
      set_solver +.
      iNext. iIntros "(pc & p_5 & r0 & acc & nz & tx)".
      iIntros "_".
      destruct (decide (w = fortytwo)).
      assert (w <? fortytwo = false)%f as ->.
      solve_finz + e.
      assert (fortytwo <? w = false)%f as ->.
      solve_finz + e.
      assert ((W1 =? W1)%f = true) as ->.
      solve_finz.
      iApply wp_sswp.
      iApply ((halt (((((pprog3 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f) with "[p_6 pc acc tx]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
      rewrite HIn. set_solver +.
      set_solver +.
      rewrite HIn //. set_solver +.
      iNext. iIntros "(pc & _ & acc & tx) _".
      iApply wp_terminated. done.
      rewrite e. iFrame "r1". done.
      assert (((if w <? fortytwo then W2 else if fortytwo <? w then W0 else W1) =? W1) = false)%f as ->.
      {
        destruct (decide (w < fortytwo)%f).
        assert (w <? fortytwo = true)%f as ->.
        solve_finz + l.
        solve_finz +.
        assert (w <? fortytwo = false)%f as ->.
        solve_finz + n n0.
        assert (fortytwo <? w = true)%f as ->.
        solve_finz + n n0.
        solve_finz +.
      }
      iApply ("L" with "p_1 p_2 p_3 p_4 p_5 p_6 acc tx rx [pc] [vmprop] [holds] nz r0 r1 r2").
      rewrite Hpprog3_eq. done.
      done.
      rewrite /VMProp_holds.
      iDestruct "holds" as "[% [H1 H2]]".
      iExists _. iSplitL "H1". 2:{ iExact "H2". }
                             iNext. done.
    }
      iApply ((ldr ((pprog3 ^+ 1) ^+ 1)%f) with "[p_3 pc acc tx r1 r2 share]"); rewrite -?Hpshare_eq ?to_pid_aligned_eq; iFrameAutoSolve.
      rewrite (HIn ((pprog3 ^+ 1) ^+ 1)%f).
      rewrite to_pid_aligned_eq.
      set_solver +.
      set_solver +.
      {
        rewrite to_pid_aligned_eq.
        intro.
        feed pose proof (NoDup_lookup _ 4 8 ptx3 Hps_nd).
        simplify_eq /=. done.
        simplify_eq /=. done.
        lia.
      }
      rewrite HIn. done.
      set_solver +. iModIntro.
      iNext. iIntros "(pc & p_3 & r2 & share & r1 & acc & tx)".
      iDestruct ("HIClose" with "[share]") as ">_".
      iNext;iLeft. iExists _; iFrame.
      iModIntro. iIntros "_".
      iApply wp_sswp.
      iApply ((cmp.cmp_word (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f) with "[p_4 pc nz r1 acc tx]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
      rewrite (HIn (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f).
      set_solver +.
      set_solver +.
      rewrite (HIn (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f).
      {
        intro.
        feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).
        simplify_eq /=. done.
        done.
      }
      set_solver +.
      iNext. iIntros "(pc & p_4 & r1 & acc & nz & tx)".
      (* destruct (decide (w = fortytwo)). *)
      iIntros "_".
      iApply wp_sswp.
      iApply ((bne.bne ((((pprog3 ^+ 1) ^+ 1) ^+ 1) ^+1)%f) with "[p_5 pc nz r0 acc tx]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
      rewrite HIn.
      set_solver +.
      set_solver +.
      rewrite HIn.
      {
        intro.
        feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).
        simplify_eq /=. done.
        done.
      }
      set_solver +.
      iNext. iIntros "(pc & p_5 & r0 & acc & nz & tx)".
      iIntros "_".
      assert (fortytwo <? fortytwo = false)%f as ->.
      solve_finz + .
      assert ((W1 =? W1)%f = true) as ->.
      solve_finz.
      iApply wp_sswp.
      iApply ((halt (((((pprog3 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f) with "[p_6 pc acc tx]"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.
      rewrite HIn. set_solver +.
      set_solver +.
      rewrite HIn //. set_solver +.
      iNext. iIntros "(pc & _ & acc & tx) _".
      iApply wp_terminated. done.
      iFrame "r1". done.
  Qed.

  Definition up_interp_access2 := interp_access (V2 : leibnizO VMID) up_slice_trans up_slice_rxs ptx2 prx2 {[pprog2; ptx2; prx2]}
                                    ({[W0 := (V1, V3, {[pshare]}, Sharing, true)]}).

  Lemma up_ftlr2: up_interp_access2 ⊢ interp_execute V2.
  Proof. iApply ftlr. Qed.

  Definition up_interp_access0 rxs := interp_access_prim up_slice_trans up_slice_rxs ptx0 prx0 {[pprog0; ptx0; prx0]}
                                    {[W0 := (V1, V3, {[pshare]}, Sharing, true)]} rxs.

  Lemma up_ftlr0 rxs : up_interp_access0 rxs ⊢ interp_execute_prim.
  Proof. iApply ftlr_p. Qed.

End up_proof.


(* *********************************************************************)
(*                                                                     *)
(*              The Compcert verified compiler                         *)
(*                                                                     *)
(*                 Xavier Leroy, INRIA Paris                           *)
(*                                                                     *)
(*  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.     *)
(*                                                                     *)
(* *********************************************************************)

(** Correctness of instruction selection for 64-bit integer operations *)

Require Import String Coqlib Maps Zbits Integers Floats Errors.
Require Archi.
Require Import AST Values Memory Globalenvs Events.
Require Import Cminor Op CminorSel.
Require Import SelectOp SelectOpproof SplitLong SplitLongproof.
Require Import SelectLong.

Local Open Scope cminorsel_scope.
Local Open Scope string_scope.

(** * Correctness of the instruction selection functions for 64-bit operators *)

Section CMCONSTR.

Variable prog: program.
Variable hf: helper_functions.
Hypothesis HELPERS: helper_functions_declared prog hf.
Let ge := Genv.globalenv prog.
Variable sp: val.
Variable e: env.
Variable m: mem.

Definition unary_constructor_sound (cstr: expr -> expr) (sem: val -> val) : Prop :=
  forall le a x,
  eval_expr ge sp e m le a x ->
  exists v, eval_expr ge sp e m le (cstr a) v /\ Val.lessdef (sem x) v.

Definition binary_constructor_sound (cstr: expr -> expr -> expr) (sem: val -> val -> val) : Prop :=
  forall le a x b y,
  eval_expr ge sp e m le a x ->
  eval_expr ge sp e m le b y ->
  exists v, eval_expr ge sp e m le (cstr a b) v /\ Val.lessdef (sem x y) v.

Definition partial_unary_constructor_sound (cstr: expr -> expr) (sem: val -> option val) : Prop :=
  forall le a x y,
  eval_expr ge sp e m le a x ->
  sem x = Some y ->
  exists v, eval_expr ge sp e m le (cstr a) v /\ Val.lessdef y v.

Definition partial_binary_constructor_sound (cstr: expr -> expr -> expr) (sem: val -> val -> option val) : Prop :=
  forall le a x b y z,
  eval_expr ge sp e m le a x ->
  eval_expr ge sp e m le b y ->
  sem x y = Some z ->
  exists v, eval_expr ge sp e m le (cstr a b) v /\ Val.lessdef z v.

Theorem eval_longconst:
  forall le n, eval_expr ge sp e m le (longconst n) (Vlong n).
Proof.
  unfold longconst; intros; destruct Archi.splitlong.
  apply SplitLongproof.eval_longconst.
  EvalOp.
Qed.

Lemma is_longconst_sound:
  forall v a n le,
  is_longconst a = Some n -> eval_expr ge sp e m le a v -> v = Vlong n.
Proof with (try discriminate).
  intros. unfold is_longconst in *. destruct Archi.splitlong.
  eapply SplitLongproof.is_longconst_sound; eauto.
  assert (a = Eop (Olongconst n) Enil).
  { destruct a... destruct o... destruct e0... congruence. }
  subst a. InvEval. auto.
Qed.

Theorem eval_intoflong: unary_constructor_sound intoflong Val.loword.
Proof.
  unfold intoflong; destruct Archi.splitlong. apply SplitLongproof.eval_intoflong.
  red; intros. destruct (is_longconst a) as [n|] eqn:C.
- TrivialExists. simpl. erewrite (is_longconst_sound x) by eauto. auto.
- TrivialExists.
Qed.

Theorem eval_longofintu: unary_constructor_sound longofintu Val.longofintu.
Proof.
  unfold longofintu; destruct Archi.splitlong. apply SplitLongproof.eval_longofintu.
  red; intros. destruct (is_intconst a) as [n|] eqn:C.
- econstructor; split. apply eval_longconst.
  exploit is_intconst_sound; eauto. intros; subst x. auto.
- TrivialExists.
Qed.

Theorem eval_longofint: unary_constructor_sound longofint Val.longofint.
Proof.
  unfold longofint; destruct Archi.splitlong. apply SplitLongproof.eval_longofint.
  red; intros. destruct (is_intconst a) as [n|] eqn:C.
- econstructor; split. apply eval_longconst.
  exploit is_intconst_sound; eauto. intros; subst x. auto.
- TrivialExists.
Qed.

Theorem eval_notl: unary_constructor_sound notl Val.notl.
Proof.
  unfold notl; destruct Archi.splitlong. apply SplitLongproof.eval_notl.
  red; intros. destruct (notl_match a).
- InvEval. econstructor; split. apply eval_longconst. auto.
- InvEval. subst. exists v1; split; auto. destruct v1; simpl; auto. rewrite Int64.not_involutive; auto.
- TrivialExists.
Qed.

Theorem eval_andlimm: forall n, unary_constructor_sound (andlimm n) (fun v => Val.andl v (Vlong n)).
Proof.
  unfold andlimm; intros; red; intros.
  predSpec Int64.eq Int64.eq_spec n Int64.zero.
  exists (Vlong Int64.zero); split. apply eval_longconst.
  subst. destruct x; simpl; auto. rewrite Int64.and_zero; auto.
  predSpec Int64.eq Int64.eq_spec n Int64.mone.
  exists x; split. assumption.
  subst. destruct x; simpl; auto. rewrite Int64.and_mone; auto.
  destruct (andlimm_match a); InvEval; subst.
- econstructor; split. apply eval_longconst. simpl. rewrite Int64.and_commut; auto.
- TrivialExists. simpl. rewrite Val.andl_assoc. rewrite Int64.and_commut; auto.
- TrivialExists. simpl. destruct v1; simpl; auto. unfold Int64.rolm. rewrite Int64.and_assoc.
  rewrite  (Int64.and_commut mask2 n). reflexivity.
- TrivialExists.
Qed.

Theorem eval_andl: binary_constructor_sound andl Val.andl.
Proof.
  unfold andl; destruct Archi.splitlong. apply SplitLongproof.eval_andl.
  red; intros. destruct (andl_match a b).
- InvEval. rewrite Val.andl_commut. apply eval_andlimm; auto.
- InvEval. apply eval_andlimm; auto.
- TrivialExists.
Qed.

Theorem eval_orlimm: forall n, unary_constructor_sound (orlimm n) (fun v => Val.orl v (Vlong n)).
Proof.
  unfold orlimm; intros; red; intros.
  predSpec Int64.eq Int64.eq_spec n Int64.zero.
  exists x; split; auto. subst. destruct x; simpl; auto. rewrite Int64.or_zero; auto.
  predSpec Int64.eq Int64.eq_spec n Int64.mone.
  econstructor; split. apply eval_longconst. subst. destruct x; simpl; auto. rewrite Int64.or_mone; auto.
  destruct (orlimm_match a); InvEval; subst.
- econstructor; split. apply eval_longconst. simpl. rewrite Int64.or_commut; auto.
- TrivialExists. simpl. rewrite Val.orl_assoc. rewrite Int64.or_commut; auto.
- TrivialExists.
Qed.

Theorem eval_orl: binary_constructor_sound orl Val.orl.
Proof.
  unfold orl; destruct Archi.splitlong. apply SplitLongproof.eval_orl.
  red; intros.
  assert (DEFAULT: exists v, eval_expr ge sp e m le (Eop Oorl (a:::b:::Enil)) v /\ Val.lessdef (Val.orl x y) v) by TrivialExists.
  assert (ROLM: forall v n1 n2 m1 m2,
             n1 = n2 ->
             Val.lessdef (Val.orl (Val.rolml v n1 m1) (Val.rolml v n2 m2))
                         (Val.rolml v n1 (Int64.or m1 m2))).
  { intros. destruct v; simpl; auto. unfold Int64.rolm.
    rewrite Int64.and_or_distrib. rewrite H1. auto. }
  destruct (orl_match a b).
- predSpec Int.eq Int.eq_spec amount1 amount2; simpl.
   destruct (same_expr_pure t1 t2) eqn:?; auto. InvEval.
   exploit eval_same_expr; eauto. intros [EQ1 EQ2]; subst.
   exists (Val.rolml v0 amount2 (Int64.or mask1 mask2)); split. EvalOp.
   apply ROLM; auto. auto.
- InvEval. rewrite Val.orl_commut. apply eval_orlimm; auto.
- InvEval. apply eval_orlimm; auto.
- apply DEFAULT.
Qed.

Theorem eval_xorlimm: forall n, unary_constructor_sound (xorlimm n) (fun v => Val.xorl v (Vlong n)).
Proof.
  unfold xorlimm; intros; red; intros.
  predSpec Int64.eq Int64.eq_spec n Int64.zero.
  exists x; split; auto. subst. destruct x; simpl; auto. rewrite Int64.xor_zero; auto.
  predSpec Int64.eq Int64.eq_spec n Int64.mone.
  replace (Val.xorl x (Vlong n)) with (Val.notl x). apply eval_notl; auto.
  subst n. destruct x; simpl; auto.
  destruct (xorlimm_match a); InvEval; subst.
- econstructor; split. apply eval_longconst. simpl. rewrite Int64.xor_commut; auto.
- TrivialExists. simpl. rewrite Val.xorl_assoc. rewrite Int64.xor_commut; auto.
- TrivialExists. simpl. destruct v1; simpl; auto. unfold Int64.not.
  rewrite Int64.xor_assoc. apply f_equal. apply f_equal. apply f_equal.
  apply Int64.xor_commut.
- TrivialExists.
Qed.

Theorem eval_xorl: binary_constructor_sound xorl Val.xorl.
Proof.
  unfold xorl; destruct Archi.splitlong. apply SplitLongproof.eval_xorl.
  red; intros. destruct (xorl_match a b).
- InvEval. rewrite Val.xorl_commut. apply eval_xorlimm; auto.
- InvEval. apply eval_xorlimm; auto.
- TrivialExists.
Qed.

Theorem eval_rolml: forall amount mask, unary_constructor_sound (fun v => rolml v amount mask) (fun v => Val.rolml v amount mask).
Proof.
  unfold rolml. intros; red; intros.
  predSpec Int.eq Int.eq_spec amount Int.zero.
  rewrite H0.
  exploit (eval_andlimm). eauto. intros (x0 & (H1 & H2)).
  exists x0. split. apply H1. destruct x; auto. simpl. unfold Int64.rolm.
  change (Int64.repr (Int.unsigned Int.zero)) with Int64.zero. rewrite Int64.rol_zero.
  apply H2.
  destruct (rolml_match a).
- econstructor; split. apply eval_longconst. simpl. InvEval. unfold Val.rolml. auto.
- InvEval. TrivialExists. simpl. rewrite <- H.
  unfold Val.rolml; destruct v1; simpl; auto.
  rewrite Int64.rolm_rolm by (exists (two_p (64-6)); auto).
  f_equal. f_equal. f_equal.
  unfold Int64.add. rewrite ! Int64.int_unsigned_repr. unfold Int.add.
  set (a := Int.unsigned amount1 + Int.unsigned amount).
  unfold Int.modu, Int64.modu.
  change (Int.unsigned Int64.iwordsize') with 64.
  change (Int64.unsigned Int64.iwordsize) with 64.
  f_equal.
  rewrite Int.unsigned_repr.
  apply eqmod_mod_eq. lia.
  apply eqmod_trans with a.
  apply eqmod_divides with Int.modulus. apply Int.eqm_sym. apply Int.eqm_unsigned_repr.
  exists (two_p (32-6)); auto.
  apply eqmod_divides with Int64.modulus. apply Int64.eqm_unsigned_repr.
  exists (two_p (64-6)); auto.
  assert (0 <= Int.unsigned (Int.repr a) mod 64 < 64) by (apply Z_mod_lt; lia).
  assert (64 < Int.max_unsigned) by (compute; auto).
  lia.
- InvEval. TrivialExists. simpl. rewrite <- H.
  unfold Val.rolml; destruct v1; simpl; auto. unfold Int64.rolm.
  rewrite Int64.rol_and. rewrite Int64.and_assoc. auto.
- TrivialExists.
Qed.

Theorem eval_shllimm: forall n, unary_constructor_sound (fun e => shllimm e n) (fun v => Val.shll v (Vint n)).
Proof.
  intros; unfold shllimm. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shllimm; auto.
  red; intros.
  predSpec Int.eq Int.eq_spec n Int.zero.
  exists x; split; auto. subst n; destruct x; simpl; auto.
  destruct (Int.ltu Int.zero Int64.iwordsize'); auto.
  change (Int64.shl' i Int.zero) with (Int64.shl i Int64.zero). rewrite Int64.shl_zero; auto.
  destruct (Int.ltu n Int64.iwordsize') eqn:LT; simpl.
- rewrite Val.shll_rolml by apply LT. apply eval_rolml. auto.
- TrivialExists. constructor; eauto.  constructor. EvalOp. simpl; eauto. constructor.
  constructor.
Qed.

Theorem eval_shrluimm: forall n, unary_constructor_sound (fun e => shrluimm e n) (fun v => Val.shrlu v (Vint n)).
Proof.
  unfold shrluimm; destruct Archi.splitlong. apply SplitLongproof.eval_shrluimm. auto.
  red; intros.
  predSpec Int.eq Int.eq_spec n Int.zero.
  exists x. split. apply H. destruct x; simpl; auto. rewrite H0. rewrite Int64.shru'_zero. constructor.
  destruct (Int.ltu n Int64.iwordsize') eqn:LT; simpl.
- rewrite Val.shrlu_rolml by apply LT. apply eval_rolml. auto.
- TrivialExists. constructor; eauto.  constructor. EvalOp. simpl; eauto. constructor.
  constructor.
Qed.

Theorem eval_shrlimm: forall n, unary_constructor_sound (fun e => shrlimm e n) (fun v => Val.shrl v (Vint n)).
Proof.
  intros; unfold shrlimm. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrlimm; auto.
  red; intros.
  predSpec Int.eq Int.eq_spec n Int.zero.
  exists x; split; auto. subst n; destruct x; simpl; auto.
  destruct (Int.ltu Int.zero Int64.iwordsize'); auto.
  change (Int64.shr' i Int.zero) with (Int64.shr i Int64.zero). rewrite Int64.shr_zero; auto.
  destruct (Int.ltu n Int64.iwordsize') eqn:LT; simpl.
  assert (DEFAULT: exists v, eval_expr ge sp e m le (Eop (Oshrlimm n) (a:::Enil)) v
                         /\  Val.lessdef (Val.shrl x (Vint n)) v) by TrivialExists.
  destruct (shrlimm_match a); InvEval.
- TrivialExists. simpl; rewrite LT; auto.
- destruct (Int.ltu (Int.add n n1) Int64.iwordsize') eqn:LT'; auto.
  subst. econstructor; split. EvalOp. simpl; eauto.
  destruct v1; simpl; auto. rewrite LT'.
  destruct (Int.ltu n1 Int64.iwordsize') eqn:LT1; auto.
  simpl; rewrite LT. rewrite Int.add_commut, Int64.shr'_shr'; auto. rewrite Int.add_commut; auto.
- apply DEFAULT.
- TrivialExists. constructor; eauto. constructor. EvalOp. simpl; eauto. constructor. auto.
Qed.

Theorem eval_shll: binary_constructor_sound shll Val.shll.
Proof.
  unfold shll. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shll; auto.
  red; intros. destruct (is_intconst b) as [n2|] eqn:C.
- exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shllimm; auto.
- TrivialExists.
Qed.

Theorem eval_shrlu: binary_constructor_sound shrlu Val.shrlu.
Proof.
  unfold shrlu. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrlu; auto.
  red; intros. destruct (is_intconst b) as [n2|] eqn:C.
- exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shrluimm; auto.
- TrivialExists.
Qed.

Theorem eval_shrl: binary_constructor_sound shrl Val.shrl.
Proof.
  unfold shrl. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrl; auto.
  red; intros. destruct (is_intconst b) as [n2|] eqn:C.
- exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shrlimm; auto.
- TrivialExists.
Qed.

Theorem eval_negl: unary_constructor_sound negl Val.negl.
Proof.
  unfold negl. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_negl; auto.
  red; intros. destruct (is_longconst a) as [n|] eqn:C.
- exploit is_longconst_sound; eauto. intros EQ; subst x.
  econstructor; split. apply eval_longconst. auto.
- TrivialExists.
Qed.

Theorem eval_addlimm: forall n, unary_constructor_sound (addlimm n) (fun v => Val.addl v (Vlong n)).
Proof.
  unfold addlimm.
  red; intros. predSpec Int64.eq Int64.eq_spec n Int64.zero.
  exists x. split; auto. rewrite H0. destruct x; auto. simpl. rewrite Int64.add_zero. constructor.
  destruct (addlimm_match a).
- econstructor; split. apply eval_longconst. simpl. InvEval. unfold Val.rolml. auto.
- InvEval. TrivialExists. simpl. rewrite <- H. rewrite Val.addl_assoc. reflexivity.
- InvEval. TrivialExists.
Qed.

Theorem eval_addl: binary_constructor_sound addl Val.addl.
Proof.
  unfold addl. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_addl; auto.
  red; intros. destruct (addl_match a b); InvEval; subst.
- exploit (eval_addlimm n1); eauto. intros (n & (H1 & H2)). exists n. split; auto.
  rewrite Val.addl_commut. exact H2.
- exploit (eval_addlimm n2). apply H. auto.
- rewrite Val.addl_permut_4. simpl.
  apply eval_addlimm; EvalOp.
- rewrite Val.addl_assoc. rewrite Val.addl_permut. rewrite Val.addl_commut.
  apply eval_addlimm; EvalOp.
- rewrite Val.addl_commut. rewrite Val.addl_assoc. rewrite Val.addl_permut.
  rewrite Val.addl_commut. apply eval_addlimm; EvalOp. rewrite Val.addl_commut.
  constructor.
- TrivialExists.
Qed.

Theorem eval_subl: binary_constructor_sound subl Val.subl.
Proof.
  unfold subl. destruct Archi.splitlong eqn:SL.
  apply SplitLongproof.eval_subl. apply Archi.splitlong_ptr32; auto.
  red; intros; destruct (subl_match a b); InvEval.
- rewrite Val.subl_addl_opp. apply eval_addlimm; auto.
-  TrivialExists.
Qed.

Theorem eval_mullimm_base: forall n, unary_constructor_sound (mullimm_base n) (fun v => Val.mull v (Vlong n)).
Proof.
  intros; unfold mullimm_base. red. intros.
  assert (DEFAULT: exists v : val, eval_expr ge sp e m le (Eop Omull (a ::: longconst n ::: Enil)) v
                              /\ Val.lessdef (Val.mull x (Vlong n)) v).
  { TrivialExists. constructor. eauto. constructor. apply eval_longconst. constructor. auto. }
  generalize (Int64.one_bits'_decomp n); intros D.
  destruct (Int64.one_bits' n) as [ | i [ | j [ | ? ? ]]] eqn:B; auto.
- replace (Val.mull x (Vlong n)) with (Val.shll x (Vint i)).
  apply eval_shllimm; auto.
  simpl in D. rewrite D, Int64.add_zero. destruct x; simpl; auto.
  rewrite (Int64.one_bits'_range n) by (rewrite B; auto with coqlib).
  rewrite Int64.shl'_mul; auto.
- set (le' := x :: le).
  assert (A0: eval_expr ge sp e m le' (Eletvar O) x) by (constructor; reflexivity).
  exploit (eval_shllimm i). eexact A0. intros (v1 & A1 & B1).
  exploit (eval_shllimm j). eexact A0. intros (v2 & A2 & B2).
  exploit (eval_addl). eexact A1. eexact A2. intros (v3 & A3 & B3).
  exists v3; split. econstructor; eauto.
  rewrite D. simpl. rewrite Int64.add_zero. destruct x; auto.
  simpl in *.
  rewrite (Int64.one_bits'_range n) in B1 by (rewrite B; auto with coqlib).
  rewrite (Int64.one_bits'_range n) in B2 by (rewrite B; auto with coqlib).
  inv B1; inv B2. simpl in B3; inv B3.
  rewrite Int64.mul_add_distr_r. rewrite <- ! Int64.shl'_mul. auto.
Qed.

Theorem eval_mullimm: forall n, unary_constructor_sound (mullimm n) (fun v => Val.mull v (Vlong n)).
Proof.
  unfold mullimm. intros.
  destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_mullimm; eauto.
  red; intros. predSpec Int64.eq Int64.eq_spec n Int64.zero.
  exists (Vlong Int64.zero).
  split. apply eval_longconst. destruct x; simpl; auto.
  subst n; rewrite Int64.mul_zero; auto.
  predSpec Int64.eq Int64.eq_spec n Int64.one.
  exists x; split; auto.
  destruct x; simpl; auto. subst n; rewrite Int64.mul_one; auto.
  destruct (mullimm_match a); InvEval.
- econstructor; split. apply eval_longconst. rewrite Int64.mul_commut; auto.
- exploit (eval_mullimm_base n); eauto.
Qed.

Theorem eval_mull: binary_constructor_sound mull Val.mull.
Proof.
  unfold mull. destruct Archi.splitlong eqn:SL.
  apply SplitLongproof.eval_mull; auto.
  red; intros. destruct (mull_match a b).
- exploit (eval_mullimm n1); eauto. intros (n & (H1 & H2)). InvEval. exists n. split; auto.
  rewrite Val.mull_commut. exact H2.
- exploit (eval_mullimm n2). apply H. InvEval. auto.
- TrivialExists.
Qed.

Theorem eval_mullhu:
  forall n, unary_constructor_sound (fun a => mullhu a n) (fun v => Val.mullhu v (Vlong n)).
Proof.
  unfold mullhu; intros. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_mullhu; auto.
  red; intros. TrivialExists. constructor. eauto. constructor. apply eval_longconst. constructor. auto.
Qed.

Theorem eval_mullhs:
  forall n, unary_constructor_sound (fun a => mullhs a n) (fun v => Val.mullhs v (Vlong n)).
Proof.
  unfold mullhs; intros. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_mullhs; auto.
  red; intros. TrivialExists. constructor. eauto. constructor. apply eval_longconst. constructor. auto.
Qed.

Theorem eval_shrxlimm:
  forall le a n x z,
  eval_expr ge sp e m le a x ->
  Val.shrxl x (Vint n) = Some z ->
  exists v, eval_expr ge sp e m le (shrxlimm a n) v /\ Val.lessdef z v.
Proof.
  unfold shrxlimm. intros. destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_shrxlimm; eauto.
  predSpec Int.eq Int.eq_spec n Int.zero.
- subst n. destruct x; simpl in H0; inv H0. econstructor; split; eauto.
  change (Int.ltu Int.zero (Int.repr 63)) with true. simpl. rewrite Int64.shrx'_zero; auto.
- TrivialExists.
Qed.

Theorem eval_divls_base: partial_binary_constructor_sound divls_base Val.divls.
Proof.
  unfold divls_base; red; intros. destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_divls_base; eauto.
  TrivialExists.
Qed.

Lemma eval_modl_aux:
  forall divop semdivop,
  (forall sp x y m, eval_operation ge sp divop (x :: y :: nil) m = semdivop x y) ->
  forall le a b x y z,
  eval_expr ge sp e m le a x ->
  eval_expr ge sp e m le b y ->
  semdivop x y = Some z ->
  eval_expr ge sp e m le (modl_aux divop a b) (Val.subl x (Val.mull z y)).
Proof.
  intros; unfold modl_aux.
  eapply eval_Elet. eexact H0. eapply eval_Elet.
  apply eval_lift. eexact H1.
  eapply eval_Eop. eapply eval_Econs.
  eapply eval_Eletvar. simpl; reflexivity.
  eapply eval_Econs. eapply eval_Eop.
  eapply eval_Econs. eapply eval_Eop.
  eapply eval_Econs. apply eval_Eletvar. simpl; reflexivity.
  eapply eval_Econs. apply eval_Eletvar. simpl; reflexivity.
  apply eval_Enil.
  rewrite H. eauto.
  eapply eval_Econs. apply eval_Eletvar. simpl; reflexivity.
  apply eval_Enil.
  simpl; reflexivity. apply eval_Enil.
  reflexivity.
Qed.

Theorem eval_modls_base: partial_binary_constructor_sound modls_base Val.modls.
Proof.
  unfold modls_base. red; intros. destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_modls_base; eauto.
  assert (DEFAULT: exists v : val, eval_expr ge sp e m le (modl_aux Odivl a b) v /\ Val.lessdef z v).
  exploit Val.modls_divls; eauto. intros [v [A B]].
  { subst. econstructor; split; eauto.
    apply eval_modl_aux with (semdivop := Val.divls); auto. }

  destruct (is_longconst a) as [n1|] eqn:A. exploit is_longconst_sound. eauto. eauto. intros.
  destruct (is_longconst b) as [n2|] eqn:B; auto. exploit is_longconst_sound. eauto. eauto. intros.
  predSpec Int64.eq Int64.eq_spec Int64.zero n2; simpl.
  (* n1 mod n2, n2 = 0 *)
  auto.
  predSpec Int64.eq Int64.eq_spec n1 (Int64.repr Int64.min_signed); predSpec Int64.eq Int64.eq_spec n2 Int64.mone; simpl; auto; subst.
- (* signed_min mod n2 | n2 != 0, n2 !- =1 *)
  econstructor; split. apply eval_longconst.
  unfold Val.modls in H1.
  rewrite Int64.eq_false in H1; auto.
  rewrite (Int64.eq_false n2 Int64.mone H6) in H1.
  inversion H1. auto.
- (* n1 mod -1, n1 !- signed_min *)
  econstructor; split. apply eval_longconst.
  unfold Val.modls in H1.
  rewrite Int64.eq_false in H1; auto.
  rewrite Int64.eq_false in H1; auto.
  inversion H1. auto.
- (* other valid cases *)
  econstructor; split. apply eval_longconst.
  unfold Val.modls in H1.
  rewrite Int64.eq_false in H1; auto.
  rewrite Int64.eq_false in H1; auto.
  inversion H1.
  auto.
- (* fallback *)
  apply DEFAULT.
Qed.

Theorem eval_divlu_base: partial_binary_constructor_sound divlu_base Val.divlu.
Proof.
  unfold divlu_base; red; intros. destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_divlu_base; eauto.
  TrivialExists.
Qed.

Theorem eval_modlu_base: partial_binary_constructor_sound modlu_base Val.modlu.
Proof.
  unfold modlu_base; red; intros. destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_modlu_base; eauto.
  assert (DEFAULT: exists v : val, eval_expr ge sp e m le (modl_aux Odivlu a b) v /\ Val.lessdef z v).
  exploit Val.modlu_divlu; eauto. intros [v [A B]].
  subst. econstructor; split; eauto.
  apply eval_modl_aux with (semdivop := Val.divlu); auto.
  (* n1 and n2 are longconsts *)
  destruct (is_longconst a) as [n1|] eqn:A. exploit is_longconst_sound; eauto.
  destruct (is_longconst b) as [n2|] eqn:B; auto. exploit is_longconst_sound; eauto. intros.
  predSpec Int64.eq Int64.eq_spec Int64.zero n2; simpl.
  (* n2 = 0 *)
-  auto.
  (* n2 != 0 *)
-  econstructor; split. apply eval_longconst.
  rewrite H2 in H1.
  rewrite H3 in H1.
  unfold Val.modlu in H1.
  rewrite Int64.eq_false in H1; auto.
  inversion H1. auto.
-  (* n1 no longconst, n2 is longconst *)
  destruct (is_longconst b) as [n2|] eqn:B; auto. exploit is_longconst_sound; eauto. intros.
  destruct (Int64.is_power2 n2) eqn:C; auto.
  (* n2 is power of 2 *)
  exploit eval_andlimm. apply H. intros. destruct H3.
  exists x0.  split. apply H3.
  replace z with (Val.andl x (Vlong (Int64.sub n2 Int64.one))). apply H3.
  apply (Val.modlu_pow2 x n2 i z); congruence.
Qed.

Theorem eval_cmplu:
  forall c le a x b y v,
  eval_expr ge sp e m le a x ->
  eval_expr ge sp e m le b y ->
  Val.cmplu (Mem.valid_pointer m) c x y = Some v ->
  eval_expr ge sp e m le (cmplu c a b) v.
Proof.
  unfold cmplu; intros. destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_cmplu; eauto using Archi.splitlong_ptr32.
  unfold Val.cmplu in H1.
  destruct (Val.cmplu_bool (Mem.valid_pointer m) c x y) as [vb|] eqn:C; simpl in H1; inv H1.
  destruct (is_longconst a) as [n1|] eqn:LC1; destruct (is_longconst b) as [n2|] eqn:LC2;
  try (assert (x = Vlong n1) by (eapply is_longconst_sound; eauto));
  try (assert (y = Vlong n2) by (eapply is_longconst_sound; eauto));
  subst.
- simpl in C; inv C. EvalOp. destruct (Int64.cmpu c n1 n2); reflexivity.
- EvalOp. simpl. rewrite Val.swap_cmplu_bool. rewrite C; auto.
- EvalOp. simpl; rewrite C; auto.
- EvalOp. simpl; rewrite C; auto.
Qed.

Theorem eval_cmpl:
  forall c le a x b y v,
  eval_expr ge sp e m le a x ->
  eval_expr ge sp e m le b y ->
  Val.cmpl c x y = Some v ->
  eval_expr ge sp e m le (cmpl c a b) v.
Proof.
  unfold cmpl; intros. destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_cmpl; eauto.
  unfold Val.cmpl in H1.
  destruct (Val.cmpl_bool c x y) as [vb|] eqn:C; simpl in H1; inv H1.
  destruct (is_longconst a) as [n1|] eqn:LC1; destruct (is_longconst b) as [n2|] eqn:LC2;
  try (assert (x = Vlong n1) by (eapply is_longconst_sound; eauto));
  try (assert (y = Vlong n2) by (eapply is_longconst_sound; eauto));
  subst.
- simpl in C; inv C. EvalOp. destruct (Int64.cmp c n1 n2); reflexivity.
- EvalOp. simpl. rewrite Val.swap_cmpl_bool. rewrite C; auto.
- EvalOp. simpl; rewrite C; auto.
- EvalOp. simpl; rewrite C; auto.
Qed.

Theorem eval_longoffloat:
  forall le a x y,
  eval_expr ge sp e m le a x ->
  Val.longoffloat x = Some y ->
  exists v, eval_expr ge sp e m le (longoffloat a) v /\ Val.lessdef y v.
Proof.
  unfold longoffloat. intros. destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_longoffloat; eauto.
  TrivialExists.
Qed.

Theorem eval_floatoflong:
  forall le a x y,
  eval_expr ge sp e m le a x ->
  Val.floatoflong x = Some y ->
  exists v, eval_expr ge sp e m le (floatoflong a) v /\ Val.lessdef y v.
Proof.
  unfold floatoflong. intros. destruct Archi.splitlong eqn:SL.
  eapply SplitLongproof.eval_floatoflong; eauto.
  TrivialExists.
Qed.

Theorem eval_longofsingle:
  forall le a x y,
  eval_expr ge sp e m le a x ->
  Val.longofsingle x = Some y ->
  exists v, eval_expr ge sp e m le (longofsingle a) v /\ Val.lessdef y v.
Proof.
  intros; unfold longofsingle.
  destruct x; simpl in H0; inv H0. destruct (Float32.to_long f) as [n|] eqn:EQ; simpl in H2; inv H2.
  exploit eval_floatofsingle; eauto. intros (v & A & B). simpl in B. inv B.
  apply Float32.to_long_double in EQ.
  eapply eval_longoffloat; eauto. simpl.
  change (Float.of_single f) with (Float32.to_double f); rewrite EQ; auto.
Qed.

End CMCONSTR.