CS153/hw6/bin/dce.ml
jmug 0c04936ccf Updated hw6 to a newer version
Signed-off-by: jmug <u.g.a.mariano@gmail.com>
2025-01-24 21:23:08 -08:00

61 lines
2.1 KiB
OCaml

(** Dead Code Elimination *)
open Ll
open Datastructures
(* expose a top-level analysis operation ------------------------------------ *)
(* TASK: This function should optimize a block by removing dead instructions
- lb: a function from uids to the live-OUT set at the
corresponding program point
- ab: the alias map flowing IN to each program point in the block
- b: the current ll block
Note:
Call instructions are never considered to be dead (they might produce
side effects)
Store instructions are not dead if the pointer written to is live _or_
the pointer written to may be aliased.
Other instructions are dead if the value they compute is not live.
Hint: Consider using List.filter
*)
let dce_block (lb:uid -> Liveness.Fact.t) (ab:uid -> Alias.fact) (b:Ll.block) : Ll.block =
(* check by each instruction *)
let is_not_dead (uid : uid) (insn: insn) : bool =
match insn with
| Call _ -> true
| Store (_, _, ptr) ->
(* not dead if live or mayalias *)
(* if we're storing into a *)
let ptr_uid = match ptr with | Id i -> i | Gid i -> i | _ -> failwith "Store must be an id" in
let ptr_live = UidS.mem ptr_uid (lb uid) in
let ptr_alias = UidM.find_opt ptr_uid (ab uid) in (* <= issue: ab ptr_uid returns "Not_Found"*)
let ptr_alias = match ptr_alias with | Some alias -> (alias == MayAlias) | None -> false in
ptr_live || ptr_alias
| _ -> if UidS.mem uid (lb uid) then true else false
in let result = List.filter (fun (uid, insn) -> is_not_dead uid insn) b.insns in
let new_block : Ll.block = {insns = result; term = b.term} in new_block
let run (lg:Liveness.Graph.t) (ag:Alias.Graph.t) (cfg:Cfg.t) : Cfg.t =
LblS.fold (fun l cfg ->
let b = Cfg.block cfg l in
(* compute liveness at each program point for the block *)
let lb = Liveness.Graph.uid_out lg l in
(* compute aliases at each program point for the block *)
let ab = Alias.Graph.uid_in ag l in
(* compute optimized block *)
let b' = dce_block lb ab b in
Cfg.add_block l b' cfg
) (Cfg.nodes cfg) cfg