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 1315 - (view) (download)

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

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