Home My Page Projects Code Snippets Project Openings diderot
Summary Activity Tracker Tasks SCM

SCM Repository

[diderot] View of /branches/vis15/src/compiler/high-to-mid/high-to-mid.sml
ViewVC logotype

View of /branches/vis15/src/compiler/high-to-mid/high-to-mid.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3830 - (download) (annotate)
Thu May 5 22:13:46 2016 UTC (3 years, 2 months ago) by jhr
File size: 12607 byte(s)
  Working on merge: getting clamp and lerp sorted
(* high-to-mid.sml
 *
 * Translation from HighIR to MidIR representations.
 *
 * This code is part of the Diderot Project (http://diderot-language.cs.uchicago.edu)
 *
 * COPYRIGHT (c) 2015 The University of Chicago
 * All rights reserved.
 *)

structure HighToMid : sig

    val translate : HighIR.program -> MidIR.program

  end = struct

    structure SrcIR = HighIR
    structure SrcTy = HighTypes
    structure SrcOp = HighOps
    structure SrcSV = SrcIR.StateVar
    structure VTbl = SrcIR.Var.Tbl
    structure DstIR = MidIR
    structure DstTy = MidTypes
    structure DstOp = MidOps
    structure InP = Inputs
    structure BCtl = BorderCtl

    fun useCount (SrcIR.V{useCnt, ...}) = !useCnt

    fun getRHS x = (case SrcIR.Var.getDef x
	   of SrcIR.GLOBAL gv => raise Fail(concat[
		  "expected rhs binding for ", SrcIR.Var.toString x,
		  " but found mutable global ", SrcIR.GlobalVar.toString gv
		])
	    | rhs => rhs
	  (* end case *))

    fun getRHSOp x = (case SrcIR.Var.getDef x
           of SrcIR.OP(rator, args) => (rator, args)
            | rhs => raise Fail(concat[
                  "expected rhs operator for ", SrcIR.Var.toString x,
                  " but found ", SrcIR.RHS.toString rhs
                ])
          (* end case *))

  (* get the image referenced on a RHS and its border control (if any) *)
    fun getRHSImage x = (case getRHSOp x
	   of (SrcOp.BorderCtlDefault info, [img, v]) => (info, BCtl.Default v)
	    | (SrcOp.BorderCtlClamp info, [img]) => (info, BCtl.clamp)
	    | (SrcOp.BorderCtlMirror info, [img]) => (info, BCtl.mirror)
	    | (SrcOp.BorderCtlWrap info, [img]) => (info, BCtl.wrap)
	    | (SrcOp.LoadImage(SrcTy.ImageTy info, _), _) => (info, BCtl.None)
	    | _ => raise Fail "bogus image variable"
	  (* end case *))

    fun cvtTy SrcTy.BoolTy = DstTy.BoolTy
      | cvtTy SrcTy.StringTy = DstTy.StringTy
      | cvtTy SrcTy.IntTy = DstTy.intTy
      | cvtTy (SrcTy.TensorTy dd) = DstTy.tensorTy dd
      | cvtTy (SrcTy.SeqTy(ty, n)) = DstTy.SeqTy(cvtTy ty, n)
    (* we replace Kernel and Field operations by 0, so the types are mapped to int *)
      | cvtTy SrcTy.KernelTy = DstTy.KernelTy
      | cvtTy SrcTy.FieldTy = DstTy.intTy
      | cvtTy (SrcTy.ImageTy info) = DstTy.ImageTy info
      | cvtTy ty = raise Fail("unexpected type " ^ SrcTy.toString ty)

  (* instantiate the translation environment *)
    structure Env = TranslateEnvFn (
      struct
        structure SrcIR = SrcIR
        structure DstIR = DstIR
        val cvtTy = cvtTy
      end)

  (* expand raising a real to an integer power.  When we know the exponent, we can inline
   * multiplications.
   *)
    fun expandPower (env, y, [x, n]) = let
          fun getConst x = (case SrcIR.Var.getDef x
                 of SrcIR.LIT(Literal.Int n) => SOME n
                  | _ => NONE
                (* end case *))
          val x = Env.rename(env, x)
          fun pow () = let
                val t = DstIR.Var.new("n", DstTy.realTy)
                in [
                  (t, DstIR.OP(DstOp.IntToReal, [Env.rename(env, n)])),
                  (y, DstIR.OP(DstOp.MathFn MathFns.POW, [x, t]))
                ] end
          in
            case getConst n
             of SOME 0 => [(y, DstIR.LIT(Literal.Real(RealLit.one)))]
              | SOME 1 => [(y, DstIR.VAR x)]
              | SOME ~1 => let
                  val t = DstIR.Var.new("one", DstTy.realTy)
                  in [
                    (t, DstIR.LIT(Literal.Real(RealLit.one))),
                    (y, DstIR.EINAPP(MkOperators.divRR, [t, x]))
                  ] end
              | SOME 2 => [(y, DstIR.EINAPP(MkOperators.mulRR, [x, x]))]
(* FIXME: expand into multiplications
              | SOME n =>
*) | SOME _ => pow()
              | NONE => pow()
            (* end case *)
          end

  (* expand the field Inside operator into a image-space test *)
    fun expandInside (env, result, pos, fld) = (case getRHS fld
           of SrcIR.EINAPP(_, [img, h]) => (case (getRHSImage img, getRHSOp h)
                 of ((v, _), (SrcOp.Kernel(h, _), _)) => let
                      val pos = Env.rename (env, pos)
                      val img = Env.rename (env, img)
                      val s = Kernel.support h
		    (* map pos to index space point ix *)
                      val (ix, code) = let
			    val avail = AvailRHS.new()
			    val (ix, _, _) = CoordSpaceTransform.worldToIndex{
				    avail = avail, info = v, img = img, pos = pos
				  }
			    in
			      (ix, AvailRHS.getAssignments avail)
			    end
		      val code = (result, DstIR.OP(DstOp.Inside(v, s), [ix, img])) :: code
                      in
                        List.rev code
                      end
                  | _ => raise Fail "bogus kernel binding"
                (* end case *))
            | _ => raise Fail "bogus field binding"
          (* end case *))

    fun arity (SrcTy.TensorTy[]) = 1
      | arity (SrcTy.TensorTy[d]) = d
      | arity _ = raise Fail "arity"

    fun expandOp (env, y, rator, args) = let
          fun assign rator' =
                [(y, DstIR.OP(rator', Env.renameList(env, args)))]
          fun cvtToInt rator' = let
                val t = DstIR.Var.new ("t", DstTy.realTy)
                in [
                  (t, DstIR.OP(rator', Env.renameList(env, args))),
                  (y, DstIR.OP(DstOp.RealToInt 1, [t]))
                ] end
          fun dummy () = [(y, DstIR.LIT(Literal.Int 0))]
          fun copy () = let val [x] = args
                in
                  [(y, DstIR.VAR(Env.rename(env, x)))]
                end
          in
            case rator
             of SrcOp.IAdd => assign DstOp.IAdd
              | SrcOp.ISub => assign DstOp.ISub
              | SrcOp.IMul => assign DstOp.IMul
              | SrcOp.IDiv => assign DstOp.IDiv
              | SrcOp.IMod => assign DstOp.IMod
              | SrcOp.INeg => assign DstOp.INeg
              | SrcOp.LT ty => assign (DstOp.LT(cvtTy ty))
              | SrcOp.LTE ty => assign (DstOp.LTE(cvtTy ty))
              | SrcOp.EQ ty => assign (DstOp.EQ(cvtTy ty))
              | SrcOp.NEQ ty => assign (DstOp.NEQ(cvtTy ty))
              | SrcOp.GT ty => assign (DstOp.GT(cvtTy ty))
              | SrcOp.GTE ty => assign (DstOp.GTE(cvtTy ty))
              | SrcOp.Power => expandPower(env, y, args)
              | SrcOp.Not => assign DstOp.Not
              | SrcOp.Abs ty => assign (DstOp.Abs(cvtTy ty))
              | SrcOp.Max ty => assign (DstOp.Max(cvtTy ty))
              | SrcOp.Min ty => assign (DstOp.Min(cvtTy ty))
              | SrcOp.Clamp ty => assign (DstOp.Clamp(cvtTy ty))
              | SrcOp.MapClamp ty => assign (DstOp.MapClamp(cvtTy ty))
              | SrcOp.Lerp ty => assign (DstOp.Lerp(cvtTy ty))
              | SrcOp.Zero ty => assign (DstOp.Zero(cvtTy ty))
(* FIXME: why not create the EINAPP when translating from SimpleAST to HighIR? *)
              | SrcOp.TensorSlice(SrcTy.TensorTy argTy, mask) => let
		(* extract the integer indices from the mask *)
		  val args' = List.mapPartial Fn.id mask
		  val mask' = List.map Option.isSome mask
                  val DstTy.TensorTy rstTy = DstIR.Var.ty y
                  val rator = MkOperators.slice (argTy, mask', args', rstTy)
                  val a = Env.renameList(env, args)
                  in
                    [(y, DstIR.EINAPP(rator, a))]
                  end
              | SrcOp.TensorIndex(ty, shp) => assign (DstOp.TensorIndex(cvtTy ty, shp))
              | SrcOp.Select(ty, i) => assign (DstOp.Select(cvtTy ty, i))
              | SrcOp.Subscript(ty as SrcTy.SeqTy _) => assign (DstOp.Subscript(cvtTy ty))
              | SrcOp.MkDynamic(ty, n) => assign (DstOp.MkDynamic(cvtTy ty, n))
              | SrcOp.Append ty => assign (DstOp.Append(cvtTy ty))
              | SrcOp.Prepend ty => assign (DstOp.Prepend(cvtTy ty))
              | SrcOp.Concat ty => assign (DstOp.Concat(cvtTy ty))
	      | SrcOp.Range => assign DstOp.Range
              | SrcOp.Length ty => assign (DstOp.Length(cvtTy ty))
              | SrcOp.SphereQuery(ty1, ty2) => assign (DstOp.SphereQuery(cvtTy ty1, cvtTy ty2))
              | SrcOp.IntToReal => assign DstOp.IntToReal
              | SrcOp.TruncToInt => cvtToInt (DstOp.Trunc 1)
              | SrcOp.RoundToInt => cvtToInt (DstOp.Round 1)
              | SrcOp.CeilToInt => cvtToInt (DstOp.Ceiling 1)
              | SrcOp.FloorToInt => cvtToInt (DstOp.Floor 1)
(* FIXME: how are we going to use these? *)
	      | SrcOp.R_All ty => assign (DstOp.R_All(cvtTy ty))
	      | SrcOp.R_Exists ty => assign (DstOp.R_Exists(cvtTy ty))
	      | SrcOp.R_Max ty => assign (DstOp.R_Max(cvtTy ty))
	      | SrcOp.R_Min ty => assign (DstOp.R_Min(cvtTy ty))
	      | SrcOp.R_Sum ty => assign (DstOp.R_Sum(cvtTy ty))
	      | SrcOp.R_Product ty => assign (DstOp.R_Product(cvtTy ty))
	      | SrcOp.R_Mean ty => assign (DstOp.R_Mean(cvtTy ty))
	      | SrcOp.R_Variance ty => assign (DstOp.R_Variance(cvtTy ty))
              | SrcOp.Kernel h => assign (DstOp.Kernel h)
              | SrcOp.Inside _ => (case args
                   of [pos, fld] => expandInside(env, y, pos, fld)
                  (* end case *))
              | SrcOp.ImageDim(info, i) => assign (DstOp.ImageDim(info, i))
	      | SrcOp.BorderCtlDefault info => assign (DstOp.BorderCtlDefault info)
	      | SrcOp.BorderCtlClamp info => assign (DstOp.BorderCtlClamp info)
	      | SrcOp.BorderCtlMirror info => assign (DstOp.BorderCtlMirror info)
	      | SrcOp.BorderCtlWrap info => assign (DstOp.BorderCtlWrap  info)
              | SrcOp.LoadSeq(ty, file) => assign (DstOp.LoadSeq(cvtTy ty, file))
              | SrcOp.LoadImage(ty, file) => assign (DstOp.LoadImage(cvtTy ty, file))
              | SrcOp.MathFn e => assign (DstOp.MathFn e)
              | rator => raise Fail("bogus operator " ^ SrcOp.toString rator)
            (* end case *)
          end
handle ex => (print(concat["error converting ", SrcOp.toString rator, "\n"]); raise ex)

  (* expandEINAPP: env* midil.var*EIN*mid-ilvar->DstIR.ASSGN list
   * Field operators are changed to zero
   *)
    fun expandEINAPP (env, srcy, y, rator, args) = (case SrcIR.Var.ty srcy
           of SrcTy.FieldTy => [DstIR.ASSGN(y, DstIR.LIT(Literal.Int 0))]
            | _ => if (useCount srcy > 0)
		then HandleEin.expand (y, rator, Env.renameList(env, args))
		else []
          (* end case *))
handle ex => (print(concat["error converting: ", MidIR.Var.toString y, " = ",
EinPP.toString rator, " ", "(", String.concatWithMap ", " HighIR.Var.toString args, ")\n"]);
raise ex)

  (* expand a SrcIR assignment to a list of DstIR assignments *)
    fun expand (env, (y, rhs)) = let
          fun assign rhs = [DstIR.ASSGN(Env.rename (env, y), rhs)]
          in
            case rhs
             of SrcIR.GLOBAL x => assign (DstIR.GLOBAL(Env.renameGV(env, x)))
              | SrcIR.STATE x => assign (DstIR.STATE(Env.renameSV(env, x)))
              | SrcIR.VAR x => assign (DstIR.VAR(Env.rename(env, x)))
              | SrcIR.LIT lit => assign (DstIR.LIT lit)
              | SrcIR.OP(rator, args) =>
                  List.map DstIR.ASSGN (expandOp (env, Env.rename (env, y), rator, args))
              | SrcIR.CONS(args, ty) => assign (DstIR.CONS(Env.renameList(env, args), cvtTy ty))
              | SrcIR.SEQ(args, ty) => assign (DstIR.SEQ(Env.renameList(env, args), cvtTy ty))
              | SrcIR.EINAPP(rator, args) =>
                  expandEINAPP (env, y, Env.rename (env, y), rator, args)
            (* end case *)
          end

  (* expand a SrcIR multi-assignment to a DstIR CFG *)
    fun mexpand (env, (ys, rator, xs)) = let
          val ys' = Env.renameList(env, ys)
          val rator' = (case rator
                 of SrcOp.Eigen2x2 => DstOp.EigenVecs2x2
                  | SrcOp.Eigen3x3 => DstOp.EigenVecs3x3
                  | SrcOp.Print tys => DstOp.Print(List.map cvtTy tys)
                  | _ => raise Fail("bogus operator " ^ SrcOp.toString rator)
                (* end case *))
          val xs' = Env.renameList(env, xs)
          val nd = DstIR.Node.mkMASSIGN(ys', rator', xs')
          in
            DstIR.CFG{entry=nd, exit=nd}
          end

    structure Trans =  TranslateFn (
      struct
        open Env
        val expand = DstIR.CFG.mkBlock o expand
        val mexpand = mexpand
      end)

    structure Promote = PromoteFn (DstIR)

    fun translate prog = let
(* need a prepass to add Inside tests for border control *)
          val prog = Trans.translate prog
          in
            MidCensus.init prog;
            Promote.transform prog
          end

  end

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0