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

SCM Repository

[diderot] Annotation of /trunk/src/compiler/cl-target/cl-target.sml
ViewVC logotype

Annotation of /trunk/src/compiler/cl-target/cl-target.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1989 - (view) (download)

1 : jhr 1671 (* cl-target.sml
2 :     *
3 :     * COPYRIGHT (c) 2011 The Diderot Project (http://diderot-language.cs.uchicago.edu)
4 :     * All rights reserved.
5 :     *)
6 :    
7 :     structure CLTarget : TARGET =
8 :     struct
9 :    
10 :     structure IL = TreeIL
11 :     structure V = IL.Var
12 :     structure Ty = IL.Ty
13 :     structure CL = CLang
14 :     structure RN = RuntimeNames
15 :     structure ToCL = TreeToCL
16 :     structure N = CNames
17 :     structure P = Paths
18 :     structure HF = CLHeaderFrag
19 :     structure SF = CLSchedFrag
20 :    
21 :     (* revmap f l == List.rev(List.map f l) *)
22 :     fun revmap f = let
23 :     fun rmap ([], l) = l
24 :     | rmap (x::r, l) = rmap (r, f x :: l)
25 :     in
26 :     fn l => rmap (l, [])
27 :     end
28 :    
29 :     (* common arithmetic *)
30 :     fun #+# (a, b) = CL.mkBinOp(a, CL.#+, b)
31 :     fun #*# (a, b) = CL.mkBinOp(a, CL.#*, b)
32 :     infix 5 #+#
33 :     infix 6 #*#
34 :    
35 :     (* translate TreeIL types to shadow types *)
36 :     fun shadowTy ty = (case ty
37 :     of Ty.BoolTy => CL.T_Named "cl_uint"
38 :     | Ty.IntTy => CL.T_Named(RN.shadowIntTy ())
39 :     | Ty.TensorTy[] => CL.T_Named(RN.shadowRealTy ())
40 :     | Ty.TensorTy[n] => CL.T_Named(RN.shadowVecTy n)
41 :     | Ty.TensorTy[n, m] => CL.T_Named(RN.shadowMatTy(n,m))
42 :     | Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}) => CL.T_Named(RN.shadowImageTy dim)
43 :     | _ => raise Fail(concat["TreeToC.trType(", Ty.toString ty, ")"])
44 :     (* end case *))
45 :    
46 :     (* FIXME: add comments that more clearly explain the difference between convertToShadow and
47 :     * convertStrandToShadow
48 :     *)
49 :     (* translate TreeIL types to shadow types *)
50 :     fun convertToShadow (ty, name) = (case ty
51 :     of Ty.IntTy => CL.mkAssign(
52 :     CL.mkSelect(CL.mkVar RN.shadowGlaobalsName, name),
53 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name))
54 :     | Ty.TensorTy[n]=> CL.mkCall(RN.convertToShadowVec n, [
55 :     CL.mkUnOp(CL.%&, CL.mkSelect(CL.mkVar RN.shadowGlaobalsName, name)),
56 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name)
57 :     ])
58 :     | Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}) => CL.mkCall(RN.shadowImageFunc dim, [
59 :     CL.mkVar "context",
60 :     CL.mkUnOp(CL.%&, CL.mkSelect(CL.mkVar RN.shadowGlaobalsName, name)),
61 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name)
62 :     ])
63 :     | Ty.TensorTy[n, m] => CL.mkCall(RN.convertToShadowMat(m,n), [
64 :     CL.mkSelect(CL.mkVar RN.shadowGlaobalsName, name),
65 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name)
66 :     ])
67 :     | _ => CL.mkAssign(
68 :     CL.mkSelect(CL.mkVar RN.shadowGlaobalsName,name),
69 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name))
70 :     (* end case *))
71 :    
72 :     (* generate code to convert strand TreeIL types to shadow types *)
73 :     fun convertStrandToShadow (ty, name, selfIn, selfOut) = (case ty
74 :     of Ty.IntTy => CL.mkAssign(
75 :     CL.mkIndirect(CL.mkVar selfIn, name),
76 :     CL.mkIndirect(CL.mkVar selfOut, name))
77 :     | Ty.TensorTy[n]=> CL.mkCall(RN.convertToShadowVec n, [
78 :     CL.mkUnOp(CL.%&, CL.mkIndirect(CL.mkVar selfIn, name)),
79 :     CL.mkIndirect(CL.mkVar selfOut, name)
80 :     ])
81 :     | Ty.TensorTy[n, m] => CL.mkCall(RN.convertToShadowMat(m,n), [
82 :     CL.mkUnOp(CL.%&, CL.mkIndirect(CL.mkVar selfIn, name)),
83 :     CL.mkIndirect(CL.mkVar selfOut, name)
84 :     ])
85 :     | _ => CL.mkAssign(
86 :     CL.mkIndirect(CL.mkVar selfIn, name),
87 :     CL.mkIndirect(CL.mkVar selfOut, name))
88 :     (* end case *))
89 :    
90 :     (* helper functions for specifying parameters in various address spaces *)
91 :     fun clParam (spc, ty, x) = CL.PARAM([spc], ty, x)
92 :     fun globalParam (ty, x) = CL.PARAM(["__global"], ty, x)
93 :     fun constantParam (ty, x) = CL.PARAM(["__constant"], ty, x)
94 :     fun localParam (ty, x) = CL.PARAM(["__local"], ty, x)
95 :     fun privateParam (ty, x) = CL.PARAM(["__private"], ty, x)
96 :    
97 :     (* OpenCL global pointer type *)
98 :     fun globalPtr ty = CL.T_Qual("__global", CL.T_Ptr ty)
99 :    
100 :     (* lvalue/rvalue state variable *)
101 :     fun lvalueSV name = CL.mkIndirect(CL.mkVar "selfOut", name)
102 :     fun rvalueSV name = CL.mkIndirect(CL.mkVar "selfIn", name)
103 :    
104 :     (* C variable translation *)
105 :     structure TrCVar =
106 :     struct
107 :     type env = CL.typed_var TreeIL.Var.Map.map
108 :     fun lookup (env, x) = (case V.Map.find (env, x)
109 :     of SOME(CL.V(_, x')) => x'
110 :     | NONE => raise Fail(concat["TrCVar.lookup(_, ", V.name x, ")"])
111 :     (* end case *))
112 :     (* translate a variable that occurs in an l-value context (i.e., as the target of an assignment) *)
113 :     fun lvalueVar (env, x) = (case V.kind x
114 :     of IL.VK_Global => CL.mkIndirect(CL.mkVar RN.globalsVarName, lookup(env, x))
115 :     | IL.VK_Local => CL.mkVar(lookup(env, x))
116 :     (* end case *))
117 :     (* translate a variable that occurs in an r-value context *)
118 :     fun rvalueVar (env, x) = (case V.kind x
119 :     of IL.VK_Global => CL.mkIndirect(CL.mkVar RN.globalsVarName, lookup(env, x))
120 :     | IL.VK_Local => CL.mkVar(lookup(env, x))
121 :     (* end case *))
122 :     (* translate a strand state variable that occurs in an l-value context *)
123 :     fun lvalueStateVar (IL.SV{name, ...}) = lvalueSV name
124 :     (* translate a strand state variable that occurs in an r-value context *)
125 :     fun rvalueStateVar (IL.SV{name, ...}) = rvalueSV name
126 :     end
127 :    
128 :     structure ToC = TreeToCFn (TrCVar)
129 :    
130 :     type var = CL.typed_var
131 :     type exp = CL.exp
132 :     type stm = CL.stm
133 :    
134 :     (* OpenCL specific types *)
135 :     val clIntTy = CL.T_Named "cl_int"
136 :     val clProgramTy = CL.T_Named "cl_program"
137 :     val clKernelTy = CL.T_Named "cl_kernel"
138 :     val clCmdQueueTy = CL.T_Named "cl_command_queue"
139 :     val clContextTy = CL.T_Named "cl_context"
140 :     val clDeviceIdTy = CL.T_Named "cl_device_id"
141 :     val clPlatformIdTy = CL.T_Named "cl_platform_id"
142 :     val clMemoryTy = CL.T_Named "cl_mem"
143 :     val globPtrTy = CL.T_Ptr(CL.T_Named RN.globalsTy)
144 :     (* FIXME: what are these for? *)
145 :     datatype shadow_env = STRAND_SHADOW | GLOBAL_SHADOW
146 :    
147 :     (* variable or field that is mirrored between host and GPU *)
148 :     type mirror_var = {
149 :     (* FIXME: perhaps it would be cleaner to just track the TreeIL type of the variable? *)
150 :     hostTy : CL.ty, (* variable type on Host (i.e., C type) *)
151 :     shadowTy : CL.ty, (* host-side shadow type of GPU type *)
152 :     gpuTy : CL.ty, (* variable's type on GPU (i.e., OpenCL type) *)
153 :     hToS: stm, (* the statement that converts the variable to its *)
154 :     (* shadow representation *)
155 :     var : CL.var (* variable name *)
156 :     }
157 :    
158 :     datatype strand = Strand of {
159 :     name : string,
160 :     tyName : string,
161 :     state : mirror_var list,
162 :     output : (Ty.ty * CL.var), (* the strand's output variable (only one for now) *)
163 :     code : CL.decl list ref,
164 :     init_code: CL.decl ref
165 :     }
166 :    
167 :     datatype program = Prog of {
168 :     name : string, (* stem of source file *)
169 :     double : bool, (* true for double-precision support *)
170 :     parallel : bool, (* true for multithreaded (or multi-GPU) target *)
171 :     debug : bool, (* true for debug support in executable *)
172 :     globals : mirror_var list ref,
173 :     topDecls : CL.decl list ref,
174 :     strands : strand AtomTable.hash_table,
175 :     initially : CL.decl ref,
176 :     numDims: int ref, (* number of dimensions in initially iteration *)
177 :     imgGlobals: (string * int) list ref,
178 :     prFn: CL.decl ref,
179 :     outFn: CL.decl ref
180 :     }
181 :    
182 :     datatype env = ENV of {
183 :     info : env_info,
184 :     vMap : var V.Map.map,
185 :     scope : scope
186 :     }
187 :    
188 :     and env_info = INFO of {
189 :     prog : program
190 :     }
191 :    
192 :     and scope
193 :     = NoScope
194 :     | GlobalScope
195 :     | InitiallyScope
196 :     | StrandScope (* strand initialization *)
197 :     | MethodScope of StrandUtil.method_name (* method body; vars are state variables *)
198 :    
199 :     (* the supprted widths of vectors of reals on the target. *)
200 :     (* FIXME: for OpenCL 1.1, 3 is also valid *)
201 :     fun vectorWidths () = [2, 4, 8, 16]
202 :    
203 :     (* we do not support printing on the OpenCL target *)
204 :     val supportsPrinting = false
205 :    
206 :     (* tests for whether various expression forms can appear inline *)
207 :     fun inlineCons n = (n < 2) (* vectors are inline, but not matrices *)
208 :     val inlineMatrixExp = false (* can matrix-valued expressions appear inline? *)
209 :    
210 :     (* TreeIL to target translations *)
211 :     structure Tr =
212 :     struct
213 :     fun fragment (ENV{info, vMap, scope}, blk) = let
214 :     val (vMap, stms) = (case scope
215 :     of GlobalScope => ToC.trFragment (vMap, blk)
216 :     | InitiallyScope => ToC.trFragment (vMap, blk)
217 : lamonts 1989 | StrandScope => ToC.trFragment (vMap, blk)
218 : jhr 1671 | _ => ToCL.trFragment (vMap, blk)
219 :     (* end case *))
220 :     in
221 :     (ENV{info=info, vMap=vMap, scope=scope}, stms)
222 :     end
223 :     fun block (ENV{vMap, scope, ...}, blk) = (case scope
224 :     of StrandScope => ToC.trBlock (vMap, blk)
225 :     | MethodScope name => ToCL.trBlock (vMap, blk)
226 : lamonts 1989 | InitiallyScope => ToC.trBlock (vMap, blk)
227 : jhr 1671 | _ => ToC.trBlock (vMap, blk)
228 :     (* end case *))
229 : lamonts 1989 fun exp (ENV{vMap,scope, ...}, e) = (case scope
230 :     of InitiallyScope => ToC.trExp(vMap, e)
231 :     | StrandScope => ToC.trExp(vMap, e)
232 :     | _ => ToCL.trExp(vMap, e)
233 :     (* end case *))
234 : jhr 1671 end
235 :    
236 :     (* variables *)
237 :     structure Var =
238 :     struct
239 :     fun mirror (ty, name, shadowEnv) = {
240 :     hostTy = ToC.trType ty,
241 :     shadowTy = shadowTy ty,
242 :     gpuTy = ToCL.trType ty,
243 :     hToS = case shadowEnv
244 :     of GLOBAL_SHADOW => convertToShadow (ty, name)
245 :     | STRAND_SHADOW => convertStrandToShadow(ty, name, "selfIn", "selfOut")
246 :     (* end case *),
247 :     var = name
248 :     }
249 :     fun name (ToCL.V(_, name)) = name
250 :     fun global (Prog{globals, imgGlobals, ...}, name, ty) = let
251 :     val x = mirror (ty, name, GLOBAL_SHADOW)
252 :     fun isImgGlobal (Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}), name) =
253 :     imgGlobals := (name,dim) :: !imgGlobals
254 :     | isImgGlobal _ = ()
255 :     in
256 :     globals := x :: !globals;
257 :     isImgGlobal (ty, name);
258 :     ToCL.V(#gpuTy x, name)
259 :     end
260 : lamonts 1989 fun param (ENV{scope, ...},x) = (case scope
261 :     of StrandScope => CL.V(ToC.trType(V.ty x), V.name x)
262 :     | InitiallyScope => CL.V(ToC.trType(V.ty x), V.name x)
263 :     | _ => ToCL.V(ToCL.trType(V.ty x), V.name x)
264 :     (* end case *))
265 : jhr 1671 end
266 :    
267 :     (* environments *)
268 :     structure Env =
269 :     struct
270 :     (* create a new environment *)
271 :     fun new prog = ENV{
272 :     info=INFO{prog = prog},
273 :     vMap = V.Map.empty,
274 :     scope = NoScope
275 :     }
276 :     (* define the current translation context *)
277 :     fun setScope scope (ENV{info, vMap, ...}) = ENV{info=info, vMap=vMap, scope=scope}
278 :     val scopeGlobal = setScope GlobalScope
279 :     val scopeInitially = setScope InitiallyScope
280 :     fun scopeStrand env = setScope StrandScope env
281 :     fun scopeMethod (env, name) = setScope (MethodScope name) env
282 :     (* bind a TreeIL varaiable to a target variable *)
283 :     fun bind (ENV{info, vMap, scope}, x, x') = ENV{
284 :     info = info,
285 :     vMap = V.Map.insert(vMap, x, x'),
286 :     scope = scope
287 :     }
288 :     end
289 :    
290 :     (* programs *)
291 :     structure Program =
292 :     struct
293 :     fun new {name, double, parallel, debug} = (
294 :     RN.initTargetSpec double;
295 :     CNames.initTargetSpec {double=double, long=false};
296 :     Prog{
297 :     name = name,
298 :     double = double, parallel = parallel, debug = debug,
299 :     globals = ref [],
300 :     topDecls = ref [],
301 :     strands = AtomTable.mkTable (16, Fail "strand table"),
302 :     initially = ref(CL.D_Comment["missing initially"]),
303 :     numDims = ref 0,
304 :     imgGlobals = ref[],
305 :     prFn = ref(CL.D_Comment(["No Print Function"])),
306 :     outFn = ref(CL.D_Comment(["No Output Function"]))
307 :     })
308 :    
309 :     (* register the code that is used to register command-line options for input variables *)
310 :     fun inputs (Prog{topDecls, ...}, stm) = let
311 :     val inputsFn = CL.D_Func(
312 :     [], CL.voidTy, RN.registerOpts,
313 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.optionsTy), "opts")],
314 :     stm)
315 :     in
316 :     topDecls := inputsFn :: !topDecls
317 :     end
318 :    
319 :     (* register the global initialization part of a program *)
320 :     fun init (Prog{topDecls, ...}, init) = let
321 :     val globalsDecl = CL.mkAssign(CL.mkVar RN.globalsVarName,
322 :     CL.mkApply("malloc", [CL.mkSizeof(CL.T_Named RN.globalsTy)]))
323 :     val initFn = CL.D_Func(
324 :     [], CL.voidTy, RN.initGlobals, [],
325 :     CL.mkBlock[
326 :     globalsDecl,
327 :     CL.mkCall(RN.initGlobalsHelper, [CL.mkVar RN.globalsVarName])
328 :     ])
329 :     val initHelperFn = CL.D_Func(
330 :     [], CL.voidTy, RN.initGlobalsHelper,
331 :     [CL.PARAM([], globPtrTy, RN.globalsVarName)],
332 :     init)
333 :     val shutdownFn = CL.D_Func(
334 :     [], CL.voidTy, RN.shutdown,
335 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.worldTy), "wrld")],
336 :     CL.S_Block[])
337 :     in
338 :     topDecls := shutdownFn :: initFn :: initHelperFn :: !topDecls
339 :     end
340 :    
341 :     (* create and register the initially function for a program *)
342 :     fun initially {
343 :     prog = Prog{name=progName, strands, initially,numDims, ...},
344 :     isArray : bool,
345 :     iterPrefix : stm list,
346 :     iters : (var * exp * exp) list,
347 :     createPrefix : stm list,
348 :     strand : Atom.atom,
349 :     args : exp list
350 :     } = let
351 :     val name = Atom.toString strand
352 :     val nDims = List.length iters
353 :     val worldTy = CL.T_Ptr(CL.T_Named N.worldTy)
354 :     fun mapi f xs = let
355 :     fun mapf (_, []) = []
356 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
357 :     in
358 :     mapf (0, xs)
359 :     end
360 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
361 :     val sizeInit = mapi
362 :     (fn (i, (CL.V(ty, _), lo, hi)) =>
363 :     (i, CL.I_Exp(CL.mkBinOp(hi, CL.#-, lo) #+# CL.mkIntTy(1, ty)))
364 :     ) iters
365 :     (* code to allocate the world and initial strands *)
366 :     val wrld = "wrld"
367 :     val allocCode = [
368 :     CL.mkComment["allocate initial block of strands"],
369 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
370 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
371 :     CL.mkDecl(worldTy, wrld,
372 :     SOME(CL.I_Exp(CL.mkApply(N.allocInitially, [
373 :     CL.mkVar "ProgramName",
374 :     CL.mkUnOp(CL.%&, CL.mkVar(N.strandDesc name)),
375 :     CL.mkBool isArray,
376 :     CL.mkIntTy(IntInf.fromInt nDims, CL.int32),
377 :     CL.mkVar "base",
378 :     CL.mkVar "size"
379 :     ]))))
380 :     ]
381 :     (* create the loop nest for the initially iterations *)
382 :     val indexVar = "ix"
383 :     val strandTy = CL.T_Ptr(CL.T_Named(N.strandTy name))
384 :     fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
385 :     CL.mkDecl(strandTy, "sp",
386 :     SOME(CL.I_Exp(
387 :     CL.mkCast(strandTy,
388 :     CL.mkApply(N.inState, [CL.mkVar "wrld", CL.mkVar indexVar]))))),
389 :     CL.mkCall(N.strandInit name, CL.mkVar "sp" :: args),
390 :     CL.mkAssign(CL.mkVar indexVar, CL.mkVar indexVar #+# CL.mkIntTy(1, CL.uint32))
391 :     ])
392 :     | mkLoopNest ((CL.V(ty, param), lo, hi)::iters) = let
393 :     val body = mkLoopNest iters
394 :     in
395 :     CL.mkFor(
396 :     [(ty, param, lo)],
397 :     CL.mkBinOp(CL.mkVar param, CL.#<=, hi),
398 :     [CL.mkPostOp(CL.mkVar param, CL.^++)],
399 :     body)
400 :     end
401 :     val iterCode = [
402 :     CL.mkComment["initially"],
403 :     CL.mkDecl(CL.uint32, indexVar, SOME(CL.I_Exp(CL.mkIntTy(0, CL.uint32)))),
404 :     mkLoopNest iters
405 :     ]
406 :     val body = CL.mkBlock(
407 :     iterPrefix @
408 :     allocCode @
409 :     iterCode @
410 :     [CL.mkReturn(SOME(CL.mkVar "wrld"))])
411 :     val initFn = CL.D_Func([], worldTy, N.initially, [], body)
412 :     in
413 :     numDims := nDims;
414 :     initially := initFn
415 :     end
416 :    
417 :    
418 :     (***** OUTPUT *****)
419 :    
420 :     fun genStrandPrint (Strand{name, tyName, state, output, code, ...}) = let
421 :     (* the print function *)
422 :     val prFnName = concat[name, "Print"]
423 :     val prFn = let
424 :     val params = [
425 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
426 :     CL.PARAM([], CL.T_Ptr(CL.T_Named(RN.strandShadowTy tyName)), "self")
427 :     ]
428 :     val (ty, x) = output
429 :     val outState = CL.mkIndirect(CL.mkVar "self", x)
430 :     val prArgs = (case ty
431 :     of Ty.IntTy => [CL.mkStr(!N.gIntFormat ^ "\n"), outState]
432 :     | Ty.SeqTy(Ty.IntTy, d) => let
433 :     fun sel i = CL.mkApply(
434 :     "VSUB",
435 :     [outState, CL.mkInt(IntInf.fromInt i)])
436 :     val fmt = CL.mkStr(
437 :     String.concatWith " " (List.tabulate(d, fn _ => !N.gIntFormat))
438 :     ^ "\n")
439 :     val args = List.tabulate (d, sel)
440 :     in
441 :     fmt :: args
442 :     end
443 :     | Ty.TensorTy[] => [CL.mkStr "%f\n", outState]
444 :     | Ty.TensorTy[d] => let
445 :     fun sel i = CL.mkApply(
446 :     "VSUB",
447 :     [outState, CL.mkInt(IntInf.fromInt i)])
448 :     val fmt = CL.mkStr(
449 :     String.concatWith " " (List.tabulate(d, fn _ => "%f"))
450 :     ^ "\n")
451 :     val args = List.tabulate (d, sel)
452 :     in
453 :     fmt :: args
454 :     end
455 :     | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
456 :     (* end case *))
457 :     in
458 :     CL.D_Func(["static"], CL.voidTy, prFnName, params,
459 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs))
460 :     end
461 :     in
462 :     prFn
463 :     end
464 :    
465 : jhr 1766 fun genStrandTyDef(targetTy,Strand{state,...},tyName) = (case state
466 :     of [] => CL.D_Comment(["No Strand Defintiion Included"])
467 :     | _ => CL.D_StructDef(
468 :     NONE,
469 :     revmap (fn x => (targetTy x, #var x)) state,
470 :     SOME tyName)
471 :     (* end case *))
472 : jhr 1671
473 :    
474 :    
475 :     (* generates the globals buffers and arguments function *)
476 :     fun genConvertShadowTypes (Strand{name, tyName, state,...}) = let
477 :     (* Delcare opencl setup objects *)
478 :     val errVar = "err"
479 :     val params = [
480 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut"),
481 :     CL.PARAM([], CL.T_Ptr(CL.T_Named(RN.strandShadowTy tyName)), "selfIn")
482 :     ]
483 :     val body = List.map (fn (x:mirror_var) => #hToS x) state
484 :     in
485 :     CL.D_Func([], CL.voidTy, RN.strandConvertName name, params, CL.mkBlock body)
486 :     end
487 :    
488 :     (* generates the opencl buffers for the image data *)
489 :     fun getGlobalDataBuffers (globals, imgGlobals, contextVar, errVar) = let
490 :     val globalBuffErr = "error creating OpenCL global buffer\n"
491 :     fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.mkVar errVar, CL.#!=, CL.mkVar "CL_SUCCESS"),
492 :     CL.mkBlock([CL.mkCall("fprintf",[CL.mkVar "stderr", CL.mkStr msg]),
493 :     CL.mkCall("exit",[CL.mkInt 1])]))
494 :     val shadowTypeDecl =
495 :     CL.mkDecl(CL.T_Named(RN.shadowGlobalsTy), RN.shadowGlaobalsName, NONE)
496 :     val globalToShadowStms = List.map (fn (x:mirror_var) => #hToS x) globals
497 :     val globalBufferDecl = CL.mkDecl(clMemoryTy,concat[RN.globalsVarName,"_cl"],NONE)
498 :     val globalBuffer = CL.mkAssign(CL.mkVar(concat[RN.globalsVarName,"_cl"]),
499 :     CL.mkApply("clCreateBuffer", [
500 :     CL.mkVar contextVar,
501 :     CL.mkBinOp(CL.mkVar "CL_MEM_READ_ONLY", CL.#|, CL.mkVar "CL_MEM_COPY_HOST_PTR"),
502 :     CL.mkSizeof(CL.T_Named RN.shadowGlobalsTy),
503 :     CL.mkUnOp(CL.%&,CL.mkVar RN.shadowGlaobalsName),
504 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
505 :     ]))
506 :     fun genDataBuffers ([],_,_,_) = []
507 :     | genDataBuffers ((var,nDims)::globals, contextVar, errVar,errFn) = let
508 :     val hostVar = CL.mkIndirect(CL.mkVar RN.globalsVarName, var)
509 :     val size = CL.mkIndirect(hostVar, "dataSzb")
510 :     in
511 :     CL.mkDecl(clMemoryTy, RN.addBufferSuffixData var ,NONE) ::
512 :     CL.mkAssign(CL.mkVar(RN.addBufferSuffixData var),
513 :     CL.mkApply("clCreateBuffer", [
514 :     CL.mkVar contextVar,
515 :     CL.mkVar "CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR",
516 :     size,
517 :     CL.mkIndirect(hostVar, "data"),
518 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
519 :     ])) ::
520 :     errFn(concat["error in creating ",RN.addBufferSuffixData var, " global buffer\n"]) ::
521 :     genDataBuffers(globals,contextVar,errVar,errFn)
522 :     end
523 :     in
524 :     [shadowTypeDecl] @ globalToShadowStms
525 :     @ [globalBufferDecl, globalBuffer,errorFn(globalBuffErr)]
526 :     @ genDataBuffers(imgGlobals,contextVar,errVar,errorFn)
527 :     end
528 :    
529 :     (* generates the kernel arguments for the image data *)
530 :     fun genGlobalArguments (globals, count, kernelVar, errVar) = let
531 :     val globalArgErr = "error creating OpenCL global argument\n"
532 :     fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.mkVar errVar, CL.#!=, CL.mkVar "CL_SUCCESS"),
533 :     CL.mkBlock([CL.mkCall("fprintf",[CL.mkVar "stderr", CL.mkStr msg]),
534 :     CL.mkCall("exit",[CL.mkInt 1])]))
535 :     val globalArgument = CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.&=,
536 :     CL.mkApply("clSetKernelArg",
537 :     [CL.mkVar kernelVar,
538 :     CL.mkPostOp(CL.mkVar count, CL.^++),
539 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
540 :     CL.mkUnOp(CL.%&,CL.mkVar(concat[RN.globalsVarName,"_cl"]))])))
541 :     fun genDataArguments ([],_,_,_,_) = []
542 :     | genDataArguments ((var,nDims)::globals,count,kernelVar,errVar,errFn) =
543 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.$=,
544 :     CL.mkApply("clSetKernelArg",
545 :     [CL.mkVar kernelVar,
546 :     CL.mkPostOp(CL.mkVar count, CL.^++),
547 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
548 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffixData var))]))) ::
549 :     errFn(concat["error in creating ",RN.addBufferSuffixData var, " argument\n"]) ::
550 :     genDataArguments (globals,count,kernelVar,errVar,errFn)
551 :     in
552 :     globalArgument :: errorFn globalArgErr ::
553 :     genDataArguments(globals, count, kernelVar, errVar,errorFn)
554 :     end
555 :    
556 :     (* generates the globals buffers and arguments function *)
557 :     fun genGlobalBuffersArgs (globals,imgGlobals) = let
558 :     (* Delcare opencl setup objects *)
559 :     val errVar = "err"
560 :     val params = [
561 :     CL.PARAM([],CL.T_Named("cl_context"), "context"),
562 :     CL.PARAM([],CL.T_Named("cl_kernel"), "kernel"),
563 :     CL.PARAM([],CL.T_Named("cl_command_queue"), "cmdQ"),
564 :     CL.PARAM([],CL.T_Named("int"), "argStart")
565 :     ]
566 :     val body = (case globals
567 :     of [] => [CL.mkReturn(NONE)]
568 :     | _ => let
569 :     val clGlobalBuffers =
570 :     getGlobalDataBuffers(globals, !imgGlobals, "context", errVar)
571 :     val clGlobalArguments =
572 :     genGlobalArguments(!imgGlobals, "argStart", "kernel", errVar)
573 :     in
574 :     (* Body: put all the statments together *)
575 :     CL.mkDecl(clIntTy, errVar, SOME(CL.I_Exp(CL.mkInt 0)))
576 :     :: clGlobalBuffers @ clGlobalArguments
577 :     end
578 :     (*end of case*))
579 :     in
580 :     CL.D_Func([],CL.voidTy,RN.globalsSetupName,params,CL.mkBlock(body))
581 :     end
582 :    
583 :     (* generate the global image meta-data and data parameters *)
584 :     fun genKeneralGlobalParams ((name,tyname)::[],line) =
585 :     concat[line, "__global void *", RN.addBufferSuffixData name]
586 :     | genKeneralGlobalParams ([],line) = line
587 :     | genKeneralGlobalParams ((name,tyname)::rest, line) =
588 :     genKeneralGlobalParams(rest, concat[line, "__global void *", RN.addBufferSuffixData name, ",\n"])
589 :    
590 :     fun genUpdateMethod (Strand{name, tyName, state,...}, globals, imgGlobals) = let
591 :     val imageDataStms = List.map
592 :     (fn (x,_) => concat[
593 :     RN.globalImageDataName, ".", RN.imageDataName x, " = ",
594 :     RN.addBufferSuffixData x, ";","\n"
595 :     ])
596 :     (!imgGlobals)
597 :     fun select ([], a, _) = a
598 :     | select (_, _, b) = b
599 :     val placeHolders = [
600 :     (RN.place_holders, tyName),
601 :     (RN.p_addDatPtr, select (!imgGlobals, "", ",")),
602 :     (RN.p_addGlobals, select (!globals, "", ",")),
603 :     (RN.p_globals, select (!globals, "", "__global Diderot_Globals_t *diderotGlobals")),
604 :     (RN.p_globalVar, select (!globals, "0", RN.globalsVarName)),
605 : lamonts 1989 (RN.p_dataVar, select (!imgGlobals, "0", RN.globalImageDataName)),
606 : jhr 1671 (RN.p_dataPtr, genKeneralGlobalParams (!imgGlobals, "")),
607 :     (RN.p_dataAssign, select (!imgGlobals, "",
608 :     String.concat("Diderot_data_ptr_t diderotDataPtrs;\n" :: imageDataStms)))
609 :     ]
610 :     in
611 :     CL.verbatim [CLUpdateFrag.text] placeHolders
612 :     end
613 :    
614 :     fun genStrandCopy(Strand{tyName,name,state,...}) = let
615 :     val params = [
616 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
617 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfOut")
618 :     ]
619 :     val assignStms = List.rev(
620 :     List.map
621 :     (fn x => CL.mkAssign(lvalueSV(#var x), rvalueSV(#var x)))
622 :     state)
623 :     in
624 :     CL.D_Func([""], CL.voidTy, RN.strandCopy, params,CL.mkBlock(assignStms))
625 :     end
626 :    
627 :     (* generate a global structure type definition from the list of globals *)
628 :     fun genGlobalStruct (_, [], _) = CL.D_Comment(["No Global Definition"])
629 :     | genGlobalStruct (targetTy, globals, tyName) = let
630 :     val globs = List.map (fn (x : mirror_var) => (targetTy x, #var x)) globals
631 :     in
632 : jhr 1766 CL.D_StructDef(NONE, globs, SOME tyName)
633 : jhr 1671 end
634 :    
635 :     (* generate a global structure type definition from the image data of the image globals *)
636 :     fun genImageDataStruct ([], _) = CL.D_Comment(["No Image Data Ptrs Definition"])
637 :     | genImageDataStruct (imgGlobals, tyName) = let
638 :     val globs = List.map
639 :     (fn (x, _) => (globalPtr CL.voidTy, RN.imageDataName x))
640 :     imgGlobals
641 :     in
642 : jhr 1766 CL.D_StructDef(NONE, globs, SOME tyName)
643 : jhr 1671 end
644 :    
645 :     fun genGlobals (declFn, targetTy, globals) = let
646 :     fun doVar (x : mirror_var) = declFn (CL.D_Var([], targetTy x, #var x, NONE))
647 :     in
648 :     List.app doVar globals
649 :     end
650 :    
651 :     fun genOutputFun(Strand{name, output,tyName, state, code,...}) = let
652 :     (* the output function *)
653 :     val outFnName = concat[name, "_Output"]
654 :     val outFun = let
655 :     val params = [
656 :     CL.PARAM([], CL.T_Ptr CL.voidTy, "outS"),
657 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
658 :     ]
659 :     (* the type and access expression for the strand's output variable *)
660 :     val (outTy, outState) = (#1 output, CL.mkIndirect(CL.mkVar "self", #2 output))
661 :     val outState = CL.mkUnOp(CL.%&, outState)
662 :     in
663 :     CL.D_Func(["static"], CL.voidTy, outFnName, params,
664 :     CL.mkCall("memcpy", [CL.mkVar "outS", outState, CL.mkSizeof(shadowTy outTy)] ))
665 :     end
666 :     in
667 :     outFun
668 :     end
669 :    
670 :     fun genStrandDesc (outFn,Strand{name, output,tyName, state, code,...}) = let
671 :     (* the output function *)
672 :     val outFnName = concat[name, "_Output"]
673 :     (* the strand's descriptor object *)
674 :     val descI = let
675 :     fun fnPtr (ty, f) = CL.I_Exp(CL.mkCast(CL.T_Named ty, CL.mkVar f))
676 :     val (outTy, _) = output
677 :     in
678 :     CL.I_Struct[
679 :     ("name", CL.I_Exp(CL.mkStr name)),
680 :     ("stateSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandTy name)))),
681 :     ("shadowStrandSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandShadowTy (RN.strandTy name))))),
682 :     (* FIXME: we may need to add a shadowOutputSzb field too for OpenCL *)
683 :     ("outputSzb", CL.I_Exp(CL.mkSizeof(shadowTy outTy))),
684 :     ("nrrdType", CL.I_Exp(CL.mkInt (NrrdTypes.toNrrdType outTy))),
685 :     ("nrrdSzb", CL.I_Exp(CL.mkInt (NrrdTypes.toNrrdSize outTy))),
686 :     ("update", fnPtr("update_method_t", "0")),
687 :     ("strandCopy", fnPtr("convert_method_t", RN.strandConvertName name)),
688 :     ("print", fnPtr("print_method_t", RN.strandPrintName name)),
689 :     ("output", fnPtr("output_method_t", outFnName)) (* FIXME *)
690 :     ]
691 :     end
692 :     val desc = CL.D_Var([], CL.T_Named N.strandDescTy, N.strandDesc name, SOME descI)
693 :     in
694 :     desc
695 :     end
696 :    
697 :     (* generate the table of strand descriptors *)
698 :     fun genStrandTable (declFn, strands) = let
699 :     val nStrands = length strands
700 :     fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.mkVar(N.strandDesc name)))
701 :     fun genInits (_, []) = []
702 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
703 :     in
704 :     declFn (CL.D_Var([], CL.int32, N.numStrands,
705 :     SOME(CL.I_Exp(CL.mkIntTy(IntInf.fromInt nStrands, CL.int32)))));
706 :     declFn (CL.D_Var([],
707 :     CL.T_Array(CL.T_Ptr(CL.T_Named N.strandDescTy), SOME nStrands),
708 :     N.strands,
709 :     SOME(CL.I_Array(genInits (0, strands)))))
710 :     end
711 :    
712 :     fun genSrc (baseName, prog) = let
713 :     val Prog{
714 :     name, double, globals, topDecls, strands, initially,
715 :     imgGlobals, numDims,outFn, ...
716 :     } = prog
717 :     val clFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "cl"}
718 :     val cFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
719 :     val clOutS = TextIO.openOut clFileName
720 :     val cOutS = TextIO.openOut cFileName
721 :     val clppStrm = PrintAsCL.new clOutS
722 :     val cppStrm = PrintAsC.new cOutS
723 :     val progName = name
724 :     fun cppDecl dcl = PrintAsC.output(cppStrm, dcl)
725 :     fun clppDecl dcl = PrintAsCL.output(clppStrm, dcl)
726 :     val strands = AtomTable.listItems strands
727 :     val [strand as Strand{name, tyName, code, init_code, ...}] = strands
728 :     in
729 :     (* Generate the OpenCL file *)
730 :     (* Retrieve the header information *)
731 :     clppDecl (CL.verbatim [HF.text] [
732 :     ("OUTFILE", clFileName),
733 :     ("SRCFILE", OS.Path.joinBaseExt{base=baseName, ext=SOME "diderot"}),
734 :     ("PRECISION", if double then "DOUBLE" else "SINGLE")
735 :     ]);
736 :     (* if there are no globals, then define a dummy type *)
737 :     if List.null(!globals)
738 :     then clppDecl (CL.D_Verbatim["typedef void ", RN.globalsTy, ";\n"])
739 :     else ();
740 :     (* if there are no images, then define a dummy type *)
741 :     if List.null(!imgGlobals)
742 :     then clppDecl (CL.D_Verbatim["typedef void * ", RN.imageDataType, ";\n"])
743 :     else ();
744 :     (* Retrieve the scheduler kernels and functions *)
745 :     clppDecl (CL.D_Verbatim[SF.text]);
746 :     clppDecl (CL.D_Verbatim[CLEigen2x2Frag.text]);
747 :     clppDecl (CL.D_Verbatim[CLEigen3x3Frag.text]);
748 :     clppDecl (genGlobalStruct (#gpuTy, !globals, RN.globalsTy));
749 :     clppDecl (genImageDataStruct(!imgGlobals, RN.imageDataType));
750 :     clppDecl (genStrandTyDef(#gpuTy, strand, tyName));
751 :     List.app clppDecl (!code);
752 :     clppDecl (genStrandCopy strand);
753 :     clppDecl (genUpdateMethod(strand, globals, imgGlobals));
754 :     (* Generate the Host C file *)
755 :     cppDecl (CL.D_Verbatim[
756 :     if double
757 :     then "#define DIDEROT_DOUBLE_PRECISION\n"
758 :     else "#define DIDEROT_SINGLE_PRECISION\n",
759 :     "#define DIDEROT_INT\n",
760 :     "#define DIDEROT_TARGET_CL\n",
761 :     "#include \"Diderot/diderot.h\"\n"
762 :     ]);
763 :     cppDecl (CL.D_Verbatim[
764 :     (case !globals
765 :     of [] => concat["typedef void ", RN.globalsTy,";\n"]
766 :     | _ => ""
767 :     (*end of case*))
768 :     ]);
769 :     cppDecl (CL.D_Var(["static"], CL.charPtr, "ProgramName",
770 :     SOME(CL.I_Exp(CL.mkStr progName))));
771 :     cppDecl (genGlobalStruct (#hostTy, !globals, RN.globalsTy));
772 :     cppDecl (genGlobalStruct (#shadowTy, !globals, RN.shadowGlobalsTy));
773 :     (* FIXME: does this really need to be a global? *)
774 :     cppDecl (CL.D_Var(["static"], globPtrTy, RN.globalsVarName, NONE));
775 :     cppDecl (genStrandTyDef (#hostTy, strand, tyName));
776 :     cppDecl (genStrandTyDef (#shadowTy, strand, RN.strandShadowTy tyName));
777 :     cppDecl (genConvertShadowTypes strand);
778 :     cppDecl (!init_code);
779 :     cppDecl (genStrandPrint strand);
780 :     cppDecl (genOutputFun strand);
781 :     List.app cppDecl (List.rev (!topDecls));
782 :     cppDecl (genGlobalBuffersArgs (!globals,imgGlobals));
783 :     List.app (fn strand => cppDecl (genStrandDesc (outFn,strand))) strands;
784 :     genStrandTable (cppDecl, strands);
785 :     cppDecl (!initially);
786 :     PrintAsC.close cppStrm;
787 :     PrintAsCL.close clppStrm;
788 :     TextIO.closeOut cOutS;
789 :     TextIO.closeOut clOutS
790 :     end
791 :    
792 :     (* output the code to the filesystem. The string is the basename of the source file *)
793 :     fun generate (basename, prog as Prog{double, parallel, debug, ...}) = let
794 :     fun condCons (true, x, xs) = x::xs
795 :     | condCons (false, _, xs) = xs
796 :     (* generate the C compiler flags *)
797 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
798 : jhr 1840 val cflags = condCons (#cl Paths.cflags <> "", #cl Paths.cflags, cflags)
799 : jhr 1671 val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
800 :     val cflags = if debug
801 :     then #debug Paths.cflags :: cflags
802 :     else #ndebug Paths.cflags :: cflags
803 :     val cflags = #base Paths.cflags :: cflags
804 :     (* generate the loader flags *)
805 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
806 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
807 :     val extraLibs = #cl Paths.extraLibs :: extraLibs
808 :     val rtLib = TargetUtil.runtimeName {
809 :     target = TargetUtil.TARGET_CL,
810 :     parallel = parallel, double = double, debug = debug
811 :     }
812 :     val ldOpts = rtLib :: extraLibs
813 :     in
814 :     genSrc (basename, prog);
815 :     RunCC.compile (basename, cflags);
816 :     RunCC.link (basename, ldOpts)
817 :     end
818 :    
819 :     end (* Program *)
820 :    
821 :     (* strands *)
822 :     structure Strand =
823 :     struct
824 : lamonts 1989
825 : jhr 1671 fun define (Prog{strands, ...}, strandId, state) = let
826 :     val name = Atom.toString strandId
827 :     (* the output state variable *)
828 :     val outputVar = (case List.filter IL.StateVar.isOutput state
829 :     of [] => raise Fail("no output specified for strand " ^ name)
830 :     | [x] => (IL.StateVar.ty x, IL.StateVar.name x)
831 :     | _ => raise Fail("multiple outputs in " ^ name)
832 :     (* end case *))
833 :     (* the state variables *)
834 :     val state = let
835 :     fun cvt x = Var.mirror (IL.StateVar.ty x, IL.StateVar.name x, STRAND_SHADOW)
836 :     in
837 :     List.map cvt state
838 :     end
839 :     val strand = Strand{
840 :     name = name,
841 :     tyName = RN.strandTy name,
842 :     state = state,
843 :     output = outputVar,
844 :     code = ref [],
845 :     init_code = ref (CL.D_Comment(["no init code"]))
846 :     }
847 :     in
848 :     AtomTable.insert strands (strandId, strand);
849 :     strand
850 :     end
851 :    
852 :     (* return the strand with the given name *)
853 :     fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
854 :    
855 :     (* register the strand-state initialization code. The variables are the strand
856 :     * parameters.
857 :     *)
858 :     fun init (Strand{name, tyName, code, init_code, ...}, params, init) = let
859 :     val fName = RN.strandInit name
860 :     val params =
861 : jhr 1907 (* FIXME: the params should not have CL types, since this code is generated to the C file! *)
862 : jhr 1671 clParam ("",CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
863 :     List.map (fn (ToCL.V(ty, x)) => CL.PARAM([], ty, x)) params
864 :     val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
865 :     in
866 :     init_code := initFn
867 :     end
868 :    
869 :     (* register a strand method *)
870 :     fun method (Strand{name, tyName, code,...}, methName, body) = let
871 :     val params = [
872 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfIn"),
873 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfOut"),
874 :     globalParam (CL.T_Ptr(CL.T_Named (RN.globalsTy)), RN.globalsVarName),
875 :     CL.PARAM([],CL.T_Named(RN.imageDataType),RN.globalImageDataName)
876 :     ]
877 :     val (fName,resTy) = (case methName
878 :     of StrandUtil.Update => (RN.strandUpdate,CL.T_Named "StrandStatus_t")
879 : lamonts 1989 | StrandUtil.Stabilize => (RN.strandStabilize, CL.voidTy)
880 : jhr 1671 (* end case *))
881 :     val methFn = CL.D_Func([], resTy, fName, params, body)
882 :     in
883 :     code := methFn :: !code
884 :     end
885 :    
886 :     end
887 :    
888 :     end
889 :    
890 :     structure CLBackEnd = CodeGenFn(CLTarget)

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