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

SCM Repository

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

Annotation of /branches/vis12/src/compiler/cl-target/cl-target.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1685 - (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 :     | _ => ToCL.trFragment (vMap, blk)
218 :     (* end case *))
219 :     in
220 :     (ENV{info=info, vMap=vMap, scope=scope}, stms)
221 :     end
222 :     fun block (ENV{vMap, scope, ...}, blk) = (case scope
223 :     of StrandScope => ToC.trBlock (vMap, blk)
224 :     | MethodScope name => ToCL.trBlock (vMap, blk)
225 :     | InitiallyScope => ToCL.trBlock (vMap, blk)
226 :     | _ => ToC.trBlock (vMap, blk)
227 :     (* end case *))
228 :     fun exp (ENV{vMap, ...}, e) = ToCL.trExp(vMap, e)
229 :     end
230 :    
231 :     (* variables *)
232 :     structure Var =
233 :     struct
234 :     fun mirror (ty, name, shadowEnv) = {
235 :     hostTy = ToC.trType ty,
236 :     shadowTy = shadowTy ty,
237 :     gpuTy = ToCL.trType ty,
238 :     hToS = case shadowEnv
239 :     of GLOBAL_SHADOW => convertToShadow (ty, name)
240 :     | STRAND_SHADOW => convertStrandToShadow(ty, name, "selfIn", "selfOut")
241 :     (* end case *),
242 :     var = name
243 :     }
244 :     fun name (ToCL.V(_, name)) = name
245 :     fun global (Prog{globals, imgGlobals, ...}, name, ty) = let
246 :     val x = mirror (ty, name, GLOBAL_SHADOW)
247 :     fun isImgGlobal (Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}), name) =
248 :     imgGlobals := (name,dim) :: !imgGlobals
249 :     | isImgGlobal _ = ()
250 :     in
251 :     globals := x :: !globals;
252 :     isImgGlobal (ty, name);
253 :     ToCL.V(#gpuTy x, name)
254 :     end
255 :     fun param x = ToCL.V(ToCL.trType(V.ty x), V.name x)
256 :     end
257 :    
258 :     (* environments *)
259 :     structure Env =
260 :     struct
261 :     (* create a new environment *)
262 :     fun new prog = ENV{
263 :     info=INFO{prog = prog},
264 :     vMap = V.Map.empty,
265 :     scope = NoScope
266 :     }
267 :     (* define the current translation context *)
268 :     fun setScope scope (ENV{info, vMap, ...}) = ENV{info=info, vMap=vMap, scope=scope}
269 :     val scopeGlobal = setScope GlobalScope
270 :     val scopeInitially = setScope InitiallyScope
271 :     fun scopeStrand env = setScope StrandScope env
272 :     fun scopeMethod (env, name) = setScope (MethodScope name) env
273 :     (* bind a TreeIL varaiable to a target variable *)
274 :     fun bind (ENV{info, vMap, scope}, x, x') = ENV{
275 :     info = info,
276 :     vMap = V.Map.insert(vMap, x, x'),
277 :     scope = scope
278 :     }
279 :     end
280 :    
281 :     (* programs *)
282 :     structure Program =
283 :     struct
284 :     fun new {name, double, parallel, debug} = (
285 :     RN.initTargetSpec double;
286 :     CNames.initTargetSpec {double=double, long=false};
287 :     Prog{
288 :     name = name,
289 :     double = double, parallel = parallel, debug = debug,
290 :     globals = ref [],
291 :     topDecls = ref [],
292 :     strands = AtomTable.mkTable (16, Fail "strand table"),
293 :     initially = ref(CL.D_Comment["missing initially"]),
294 :     numDims = ref 0,
295 :     imgGlobals = ref[],
296 :     prFn = ref(CL.D_Comment(["No Print Function"])),
297 :     outFn = ref(CL.D_Comment(["No Output Function"]))
298 :     })
299 :    
300 :     (* register the code that is used to register command-line options for input variables *)
301 :     fun inputs (Prog{topDecls, ...}, stm) = let
302 :     val inputsFn = CL.D_Func(
303 :     [], CL.voidTy, RN.registerOpts,
304 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.optionsTy), "opts")],
305 :     stm)
306 :     in
307 :     topDecls := inputsFn :: !topDecls
308 :     end
309 :    
310 :     (* register the global initialization part of a program *)
311 :     fun init (Prog{topDecls, ...}, init) = let
312 :     val globalsDecl = CL.mkAssign(CL.mkVar RN.globalsVarName,
313 :     CL.mkApply("malloc", [CL.mkSizeof(CL.T_Named RN.globalsTy)]))
314 :     val initFn = CL.D_Func(
315 :     [], CL.voidTy, RN.initGlobals, [],
316 :     CL.mkBlock[
317 :     globalsDecl,
318 :     CL.mkCall(RN.initGlobalsHelper, [CL.mkVar RN.globalsVarName])
319 :     ])
320 :     val initHelperFn = CL.D_Func(
321 :     [], CL.voidTy, RN.initGlobalsHelper,
322 :     [CL.PARAM([], globPtrTy, RN.globalsVarName)],
323 :     init)
324 :     val shutdownFn = CL.D_Func(
325 :     [], CL.voidTy, RN.shutdown,
326 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.worldTy), "wrld")],
327 :     CL.S_Block[])
328 :     in
329 :     topDecls := shutdownFn :: initFn :: initHelperFn :: !topDecls
330 :     end
331 :    
332 :     (* create and register the initially function for a program *)
333 :     fun initially {
334 :     prog = Prog{name=progName, strands, initially,numDims, ...},
335 :     isArray : bool,
336 :     iterPrefix : stm list,
337 :     iters : (var * exp * exp) list,
338 :     createPrefix : stm list,
339 :     strand : Atom.atom,
340 :     args : exp list
341 :     } = let
342 :     val name = Atom.toString strand
343 :     val nDims = List.length iters
344 :     val worldTy = CL.T_Ptr(CL.T_Named N.worldTy)
345 :     fun mapi f xs = let
346 :     fun mapf (_, []) = []
347 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
348 :     in
349 :     mapf (0, xs)
350 :     end
351 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
352 :     val sizeInit = mapi
353 :     (fn (i, (CL.V(ty, _), lo, hi)) =>
354 :     (i, CL.I_Exp(CL.mkBinOp(hi, CL.#-, lo) #+# CL.mkIntTy(1, ty)))
355 :     ) iters
356 :     (* code to allocate the world and initial strands *)
357 :     val wrld = "wrld"
358 :     val allocCode = [
359 :     CL.mkComment["allocate initial block of strands"],
360 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
361 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
362 :     CL.mkDecl(worldTy, wrld,
363 :     SOME(CL.I_Exp(CL.mkApply(N.allocInitially, [
364 :     CL.mkVar "ProgramName",
365 :     CL.mkUnOp(CL.%&, CL.mkVar(N.strandDesc name)),
366 :     CL.mkBool isArray,
367 :     CL.mkIntTy(IntInf.fromInt nDims, CL.int32),
368 :     CL.mkVar "base",
369 :     CL.mkVar "size"
370 :     ]))))
371 :     ]
372 :     (* create the loop nest for the initially iterations *)
373 :     val indexVar = "ix"
374 :     val strandTy = CL.T_Ptr(CL.T_Named(N.strandTy name))
375 :     fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
376 :     CL.mkDecl(strandTy, "sp",
377 :     SOME(CL.I_Exp(
378 :     CL.mkCast(strandTy,
379 :     CL.mkApply(N.inState, [CL.mkVar "wrld", CL.mkVar indexVar]))))),
380 :     CL.mkCall(N.strandInit name, CL.mkVar "sp" :: args),
381 :     CL.mkAssign(CL.mkVar indexVar, CL.mkVar indexVar #+# CL.mkIntTy(1, CL.uint32))
382 :     ])
383 :     | mkLoopNest ((CL.V(ty, param), lo, hi)::iters) = let
384 :     val body = mkLoopNest iters
385 :     in
386 :     CL.mkFor(
387 :     [(ty, param, lo)],
388 :     CL.mkBinOp(CL.mkVar param, CL.#<=, hi),
389 :     [CL.mkPostOp(CL.mkVar param, CL.^++)],
390 :     body)
391 :     end
392 :     val iterCode = [
393 :     CL.mkComment["initially"],
394 :     CL.mkDecl(CL.uint32, indexVar, SOME(CL.I_Exp(CL.mkIntTy(0, CL.uint32)))),
395 :     mkLoopNest iters
396 :     ]
397 :     val body = CL.mkBlock(
398 :     iterPrefix @
399 :     allocCode @
400 :     iterCode @
401 :     [CL.mkReturn(SOME(CL.mkVar "wrld"))])
402 :     val initFn = CL.D_Func([], worldTy, N.initially, [], body)
403 :     in
404 :     numDims := nDims;
405 :     initially := initFn
406 :     end
407 :    
408 :    
409 :     (***** OUTPUT *****)
410 :    
411 :     fun genStrandPrint (Strand{name, tyName, state, output, code, ...}) = let
412 :     (* the print function *)
413 :     val prFnName = concat[name, "Print"]
414 :     val prFn = let
415 :     val params = [
416 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
417 :     CL.PARAM([], CL.T_Ptr(CL.T_Named(RN.strandShadowTy tyName)), "self")
418 :     ]
419 :     val (ty, x) = output
420 :     val outState = CL.mkIndirect(CL.mkVar "self", x)
421 :     val prArgs = (case ty
422 :     of Ty.IntTy => [CL.mkStr(!N.gIntFormat ^ "\n"), outState]
423 :     | Ty.SeqTy(Ty.IntTy, d) => let
424 :     fun sel i = CL.mkApply(
425 :     "VSUB",
426 :     [outState, CL.mkInt(IntInf.fromInt i)])
427 :     val fmt = CL.mkStr(
428 :     String.concatWith " " (List.tabulate(d, fn _ => !N.gIntFormat))
429 :     ^ "\n")
430 :     val args = List.tabulate (d, sel)
431 :     in
432 :     fmt :: args
433 :     end
434 :     | Ty.TensorTy[] => [CL.mkStr "%f\n", outState]
435 :     | Ty.TensorTy[d] => let
436 :     fun sel i = CL.mkApply(
437 :     "VSUB",
438 :     [outState, CL.mkInt(IntInf.fromInt i)])
439 :     val fmt = CL.mkStr(
440 :     String.concatWith " " (List.tabulate(d, fn _ => "%f"))
441 :     ^ "\n")
442 :     val args = List.tabulate (d, sel)
443 :     in
444 :     fmt :: args
445 :     end
446 :     | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
447 :     (* end case *))
448 :     in
449 :     CL.D_Func(["static"], CL.voidTy, prFnName, params,
450 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs))
451 :     end
452 :     in
453 :     prFn
454 :     end
455 :    
456 :     fun genStrandTyDef(targetTy,Strand{state,...},tyName) =
457 :     (case state
458 :     of [] => CL.D_Comment(["No Strand Defintiion Included"])
459 :     | _ => CL.D_StructDef(revmap (fn x => (targetTy x, #var x)) state,
460 :     tyName)
461 :     (* end case *))
462 :    
463 :    
464 :    
465 :     (* generates the globals buffers and arguments function *)
466 :     fun genConvertShadowTypes (Strand{name, tyName, state,...}) = let
467 :     (* Delcare opencl setup objects *)
468 :     val errVar = "err"
469 :     val params = [
470 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut"),
471 :     CL.PARAM([], CL.T_Ptr(CL.T_Named(RN.strandShadowTy tyName)), "selfIn")
472 :     ]
473 :     val body = List.map (fn (x:mirror_var) => #hToS x) state
474 :     in
475 :     CL.D_Func([], CL.voidTy, RN.strandConvertName name, params, CL.mkBlock body)
476 :     end
477 :    
478 :     (* generates the opencl buffers for the image data *)
479 :     fun getGlobalDataBuffers (globals, imgGlobals, contextVar, errVar) = let
480 :     val globalBuffErr = "error creating OpenCL global buffer\n"
481 :     fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.mkVar errVar, CL.#!=, CL.mkVar "CL_SUCCESS"),
482 :     CL.mkBlock([CL.mkCall("fprintf",[CL.mkVar "stderr", CL.mkStr msg]),
483 :     CL.mkCall("exit",[CL.mkInt 1])]))
484 :     val shadowTypeDecl =
485 :     CL.mkDecl(CL.T_Named(RN.shadowGlobalsTy), RN.shadowGlaobalsName, NONE)
486 :     val globalToShadowStms = List.map (fn (x:mirror_var) => #hToS x) globals
487 :     val globalBufferDecl = CL.mkDecl(clMemoryTy,concat[RN.globalsVarName,"_cl"],NONE)
488 :     val globalBuffer = CL.mkAssign(CL.mkVar(concat[RN.globalsVarName,"_cl"]),
489 :     CL.mkApply("clCreateBuffer", [
490 :     CL.mkVar contextVar,
491 :     CL.mkBinOp(CL.mkVar "CL_MEM_READ_ONLY", CL.#|, CL.mkVar "CL_MEM_COPY_HOST_PTR"),
492 :     CL.mkSizeof(CL.T_Named RN.shadowGlobalsTy),
493 :     CL.mkUnOp(CL.%&,CL.mkVar RN.shadowGlaobalsName),
494 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
495 :     ]))
496 :     fun genDataBuffers ([],_,_,_) = []
497 :     | genDataBuffers ((var,nDims)::globals, contextVar, errVar,errFn) = let
498 :     val hostVar = CL.mkIndirect(CL.mkVar RN.globalsVarName, var)
499 :     val size = CL.mkIndirect(hostVar, "dataSzb")
500 :     in
501 :     CL.mkDecl(clMemoryTy, RN.addBufferSuffixData var ,NONE) ::
502 :     CL.mkAssign(CL.mkVar(RN.addBufferSuffixData var),
503 :     CL.mkApply("clCreateBuffer", [
504 :     CL.mkVar contextVar,
505 :     CL.mkVar "CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR",
506 :     size,
507 :     CL.mkIndirect(hostVar, "data"),
508 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
509 :     ])) ::
510 :     errFn(concat["error in creating ",RN.addBufferSuffixData var, " global buffer\n"]) ::
511 :     genDataBuffers(globals,contextVar,errVar,errFn)
512 :     end
513 :     in
514 :     [shadowTypeDecl] @ globalToShadowStms
515 :     @ [globalBufferDecl, globalBuffer,errorFn(globalBuffErr)]
516 :     @ genDataBuffers(imgGlobals,contextVar,errVar,errorFn)
517 :     end
518 :    
519 :     (* generates the kernel arguments for the image data *)
520 :     fun genGlobalArguments (globals, count, kernelVar, errVar) = let
521 :     val globalArgErr = "error creating OpenCL global argument\n"
522 :     fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.mkVar errVar, CL.#!=, CL.mkVar "CL_SUCCESS"),
523 :     CL.mkBlock([CL.mkCall("fprintf",[CL.mkVar "stderr", CL.mkStr msg]),
524 :     CL.mkCall("exit",[CL.mkInt 1])]))
525 :     val globalArgument = CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.&=,
526 :     CL.mkApply("clSetKernelArg",
527 :     [CL.mkVar kernelVar,
528 :     CL.mkPostOp(CL.mkVar count, CL.^++),
529 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
530 :     CL.mkUnOp(CL.%&,CL.mkVar(concat[RN.globalsVarName,"_cl"]))])))
531 :     fun genDataArguments ([],_,_,_,_) = []
532 :     | genDataArguments ((var,nDims)::globals,count,kernelVar,errVar,errFn) =
533 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.$=,
534 :     CL.mkApply("clSetKernelArg",
535 :     [CL.mkVar kernelVar,
536 :     CL.mkPostOp(CL.mkVar count, CL.^++),
537 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
538 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffixData var))]))) ::
539 :     errFn(concat["error in creating ",RN.addBufferSuffixData var, " argument\n"]) ::
540 :     genDataArguments (globals,count,kernelVar,errVar,errFn)
541 :     in
542 :     globalArgument :: errorFn globalArgErr ::
543 :     genDataArguments(globals, count, kernelVar, errVar,errorFn)
544 :     end
545 :    
546 :     (* generates the globals buffers and arguments function *)
547 :     fun genGlobalBuffersArgs (globals,imgGlobals) = let
548 :     (* Delcare opencl setup objects *)
549 :     val errVar = "err"
550 :     val params = [
551 :     CL.PARAM([],CL.T_Named("cl_context"), "context"),
552 :     CL.PARAM([],CL.T_Named("cl_kernel"), "kernel"),
553 :     CL.PARAM([],CL.T_Named("cl_command_queue"), "cmdQ"),
554 :     CL.PARAM([],CL.T_Named("int"), "argStart")
555 :     ]
556 :     val body = (case globals
557 :     of [] => [CL.mkReturn(NONE)]
558 :     | _ => let
559 :     val clGlobalBuffers =
560 :     getGlobalDataBuffers(globals, !imgGlobals, "context", errVar)
561 :     val clGlobalArguments =
562 :     genGlobalArguments(!imgGlobals, "argStart", "kernel", errVar)
563 :     in
564 :     (* Body: put all the statments together *)
565 :     CL.mkDecl(clIntTy, errVar, SOME(CL.I_Exp(CL.mkInt 0)))
566 :     :: clGlobalBuffers @ clGlobalArguments
567 :     end
568 :     (*end of case*))
569 :     in
570 :     CL.D_Func([],CL.voidTy,RN.globalsSetupName,params,CL.mkBlock(body))
571 :     end
572 :    
573 :     (* generate the global image meta-data and data parameters *)
574 :     fun genKeneralGlobalParams ((name,tyname)::[],line) =
575 :     concat[line, "__global void *", RN.addBufferSuffixData name]
576 :     | genKeneralGlobalParams ([],line) = line
577 :     | genKeneralGlobalParams ((name,tyname)::rest, line) =
578 :     genKeneralGlobalParams(rest, concat[line, "__global void *", RN.addBufferSuffixData name, ",\n"])
579 :    
580 :     fun genUpdateMethod (Strand{name, tyName, state,...}, globals, imgGlobals) = let
581 :     val imageDataStms = List.map
582 :     (fn (x,_) => concat[
583 :     RN.globalImageDataName, ".", RN.imageDataName x, " = ",
584 :     RN.addBufferSuffixData x, ";","\n"
585 :     ])
586 :     (!imgGlobals)
587 :     fun select ([], a, _) = a
588 :     | select (_, _, b) = b
589 :     val placeHolders = [
590 :     (RN.place_holders, tyName),
591 :     (RN.p_addDatPtr, select (!imgGlobals, "", ",")),
592 :     (RN.p_addGlobals, select (!globals, "", ",")),
593 :     (RN.p_globals, select (!globals, "", "__global Diderot_Globals_t *diderotGlobals")),
594 :     (RN.p_globalVar, select (!globals, "0", RN.globalsVarName)),
595 :     (RN.p_dataVar, select (!globals, "0", RN.globalImageDataName)),
596 :     (RN.p_dataPtr, genKeneralGlobalParams (!imgGlobals, "")),
597 :     (RN.p_dataAssign, select (!imgGlobals, "",
598 :     String.concat("Diderot_data_ptr_t diderotDataPtrs;\n" :: imageDataStms)))
599 :     ]
600 :     in
601 :     CL.verbatim [CLUpdateFrag.text] placeHolders
602 :     end
603 :    
604 :     fun genStrandCopy(Strand{tyName,name,state,...}) = let
605 :     val params = [
606 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
607 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfOut")
608 :     ]
609 :     val assignStms = List.rev(
610 :     List.map
611 :     (fn x => CL.mkAssign(lvalueSV(#var x), rvalueSV(#var x)))
612 :     state)
613 :     in
614 :     CL.D_Func([""], CL.voidTy, RN.strandCopy, params,CL.mkBlock(assignStms))
615 :     end
616 :    
617 :     (* generate a global structure type definition from the list of globals *)
618 :     fun genGlobalStruct (_, [], _) = CL.D_Comment(["No Global Definition"])
619 :     | genGlobalStruct (targetTy, globals, tyName) = let
620 :     val globs = List.map (fn (x : mirror_var) => (targetTy x, #var x)) globals
621 :     in
622 :     CL.D_StructDef(globs, tyName)
623 :     end
624 :    
625 :     (* generate a global structure type definition from the image data of the image globals *)
626 :     fun genImageDataStruct ([], _) = CL.D_Comment(["No Image Data Ptrs Definition"])
627 :     | genImageDataStruct (imgGlobals, tyName) = let
628 :     val globs = List.map
629 :     (fn (x, _) => (globalPtr CL.voidTy, RN.imageDataName x))
630 :     imgGlobals
631 :     in
632 :     CL.D_StructDef(globs, tyName)
633 :     end
634 :    
635 :     fun genGlobals (declFn, targetTy, globals) = let
636 :     fun doVar (x : mirror_var) = declFn (CL.D_Var([], targetTy x, #var x, NONE))
637 :     in
638 :     List.app doVar globals
639 :     end
640 :    
641 :     fun genOutputFun(Strand{name, output,tyName, state, code,...}) = let
642 :     (* the output function *)
643 :     val outFnName = concat[name, "_Output"]
644 :     val outFun = let
645 :     val params = [
646 :     CL.PARAM([], CL.T_Ptr CL.voidTy, "outS"),
647 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
648 :     ]
649 :     (* the type and access expression for the strand's output variable *)
650 :     val (outTy, outState) = (#1 output, CL.mkIndirect(CL.mkVar "self", #2 output))
651 :     val outState = CL.mkUnOp(CL.%&, outState)
652 :     in
653 :     CL.D_Func(["static"], CL.voidTy, outFnName, params,
654 :     CL.mkCall("memcpy", [CL.mkVar "outS", outState, CL.mkSizeof(shadowTy outTy)] ))
655 :     end
656 :     in
657 :     outFun
658 :     end
659 :    
660 :     fun genStrandDesc (outFn,Strand{name, output,tyName, state, code,...}) = let
661 :     (* the output function *)
662 :     val outFnName = concat[name, "_Output"]
663 :     (* the strand's descriptor object *)
664 :     val descI = let
665 :     fun fnPtr (ty, f) = CL.I_Exp(CL.mkCast(CL.T_Named ty, CL.mkVar f))
666 :     val (outTy, _) = output
667 :     in
668 :     CL.I_Struct[
669 :     ("name", CL.I_Exp(CL.mkStr name)),
670 :     ("stateSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandTy name)))),
671 :     ("shadowStrandSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandShadowTy (RN.strandTy name))))),
672 :     (* FIXME: we may need to add a shadowOutputSzb field too for OpenCL *)
673 :     ("outputSzb", CL.I_Exp(CL.mkSizeof(shadowTy outTy))),
674 :     ("nrrdType", CL.I_Exp(CL.mkInt (NrrdTypes.toNrrdType outTy))),
675 :     ("nrrdSzb", CL.I_Exp(CL.mkInt (NrrdTypes.toNrrdSize outTy))),
676 :     ("update", fnPtr("update_method_t", "0")),
677 :     ("strandCopy", fnPtr("convert_method_t", RN.strandConvertName name)),
678 :     ("print", fnPtr("print_method_t", RN.strandPrintName name)),
679 :     ("output", fnPtr("output_method_t", outFnName)) (* FIXME *)
680 :     ]
681 :     end
682 :     val desc = CL.D_Var([], CL.T_Named N.strandDescTy, N.strandDesc name, SOME descI)
683 :     in
684 :     desc
685 :     end
686 :    
687 :     (* generate the table of strand descriptors *)
688 :     fun genStrandTable (declFn, strands) = let
689 :     val nStrands = length strands
690 :     fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.mkVar(N.strandDesc name)))
691 :     fun genInits (_, []) = []
692 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
693 :     in
694 :     declFn (CL.D_Var([], CL.int32, N.numStrands,
695 :     SOME(CL.I_Exp(CL.mkIntTy(IntInf.fromInt nStrands, CL.int32)))));
696 :     declFn (CL.D_Var([],
697 :     CL.T_Array(CL.T_Ptr(CL.T_Named N.strandDescTy), SOME nStrands),
698 :     N.strands,
699 :     SOME(CL.I_Array(genInits (0, strands)))))
700 :     end
701 :    
702 :     fun genSrc (baseName, prog) = let
703 :     val Prog{
704 :     name, double, globals, topDecls, strands, initially,
705 :     imgGlobals, numDims,outFn, ...
706 :     } = prog
707 :     val clFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "cl"}
708 :     val cFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
709 :     val clOutS = TextIO.openOut clFileName
710 :     val cOutS = TextIO.openOut cFileName
711 :     val clppStrm = PrintAsCL.new clOutS
712 :     val cppStrm = PrintAsC.new cOutS
713 :     val progName = name
714 :     fun cppDecl dcl = PrintAsC.output(cppStrm, dcl)
715 :     fun clppDecl dcl = PrintAsCL.output(clppStrm, dcl)
716 :     val strands = AtomTable.listItems strands
717 :     val [strand as Strand{name, tyName, code, init_code, ...}] = strands
718 :     in
719 :     (* Generate the OpenCL file *)
720 :     (* Retrieve the header information *)
721 :     clppDecl (CL.verbatim [HF.text] [
722 :     ("OUTFILE", clFileName),
723 :     ("SRCFILE", OS.Path.joinBaseExt{base=baseName, ext=SOME "diderot"}),
724 :     ("PRECISION", if double then "DOUBLE" else "SINGLE")
725 :     ]);
726 :     (* if there are no globals, then define a dummy type *)
727 :     if List.null(!globals)
728 :     then clppDecl (CL.D_Verbatim["typedef void ", RN.globalsTy, ";\n"])
729 :     else ();
730 :     (* if there are no images, then define a dummy type *)
731 :     if List.null(!imgGlobals)
732 :     then clppDecl (CL.D_Verbatim["typedef void * ", RN.imageDataType, ";\n"])
733 :     else ();
734 :     (* Retrieve the scheduler kernels and functions *)
735 :     clppDecl (CL.D_Verbatim[SF.text]);
736 :     clppDecl (CL.D_Verbatim[CLEigen2x2Frag.text]);
737 :     clppDecl (CL.D_Verbatim[CLEigen3x3Frag.text]);
738 :     clppDecl (genGlobalStruct (#gpuTy, !globals, RN.globalsTy));
739 :     clppDecl (genImageDataStruct(!imgGlobals, RN.imageDataType));
740 :     clppDecl (genStrandTyDef(#gpuTy, strand, tyName));
741 :     List.app clppDecl (!code);
742 :     clppDecl (genStrandCopy strand);
743 :     clppDecl (genUpdateMethod(strand, globals, imgGlobals));
744 :     (* Generate the Host C file *)
745 :     cppDecl (CL.D_Verbatim[
746 :     if double
747 :     then "#define DIDEROT_DOUBLE_PRECISION\n"
748 :     else "#define DIDEROT_SINGLE_PRECISION\n",
749 :     "#define DIDEROT_INT\n",
750 :     "#define DIDEROT_TARGET_CL\n",
751 :     "#include \"Diderot/diderot.h\"\n"
752 :     ]);
753 :     cppDecl (CL.D_Verbatim[
754 :     (case !globals
755 :     of [] => concat["typedef void ", RN.globalsTy,";\n"]
756 :     | _ => ""
757 :     (*end of case*))
758 :     ]);
759 :     cppDecl (CL.D_Var(["static"], CL.charPtr, "ProgramName",
760 :     SOME(CL.I_Exp(CL.mkStr progName))));
761 :     cppDecl (genGlobalStruct (#hostTy, !globals, RN.globalsTy));
762 :     cppDecl (genGlobalStruct (#shadowTy, !globals, RN.shadowGlobalsTy));
763 :     (* FIXME: does this really need to be a global? *)
764 :     cppDecl (CL.D_Var(["static"], globPtrTy, RN.globalsVarName, NONE));
765 :     cppDecl (genStrandTyDef (#hostTy, strand, tyName));
766 :     cppDecl (genStrandTyDef (#shadowTy, strand, RN.strandShadowTy tyName));
767 :     cppDecl (genConvertShadowTypes strand);
768 :     cppDecl (!init_code);
769 :     cppDecl (genStrandPrint strand);
770 :     cppDecl (genOutputFun strand);
771 :     List.app cppDecl (List.rev (!topDecls));
772 :     cppDecl (genGlobalBuffersArgs (!globals,imgGlobals));
773 :     List.app (fn strand => cppDecl (genStrandDesc (outFn,strand))) strands;
774 :     genStrandTable (cppDecl, strands);
775 :     cppDecl (!initially);
776 :     PrintAsC.close cppStrm;
777 :     PrintAsCL.close clppStrm;
778 :     TextIO.closeOut cOutS;
779 :     TextIO.closeOut clOutS
780 :     end
781 :    
782 :     (* output the code to the filesystem. The string is the basename of the source file *)
783 :     fun generate (basename, prog as Prog{double, parallel, debug, ...}) = let
784 :     fun condCons (true, x, xs) = x::xs
785 :     | condCons (false, _, xs) = xs
786 :     (* generate the C compiler flags *)
787 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
788 :     val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
789 :     val cflags = if debug
790 :     then #debug Paths.cflags :: cflags
791 :     else #ndebug Paths.cflags :: cflags
792 :     val cflags = #base Paths.cflags :: cflags
793 :     (* generate the loader flags *)
794 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
795 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
796 :     val extraLibs = #cl Paths.extraLibs :: extraLibs
797 :     val rtLib = TargetUtil.runtimeName {
798 :     target = TargetUtil.TARGET_CL,
799 :     parallel = parallel, double = double, debug = debug
800 :     }
801 :     val ldOpts = rtLib :: extraLibs
802 :     in
803 :     genSrc (basename, prog);
804 :     RunCC.compile (basename, cflags);
805 :     RunCC.link (basename, ldOpts)
806 :     end
807 :    
808 :     end (* Program *)
809 :    
810 :     (* strands *)
811 :     structure Strand =
812 :     struct
813 :    
814 :     fun define (Prog{strands, ...}, strandId, state) = let
815 :     val name = Atom.toString strandId
816 :     (* the output state variable *)
817 :     val outputVar = (case List.filter IL.StateVar.isOutput state
818 :     of [] => raise Fail("no output specified for strand " ^ name)
819 :     | [x] => (IL.StateVar.ty x, IL.StateVar.name x)
820 :     | _ => raise Fail("multiple outputs in " ^ name)
821 :     (* end case *))
822 :     (* the state variables *)
823 :     val state = let
824 :     fun cvt x = Var.mirror (IL.StateVar.ty x, IL.StateVar.name x, STRAND_SHADOW)
825 :     in
826 :     List.map cvt state
827 :     end
828 :     val strand = Strand{
829 :     name = name,
830 :     tyName = RN.strandTy name,
831 :     state = state,
832 :     output = outputVar,
833 :     code = ref [],
834 :     init_code = ref (CL.D_Comment(["no init code"]))
835 :     }
836 :     in
837 :     AtomTable.insert strands (strandId, strand);
838 :     strand
839 :     end
840 :    
841 :     (* return the strand with the given name *)
842 :     fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
843 :    
844 :     (* register the strand-state initialization code. The variables are the strand
845 :     * parameters.
846 :     *)
847 :     fun init (Strand{name, tyName, code, init_code, ...}, params, init) = let
848 :     val fName = RN.strandInit name
849 :     val params =
850 :     clParam ("",CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
851 :     List.map (fn (ToCL.V(ty, x)) => CL.PARAM([], ty, x)) params
852 :     val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
853 :     in
854 :     init_code := initFn
855 :     end
856 :    
857 :     (* register a strand method *)
858 :     fun method (Strand{name, tyName, code,...}, methName, body) = let
859 :     val params = [
860 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfIn"),
861 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfOut"),
862 :     globalParam (CL.T_Ptr(CL.T_Named (RN.globalsTy)), RN.globalsVarName),
863 :     CL.PARAM([],CL.T_Named(RN.imageDataType),RN.globalImageDataName)
864 :     ]
865 :     val (fName,resTy) = (case methName
866 :     of StrandUtil.Update => (RN.strandUpdate,CL.T_Named "StrandStatus_t")
867 :     | StrandUtil.Stabilize => (name ^ StrandUtil.nameToString methName, CL.voidTy)
868 :     (* end case *))
869 :     val methFn = CL.D_Func([], resTy, fName, params, body)
870 :     in
871 :     code := methFn :: !code
872 :     end
873 :    
874 :     end
875 :    
876 :     end
877 :    
878 :     structure CLBackEnd = CodeGenFn(CLTarget)

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