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

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