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

SCM Repository

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

Annotation of /branches/pure-cfg/src/compiler/cl-target/cl-target.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1313 - (view) (download)

1 : lamonts 1244 (* c-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 : jhr 1273 structure ToCL = TreeToCL
16 : lamonts 1305 structure N = CNames
17 : lamonts 1244
18 : lamonts 1305 (* variable translation *)
19 :     structure TrVar =
20 :     struct
21 :     type env = CL.typed_var TreeIL.Var.Map.map
22 :     fun lookup (env, x) = (case V.Map.find (env, x)
23 :     of SOME(CL.V(_, x')) => x'
24 :     | NONE => raise Fail(concat["lookup(_, ", V.name x, ")"])
25 :     (* end case *))
26 :     (* translate a variable that occurs in an l-value context (i.e., as the target of an assignment) *)
27 :     fun lvalueVar (env, x) = (case V.kind x
28 :     of IL.VK_Global => CL.mkVar(lookup(env, x))
29 :     | IL.VK_State strand => CL.mkIndirect(CL.mkVar "selfOut", lookup(env, x))
30 :     | IL.VK_Local => CL.mkVar(lookup(env, x))
31 :     (* end case *))
32 :     (* translate a variable that occurs in an r-value context *)
33 :     fun rvalueVar (env, x) = (case V.kind x
34 :     of IL.VK_Global => CL.mkVar(lookup(env, x))
35 :     | IL.VK_State strand => CL.mkIndirect(CL.mkVar "selfIn", lookup(env, x))
36 :     | IL.VK_Local => CL.mkVar(lookup(env, x))
37 :     (* end case *))
38 : jhr 1307 end
39 : lamonts 1305
40 : jhr 1307 structure ToC = TreeToCFn (TrVar)
41 : lamonts 1305
42 : jhr 1285 (* C variable translation *)
43 :     structure TrCVar =
44 :     struct
45 :     type env = CL.typed_var TreeIL.Var.Map.map
46 :     fun lookup (env, x) = (case V.Map.find (env, x)
47 :     of SOME(CL.V(_, x')) => x'
48 :     | NONE => raise Fail(concat["TrCVar.lookup(_, ", V.name x, ")"])
49 :     (* end case *))
50 :     (* translate a variable that occurs in an l-value context (i.e., as the target of an assignment) *)
51 :     fun lvalueVar (env, x) = (case V.kind x
52 : jhr 1286 of IL.VK_Global => CL.mkIndirect(CL.mkVar RN.globalsVarName, lookup(env, x))
53 : jhr 1285 | IL.VK_State strand => raise Fail "unexpected strand context"
54 :     | IL.VK_Local => CL.mkVar(lookup(env, x))
55 :     (* end case *))
56 :     (* translate a variable that occurs in an r-value context *)
57 :     val rvalueVar = lvalueVar
58 :     end
59 :    
60 :     structure ToC = TreeToCFn (TrCVar)
61 :    
62 :     type var = CL.typed_var
63 : lamonts 1244 type exp = CL.exp
64 :     type stm = CL.stm
65 :    
66 : jhr 1313 (* OpenCL specific types *)
67 :     val clIntTy = CL.T_Named "cl_int"
68 : jhr 1279 val clProgramTy = CL.T_Named "cl_program"
69 :     val clKernelTy = CL.T_Named "cl_kernel"
70 :     val clCmdQueueTy = CL.T_Named "cl_command_queue"
71 :     val clContextTy = CL.T_Named "cl_context"
72 :     val clDeviceIdTy = CL.T_Named "cl_device_id"
73 :     val clPlatformIdTy = CL.T_Named "cl_platform_id"
74 :     val clMemoryTy = CL.T_Named "cl_mem"
75 : jhr 1313 val globPtrTy = CL.T_Ptr(CL.T_Named RN.globalsTy)
76 : jhr 1279
77 : jhr 1307 (* variable or field that is mirrored between host and GPU *)
78 :     type mirror_var = {
79 :     hostTy : CL.ty, (* variable type on Host (i.e., C type) *)
80 :     gpuTy : CL.ty, (* variable's type on GPU (i.e., OpenCL type) *)
81 :     var : CL.var (* variable name *)
82 :     }
83 :    
84 : lamonts 1244 datatype strand = Strand of {
85 : jhr 1261 name : string,
86 :     tyName : string,
87 : jhr 1307 state : mirror_var list ref,
88 : jhr 1261 output : (Ty.ty * CL.var) option ref, (* the strand's output variable (only one for now) *)
89 : lamonts 1271 code : CL.decl list ref,
90 : jhr 1273 init_code: CL.decl ref
91 : lamonts 1244 }
92 :    
93 :     datatype program = Prog of {
94 : jhr 1307 name : string, (* stem of source file *)
95 : jhr 1261 double : bool, (* true for double-precision support *)
96 :     parallel : bool, (* true for multithreaded (or multi-GPU) target *)
97 :     debug : bool, (* true for debug support in executable *)
98 : jhr 1307 globals : mirror_var list ref,
99 : jhr 1261 topDecls : CL.decl list ref,
100 :     strands : strand AtomTable.hash_table,
101 : lamonts 1305 initially : CL.decl ref,
102 : jhr 1273 numDims: int ref,
103 :     imgGlobals: (string * int) list ref,
104 :     prFn: CL.decl ref
105 :     }
106 : lamonts 1244
107 :     datatype env = ENV of {
108 : jhr 1261 info : env_info,
109 :     vMap : var V.Map.map,
110 :     scope : scope
111 : lamonts 1244 }
112 :    
113 :     and env_info = INFO of {
114 : jhr 1261 prog : program
115 : lamonts 1244 }
116 :    
117 :     and scope
118 :     = NoScope
119 :     | GlobalScope
120 :     | InitiallyScope
121 : jhr 1261 | StrandScope of TreeIL.var list (* strand initialization *)
122 :     | MethodScope of TreeIL.var list (* method body; vars are state variables *)
123 : lamonts 1244
124 : jhr 1273 (* the supprted widths of vectors of reals on the target. *)
125 :     (* FIXME: for OpenCL 1.1, 3 is also valid *)
126 :     fun vectorWidths () = [2, 4, 8, 16]
127 : lamonts 1244
128 :     (* tests for whether various expression forms can appear inline *)
129 : jhr 1261 fun inlineCons n = (n < 2) (* vectors are inline, but not matrices *)
130 :     val inlineMatrixExp = false (* can matrix-valued expressions appear inline? *)
131 : lamonts 1244
132 :     (* TreeIL to target translations *)
133 :     structure Tr =
134 :     struct
135 : jhr 1261 fun fragment (ENV{info, vMap, scope}, blk) = let
136 : jhr 1308 val (vMap, stms) = (case scope
137 :     of GlobalScope => ToC.trFragment (vMap, blk)
138 :     | _ => ToCL.trFragment (vMap, blk)
139 :     (* end case *))
140 : jhr 1261 in
141 :     (ENV{info=info, vMap=vMap, scope=scope}, stms)
142 :     end
143 :     fun saveState cxt stateVars (env, args, stm) = (
144 :     ListPair.foldrEq
145 : jhr 1273 (fn (x, e, stms) => ToCL.trAssign(env, x, e)@stms)
146 : jhr 1261 [stm]
147 :     (stateVars, args)
148 :     ) handle ListPair.UnequalLengths => (
149 :     print(concat["saveState ", cxt, ": length mismatch; ", Int.toString(List.length args), " args\n"]);
150 :     raise Fail(concat["saveState ", cxt, ": length mismatch"]))
151 :     fun block (ENV{vMap, scope, ...}, blk) = (case scope
152 : jhr 1313 (* NOTE: if we move strand initialization to the GPU, then we'll have to change the following line! *)
153 :     of StrandScope stateVars => ToC.trBlock (vMap, saveState "StrandScope" stateVars, blk)
154 : jhr 1273 | MethodScope stateVars => ToCL.trBlock (vMap, saveState "MethodScope" stateVars, blk)
155 : jhr 1286 | InitiallyScope => ToCL.trBlock (vMap, fn (_, _, stm) => [stm], blk)
156 :     | _ => ToC.trBlock (vMap, fn (_, _, stm) => [stm], blk)
157 : jhr 1261 (* end case *))
158 : jhr 1273 fun exp (ENV{vMap, ...}, e) = ToCL.trExp(vMap, e)
159 : lamonts 1244 end
160 :    
161 :     (* variables *)
162 :     structure Var =
163 :     struct
164 : jhr 1273 fun name (ToCL.V(_, name)) = name
165 : jhr 1307 fun global (Prog{globals, imgGlobals, ...}, name, ty) = let
166 :     val x = {hostTy = ToC.trType ty, gpuTy = ToCL.trType ty, var = name}
167 :     fun isImgGlobal (Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}), name) =
168 :     imgGlobals := (name,dim) :: !imgGlobals
169 :     | isImgGlobal _ = ()
170 : jhr 1261 in
171 : jhr 1307 globals := x :: !globals;
172 :     isImgGlobal (ty, name);
173 :     ToCL.V(#gpuTy x, name)
174 : jhr 1261 end
175 : jhr 1273 fun param x = ToCL.V(ToCL.trType(V.ty x), V.name x)
176 : jhr 1261 fun state (Strand{state, ...}, x) = let
177 : jhr 1307 val ty = V.ty x
178 :     val x' = {hostTy = ToC.trType ty, gpuTy = ToCL.trType ty, var = V.name x}
179 : jhr 1261 in
180 :     state := x' :: !state;
181 : jhr 1307 ToCL.V(#gpuTy x', #var x')
182 : jhr 1261 end
183 : lamonts 1244 end
184 :    
185 :     (* environments *)
186 :     structure Env =
187 :     struct
188 :     (* create a new environment *)
189 : jhr 1261 fun new prog = ENV{
190 :     info=INFO{prog = prog},
191 :     vMap = V.Map.empty,
192 :     scope = NoScope
193 :     }
194 : lamonts 1244 (* define the current translation context *)
195 : jhr 1261 fun setScope scope (ENV{info, vMap, ...}) = ENV{info=info, vMap=vMap, scope=scope}
196 :     val scopeGlobal = setScope GlobalScope
197 :     val scopeInitially = setScope InitiallyScope
198 :     fun scopeStrand (env, svars) = setScope (StrandScope svars) env
199 :     fun scopeMethod (env, svars) = setScope (MethodScope svars) env
200 : lamonts 1244 (* bind a TreeIL varaiable to a target variable *)
201 : jhr 1261 fun bind (ENV{info, vMap, scope}, x, x') = ENV{
202 :     info = info,
203 :     vMap = V.Map.insert(vMap, x, x'),
204 :     scope = scope
205 :     }
206 : lamonts 1244 end
207 :    
208 :     (* programs *)
209 :     structure Program =
210 :     struct
211 : jhr 1278 fun new {name, double, parallel, debug} = (
212 : jhr 1261 RN.initTargetSpec double;
213 : jhr 1286 CNames.initTargetSpec double;
214 : jhr 1261 Prog{
215 : jhr 1307 name = name,
216 : jhr 1261 double = double, parallel = parallel, debug = debug,
217 : lamonts 1271 globals = ref [],
218 : jhr 1261 topDecls = ref [],
219 :     strands = AtomTable.mkTable (16, Fail "strand table"),
220 : jhr 1307 initially = ref(CL.D_Comment["missing initially"]),
221 :     numDims = ref(0),
222 :     imgGlobals = ref[],
223 :     prFn = ref(CL.D_Comment(["No Print Function"]))
224 : jhr 1261 })
225 : lamonts 1244 (* register the global initialization part of a program *)
226 : jhr 1308 (* FIXME: unused code; can this be removed??
227 : jhr 1307 fun globalIndirects (globals,stms) = let
228 : lamonts 1305 fun getGlobals ({name,target as TargetUtil.TARGET_CL}::rest) =
229 : jhr 1307 CL.mkAssign(CL.mkIndirect(CL.mkVar RN.globalsVarName,name),CL.mkVar name)
230 :     ::getGlobals rest
231 : jhr 1281 | getGlobals [] = []
232 :     | getGlobals (_::rest) = getGlobals rest
233 : jhr 1273 in
234 : jhr 1281 stms @ getGlobals globals
235 : jhr 1273 end
236 : jhr 1308 *)
237 : jhr 1261 (* register the code that is used to register command-line options for input variables *)
238 :     fun inputs (Prog{topDecls, ...}, stm) = let
239 :     val inputsFn = CL.D_Func(
240 :     [], CL.voidTy, RN.registerOpts,
241 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.optionsTy), "opts")],
242 :     stm)
243 :     in
244 :     topDecls := inputsFn :: !topDecls
245 :     end
246 :    
247 : jhr 1286 (* register the global initialization part of a program *)
248 : jhr 1307 fun init (Prog{topDecls, ...}, init) = let
249 :     val initFn = CL.D_Func(
250 : jhr 1286 [], CL.voidTy, RN.initGlobals, [CL.PARAM([], globPtrTy, RN.globalsVarName)],
251 :     init)
252 : jhr 1307 val shutdownFn = CL.D_Func(
253 :     [], CL.voidTy, RN.shutdown,
254 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.worldTy), "wrld")],
255 :     CL.S_Block[])
256 :     in
257 :     topDecls := shutdownFn :: initFn :: !topDecls
258 :     end
259 : lamonts 1305 (* create and register the initially function for a program *)
260 : jhr 1307 fun initially {
261 :     prog = Prog{name=progName, strands, initially, ...},
262 :     isArray : bool,
263 :     iterPrefix : stm list,
264 :     iters : (var * exp * exp) list,
265 :     createPrefix : stm list,
266 :     strand : Atom.atom,
267 :     args : exp list
268 :     } = let
269 :     val name = Atom.toString strand
270 :     val nDims = List.length iters
271 :     val worldTy = CL.T_Ptr(CL.T_Named N.worldTy)
272 :     fun mapi f xs = let
273 :     fun mapf (_, []) = []
274 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
275 :     in
276 :     mapf (0, xs)
277 :     end
278 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
279 :     val sizeInit = mapi
280 :     (fn (i, (CL.V(ty, _), lo, hi)) =>
281 :     (i, CL.I_Exp(CL.mkBinOp(CL.mkBinOp(hi, CL.#-, lo), CL.#+, CL.E_Int(1, ty))))
282 :     ) iters
283 :     (* code to allocate the world and initial strands *)
284 :     val wrld = "wrld"
285 :     val allocCode = [
286 :     CL.mkComment["allocate initial block of strands"],
287 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
288 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
289 :     CL.mkDecl(worldTy, wrld,
290 :     SOME(CL.I_Exp(CL.E_Apply(N.allocInitially, [
291 :     CL.mkVar "ProgramName",
292 :     CL.mkUnOp(CL.%&, CL.E_Var(N.strandDesc name)),
293 :     CL.E_Bool isArray,
294 :     CL.E_Int(IntInf.fromInt nDims, CL.int32),
295 :     CL.E_Var "base",
296 :     CL.E_Var "size"
297 :     ]))))
298 :     ]
299 :     (* create the loop nest for the initially iterations *)
300 :     val indexVar = "ix"
301 :     val strandTy = CL.T_Ptr(CL.T_Named(N.strandTy name))
302 :     fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
303 :     CL.mkDecl(strandTy, "sp",
304 :     SOME(CL.I_Exp(
305 :     CL.E_Cast(strandTy,
306 :     CL.E_Apply(N.inState, [CL.E_Var "wrld", CL.E_Var indexVar]))))),
307 :     CL.mkCall(N.strandInit name, CL.E_Var "sp" :: args),
308 :     CL.mkAssign(CL.E_Var indexVar, CL.mkBinOp(CL.E_Var indexVar, CL.#+, CL.E_Int(1, CL.uint32)))
309 :     ])
310 :     | mkLoopNest ((CL.V(ty, param), lo, hi)::iters) = let
311 :     val body = mkLoopNest iters
312 :     in
313 :     CL.mkFor(
314 :     [(ty, param, lo)],
315 :     CL.mkBinOp(CL.E_Var param, CL.#<=, hi),
316 :     [CL.mkPostOp(CL.E_Var param, CL.^++)],
317 :     body)
318 :     end
319 :     val iterCode = [
320 :     CL.mkComment["initially"],
321 :     CL.mkDecl(CL.uint32, indexVar, SOME(CL.I_Exp(CL.E_Int(0, CL.uint32)))),
322 :     mkLoopNest iters
323 :     ]
324 :     val body = CL.mkBlock(
325 :     iterPrefix @
326 :     allocCode @
327 :     iterCode @
328 :     [CL.mkReturn(SOME(CL.E_Var "wrld"))])
329 :     val initFn = CL.D_Func([], worldTy, N.initially, [], body)
330 :     in
331 :     initially := initFn
332 :     end
333 : jhr 1281
334 : lamonts 1305 (***** OUTPUT *****)
335 : jhr 1307 fun genStrandPrint (Strand{name, tyName, state, output, code,...}) = let
336 : jhr 1308 (* the print function *)
337 : jhr 1307 val prFnName = concat[name, "_print"]
338 :     val prFn = let
339 : jhr 1308 val params = [
340 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
341 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
342 :     ]
343 :     val SOME(ty, x) = !output
344 :     val outState = CL.mkIndirect(CL.mkVar "self", x)
345 :     val prArgs = (case ty
346 :     of Ty.IVecTy 1 => [CL.E_Str(!N.gIntFormat ^ "\n"), outState]
347 :     | Ty.IVecTy d => let
348 :     val fmt = CL.E_Str(
349 :     String.concatWith " " (List.tabulate(d, fn _ => !N.gIntFormat))
350 :     ^ "\n")
351 :     val args = List.tabulate (d, fn i => ToC.ivecIndex(outState, d, i))
352 :     in
353 :     fmt :: args
354 :     end
355 :     | Ty.TensorTy[] => [CL.E_Str "%f\n", outState]
356 :     | Ty.TensorTy[d] => let
357 :     val fmt = CL.E_Str(
358 :     String.concatWith " " (List.tabulate(d, fn _ => "%f"))
359 :     ^ "\n")
360 :     val args = List.tabulate (d, fn i => ToC.vecIndex(outState, d, i))
361 :     in
362 :     fmt :: args
363 :     end
364 :     | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
365 :     (* end case *))
366 :     in
367 :     CL.D_Func(["static"], CL.voidTy, prFnName, params,
368 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs))
369 :     end
370 : jhr 1307 in
371 : jhr 1308 prFn
372 : jhr 1307 end
373 : lamonts 1305
374 : jhr 1307 fun genStrandTyDef (targetTy, Strand{tyName, state,...}) =
375 : jhr 1261 (* the type declaration for the strand's state struct *)
376 :     CL.D_StructDef(
377 : jhr 1307 List.rev (List.map (fn x => (targetTy x, #var x)) (!state)),
378 :     tyName)
379 : lamonts 1305
380 : jhr 1308 (* generates the load kernel function *)
381 : jhr 1307
382 :     (* generates the opencl buffers for the image data *)
383 :     fun getGlobalDataBuffers(globals,contextVar,errVar) = let
384 :     val globalBufferDecl = CL.mkDecl(clMemoryTy,concat[RN.globalsVarName,"_cl"],NONE)
385 :     val globalBuffer = CL.mkAssign(CL.mkVar(concat[RN.globalsVarName,"_cl"]),
386 :     CL.mkApply("clCreateBuffer", [
387 :     CL.mkVar contextVar,
388 :     CL.mkVar "CL_MEM_COPY_HOST_PTR",
389 :     CL.mkApply("sizeof",[CL.mkVar RN.globalsTy]),
390 :     CL.mkVar RN.globalsVarName,
391 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
392 :     ]))
393 : jhr 1308 fun genDataBuffers([],_,_) = []
394 :     | genDataBuffers((var,nDims)::globals,contextVar,errVar) = let
395 : jhr 1313 (* FIXME: use CL constructors to build expressions (not strings) *)
396 : jhr 1308 val size = if nDims = 1
397 :     then CL.mkBinOp(CL.mkApply("sizeof",[CL.mkVar "float"]), CL.#*,
398 :     CL.mkIndirect(CL.mkVar var, "size[0]"))
399 :     else if nDims = 2
400 :     then CL.mkBinOp(CL.mkApply("sizeof",[CL.mkVar "float"]), CL.#*,
401 :     CL.mkIndirect(CL.mkVar var, concat["size[0]", " * ", var, "->size[1]"]))
402 :     else CL.mkBinOp(CL.mkApply("sizeof",[CL.mkVar "float"]), CL.#*,
403 :     CL.mkIndirect(CL.mkVar var,concat["size[0]", " * ", var, "->size[1] * ", var, "->size[2]"]))
404 :     in
405 :     CL.mkDecl(clMemoryTy, RN.addBufferSuffix var ,NONE)::
406 :     CL.mkDecl(clMemoryTy, RN.addBufferSuffixData var ,NONE)::
407 :     CL.mkAssign(CL.mkVar(RN.addBufferSuffix var), CL.mkApply("clCreateBuffer",
408 :     [CL.mkVar contextVar,
409 :     CL.mkVar "CL_MEM_COPY_HOST_PTR",
410 :     CL.mkApply("sizeof",[CL.mkVar (RN.imageTy nDims)]),
411 :     CL.mkVar var,
412 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)])) ::
413 :     CL.mkAssign(CL.mkVar(RN.addBufferSuffixData var), CL.mkApply("clCreateBuffer",
414 :     [CL.mkVar contextVar,
415 :     CL.mkVar "CL_MEM_COPY_HOST_PTR",
416 :     size,
417 :     CL.mkIndirect(CL.mkVar var,"data"),
418 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)])):: genDataBuffers(globals,contextVar,errVar)
419 :     end
420 : jhr 1307 in
421 : jhr 1308 globalBufferDecl :: globalBuffer :: genDataBuffers(globals,contextVar,errVar)
422 : jhr 1307 end
423 : lamonts 1264
424 : jhr 1309 (* generates the kernel arguments for the image data *)
425 : jhr 1313 fun genGlobalArguments (globals, count, kernelVar, errVar) = let
426 :     val globalArgument = CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.|=,
427 :     CL.mkApply("clSetKernelArg",
428 :     [CL.mkVar kernelVar,
429 :     CL.mkPostOp(CL.E_Var count, CL.^++),
430 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
431 :     CL.mkUnOp(CL.%&,CL.mkVar(concat[RN.globalsVarName,"_cl"]))])))
432 :     fun genDataArguments ([],_,_,_) = []
433 :     | genDataArguments ((var,nDims)::globals,count,kernelVar,errVar) =
434 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.|=,
435 :     CL.mkApply("clSetKernelArg",
436 :     [CL.mkVar kernelVar,
437 :     CL.mkPostOp(CL.E_Var count, CL.^++),
438 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
439 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffix var))]))) ::
440 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.|=,
441 :     CL.mkApply("clSetKernelArg",
442 :     [CL.mkVar kernelVar,
443 :     CL.mkPostOp(CL.E_Var count, CL.^++),
444 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
445 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffixData var))]))) ::
446 :     genDataArguments (globals,count,kernelVar,errVar)
447 :     in
448 :     globalArgument :: genDataArguments(globals, count, kernelVar, errVar)
449 :     end
450 : lamonts 1264
451 : lamonts 1305 (* generates the globals buffers and arguments function *)
452 : jhr 1307 fun genGlobalBuffersArgs (imgGlobals) = let
453 : jhr 1273 (* Delcare opencl setup objects *)
454 :     val errVar = "err"
455 :     val imgDataSizeVar = "image_dataSize"
456 :     val params = [
457 : lamonts 1305 CL.PARAM([],CL.T_Named("cl_context"), "context"),
458 : jhr 1307 CL.PARAM([],CL.T_Named("cl_kernel"), "kernel"),
459 :     CL.PARAM([],CL.T_Named("int"), "argStart")
460 : jhr 1273 ]
461 : jhr 1313 val clGlobalBuffers = getGlobalDataBuffers(!imgGlobals, "context", errVar)
462 :     val clGlobalArguments = genGlobalArguments(!imgGlobals, "argStart", "kernel", errVar)
463 : jhr 1307 (* Body put all the statments together *)
464 : jhr 1313 val body = CL.mkDecl(clIntTy, errVar, SOME(CL.I_Exp(CL.mkInt(0, CL.intTy))))
465 :     :: clGlobalBuffers @ clGlobalArguments
466 :     in
467 :     (* FIXME: we ought to check the error condition! *)
468 : jhr 1307 CL.D_Func([],CL.voidTy,RN.globalsSetupName,params,CL.mkBlock(body))
469 :     end
470 : lamonts 1305
471 : jhr 1307 (* generate the data and global parameters *)
472 :     fun genKeneralGlobalParams ((name,tyname)::rest) =
473 :     CL.PARAM([], CL.T_Ptr(CL.T_Named RN.globalsTy), concat[RN.globalsVarName]) ::
474 :     CL.PARAM([], CL.T_Ptr(CL.T_Named (RN.imageTy tyname)),RN.addBufferSuffix name) ::
475 :     CL.PARAM([], CL.T_Ptr(CL.voidTy),RN.addBufferSuffixData name) ::
476 :     genKeneralGlobalParams rest
477 :     | genKeneralGlobalParams [] = []
478 :    
479 :     (*generate code for intilizing kernel global data *)
480 :     fun initKernelGlobals (globals, imgGlobals) = let
481 :     (* FIXME: should use List.map here *)
482 :     fun initGlobalStruct ({hostTy, gpuTy, var}::rest) =
483 :     CL.mkAssign(CL.mkVar var, CL.mkIndirect(CL.mkVar RN.globalsVarName, var)) ::
484 :     initGlobalStruct rest
485 :     | initGlobalStruct [] = []
486 :     fun initGlobalImages ((name, tyname)::rest) =
487 :     CL.mkAssign(CL.mkVar name, CL.mkVar (RN.addBufferSuffix name)) ::
488 :     CL.mkAssign(CL.mkIndirect(CL.mkVar name,"data"),CL.mkVar (RN.addBufferSuffixData name)) ::
489 :     initGlobalImages rest
490 :     | initGlobalImages [] = []
491 :     in
492 :     initGlobalStruct globals @ initGlobalImages(imgGlobals)
493 :     end
494 :    
495 :     (* generate the main kernel function for the .cl file *)
496 :     fun genKernelFun (strand, nDims, globals, imgGlobals) = let
497 :     val Strand{name, tyName, state, output, code,...} = strand
498 :     val fName = RN.kernelFuncName;
499 :     val inState = "strand_in"
500 :     val outState = "strand_out"
501 :     val params = [
502 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
503 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfOut"),
504 :     CL.PARAM(["__global"], CL.intTy, "width")
505 :     ] @ genKeneralGlobalParams(!imgGlobals)
506 :     val thread_ids = if nDims = 1
507 :     then [
508 :     CL.mkDecl(CL.intTy, "x", SOME(CL.I_Exp(CL.mkInt(0, CL.intTy)))),
509 :     CL.mkAssign(CL.mkVar "x",CL.mkApply(RN.getGlobalThreadId,[CL.mkInt(0,CL.intTy)]))
510 :     ]
511 :     else [
512 :     CL.mkDecl(CL.intTy, "x", SOME(CL.I_Exp(CL.mkInt(0, CL.intTy)))),
513 :     CL.mkDecl(CL.intTy, "y", SOME(CL.I_Exp(CL.mkInt(0, CL.intTy)))),
514 :     CL.mkAssign(CL.mkVar "x", CL.mkApply(RN.getGlobalThreadId,[CL.mkInt(0,CL.intTy)])),
515 :     CL.mkAssign(CL.mkVar "y",CL.mkApply(RN.getGlobalThreadId,[CL.mkInt(1,CL.intTy)]))
516 :     ]
517 :     val strandDecl = [
518 :     CL.mkDecl(CL.T_Named tyName, inState, NONE),
519 :     CL.mkDecl(CL.T_Named tyName, outState,NONE)]
520 : jhr 1309 val strandObjects = if nDims = 1
521 :     then [
522 :     CL.mkAssign( CL.mkVar inState, CL.mkSubscript(CL.mkVar "selfIn", CL.mkStr "x")),
523 :     CL.mkAssign(CL.mkVar outState,CL.mkSubscript(CL.mkVar "selfOut", CL.mkStr "x"))
524 :     ]
525 :     else let
526 :     val index = CL.mkBinOp(CL.mkBinOp(CL.mkVar "x",CL.#*,CL.mkVar "width"),CL.#+,CL.mkVar "y")
527 :     in [
528 :     CL.mkAssign(CL.mkVar inState, CL.mkSubscript(CL.mkVar "selfIn",index)),
529 :     CL.mkAssign(CL.mkVar outState,CL.mkSubscript(CL.mkVar "selfOut",index))
530 :     ] end
531 : jhr 1307 val status = CL.mkDecl(CL.intTy, "status", SOME(CL.I_Exp(CL.mkInt(0, CL.intTy))))
532 : jhr 1309 val local_vars = thread_ids @ initKernelGlobals(!globals,!imgGlobals) @ strandDecl @ strandObjects @ [status]
533 :     val while_exp = CL.mkBinOp(
534 :     CL.mkBinOp(CL.mkVar "status",CL.#!=, CL.mkVar RN.kStabilize),
535 :     CL.#||,
536 :     CL.mkBinOp(CL.mkVar "status", CL.#!=, CL.mkVar RN.kDie))
537 : jhr 1307 val whileBody = CL.mkBlock [
538 :     CL.mkAssign(CL.mkVar "status",
539 :     CL.mkApply(RN.strandUpdate name,
540 :     [CL.mkUnOp(CL.%&,CL.mkVar inState), CL.mkUnOp(CL.%&,CL.mkVar outState)])),
541 :     CL.mkCall(RN.strandStabilize name,
542 :     [CL.mkUnOp(CL.%&,CL.mkVar inState), CL.mkUnOp(CL.%&,CL.mkVar outState)])
543 :     ]
544 :     val whileBlock = [CL.mkWhile(while_exp, whileBody)]
545 :     val body = CL.mkBlock(local_vars @ whileBlock)
546 :     in
547 :     CL.D_Func(["__kernel"], CL.voidTy, fName, params, body)
548 :     end
549 :     (* generate a global structure from the globals *)
550 :     fun genGlobalStruct (targetTy, globals) = let
551 :     val globs = List.map (fn (x : mirror_var) => (targetTy x, #var x)) globals
552 :     in
553 :     CL.D_StructDef(globs, RN.globalsTy)
554 :     end
555 :     fun genGlobals (declFn, targetTy, globals) = let
556 :     fun doVar (x : mirror_var) = declFn (CL.D_Var([], targetTy x, #var x, NONE))
557 :     in
558 :     List.app doVar globals
559 :     end
560 : lamonts 1264
561 : jhr 1308 fun genSrc (baseName, prog) = let
562 :     val Prog{double, globals, topDecls, strands, initially, imgGlobals, numDims, ...} = prog
563 : jhr 1307 val clFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "cl"}
564 :     val cFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
565 :     val clOutS = TextIO.openOut clFileName
566 :     val cOutS = TextIO.openOut cFileName
567 :     val clppStrm = PrintAsCL.new clOutS
568 :     val cppStrm = PrintAsC.new cOutS
569 :     fun cppDecl dcl = PrintAsC.output(cppStrm, dcl)
570 :     fun clppDecl dcl = PrintAsCL.output(clppStrm, dcl)
571 :     val strands = AtomTable.listItems strands
572 :     val [strand as Strand{name, tyName, code, init_code, ...}] = strands
573 :     in
574 : jhr 1273 (* Generate the OpenCl file *)
575 :     clppDecl (CL.D_Verbatim([
576 :     if double
577 :     then "#define DIDEROT_DOUBLE_PRECISION"
578 :     else "#define DIDEROT_SINGLE_PRECISION",
579 :     "#define DIDEROT_TARGET_CL",
580 : lamonts 1305 "#include \"Diderot/cl-diderot.h\""
581 : jhr 1273 ]));
582 : jhr 1307 genGlobals (clppDecl, #gpuTy, !globals);
583 :     clppDecl (genGlobalStruct (#gpuTy, !globals));
584 :     clppDecl (genStrandTyDef(#gpuTy, strand));
585 : jhr 1273 List.app clppDecl (!code);
586 : jhr 1307 clppDecl (genKernelFun (strand, !numDims, globals, imgGlobals));
587 :     (* Generate the Host C file *)
588 : jhr 1273 cppDecl (CL.D_Verbatim([
589 :     if double
590 :     then "#define DIDEROT_DOUBLE_PRECISION"
591 :     else "#define DIDEROT_SINGLE_PRECISION",
592 :     "#define DIDEROT_TARGET_CL",
593 :     "#include \"Diderot/diderot.h\""
594 :     ]));
595 : jhr 1307 genGlobals (cppDecl, #hostTy, !globals);
596 :     cppDecl (genGlobalStruct (#hostTy, !globals));
597 : jhr 1308 cppDecl (genStrandTyDef (#hostTy, strand));
598 : jhr 1307 cppDecl (!init_code);
599 :     cppDecl (genStrandPrint strand);
600 : jhr 1273 List.app cppDecl (List.rev (!topDecls));
601 : jhr 1307 cppDecl (genGlobalBuffersArgs (imgGlobals));
602 :     cppDecl (!initially);
603 :     PrintAsC.close cppStrm;
604 :     PrintAsCL.close clppStrm;
605 :     TextIO.closeOut cOutS;
606 :     TextIO.closeOut clOutS
607 :     end
608 : lamonts 1264
609 : lamonts 1244 (* output the code to a file. The string is the basename of the file, the extension
610 :     * is provided by the target.
611 :     *)
612 : jhr 1307 fun generate (basename, prog as Prog{double, parallel, debug, ...}) = let
613 :     fun condCons (true, x, xs) = x::xs
614 :     | condCons (false, _, xs) = xs
615 :     (* generate the C compiler flags *)
616 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
617 :     val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
618 :     val cflags = if debug
619 :     then #debug Paths.cflags :: cflags
620 :     else #ndebug Paths.cflags :: cflags
621 :     val cflags = #base Paths.cflags :: cflags
622 :     (* generate the loader flags *)
623 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
624 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
625 :     val extraLibs = #cl Paths.extraLibs :: extraLibs
626 :     val rtLib = TargetUtil.runtimeName {
627 :     target = TargetUtil.TARGET_CL,
628 :     parallel = parallel, double = double, debug = debug
629 :     }
630 :     val ldOpts = rtLib :: extraLibs
631 :     in
632 :     genSrc (basename, prog);
633 :     RunCC.compile (basename, cflags);
634 :     RunCC.link (basename, ldOpts)
635 : jhr 1273 end
636 : lamonts 1244
637 : jhr 1273 end
638 : lamonts 1264
639 : lamonts 1244 (* strands *)
640 :     structure Strand =
641 :     struct
642 : jhr 1261 fun define (Prog{strands, ...}, strandId) = let
643 :     val name = Atom.toString strandId
644 :     val strand = Strand{
645 :     name = name,
646 :     tyName = RN.strandTy name,
647 :     state = ref [],
648 :     output = ref NONE,
649 : lamonts 1271 code = ref [],
650 : jhr 1273 init_code = ref (CL.D_Comment(["no init code"]))
651 : jhr 1261 }
652 :     in
653 :     AtomTable.insert strands (strandId, strand);
654 :     strand
655 :     end
656 : lamonts 1244
657 :     (* return the strand with the given name *)
658 : jhr 1261 fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
659 : lamonts 1244
660 :     (* register the strand-state initialization code. The variables are the strand
661 :     * parameters.
662 :     *)
663 : jhr 1308 fun init (Strand{name, tyName, code, init_code, ...}, params, init) = let
664 : jhr 1261 val fName = RN.strandInit name
665 :     val params =
666 : jhr 1313 CL.PARAM([], globPtrTy, RN.globalsVarName) ::
667 : jhr 1261 CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
668 : jhr 1273 List.map (fn (ToCL.V(ty, x)) => CL.PARAM([], ty, x)) params
669 : jhr 1261 val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
670 :     in
671 : jhr 1273 init_code := initFn
672 : jhr 1261 end
673 : lamonts 1244
674 :     (* register a strand method *)
675 : lamonts 1271 fun method (Strand{name, tyName, code,...}, methName, body) = let
676 : jhr 1261 val fName = concat[name, "_", methName]
677 :     val params = [
678 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
679 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut")
680 :     ]
681 :     val methFn = CL.D_Func([], CL.int32, fName, params, body)
682 :     in
683 : jhr 1273 code := methFn :: !code
684 : jhr 1261 end
685 :    
686 : jhr 1273 fun output (Strand{output, ...}, ty, ToCL.V(_, x)) = output := SOME(ty, x)
687 : lamonts 1244
688 :     end
689 :    
690 :     end
691 :    
692 :     structure CLBackEnd = CodeGenFn(CLTarget)

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