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

SCM Repository

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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1278 - (view) (download)

1 : jhr 519 (* c-target.sml
2 :     *
3 :     * COPYRIGHT (c) 2011 The Diderot Project (http://diderot-language.cs.uchicago.edu)
4 :     * All rights reserved.
5 :     *)
6 :    
7 : jhr 840 structure CTarget : TARGET =
8 : jhr 519 struct
9 :    
10 : jhr 839 structure IL = TreeIL
11 : jhr 840 structure V = IL.Var
12 : jhr 842 structure Ty = IL.Ty
13 : jhr 522 structure CL = CLang
14 : jhr 1261 structure N = TargetNames
15 : jhr 839 structure ToC = TreeToC
16 : jhr 522
17 : jhr 840 type var = ToC.var
18 : jhr 839 type exp = CL.exp
19 :     type stm = CL.stm
20 : jhr 519
21 : jhr 544 datatype strand = Strand of {
22 :     name : string,
23 :     tyName : string,
24 : jhr 623 state : var list ref,
25 : jhr 842 output : (Ty.ty * CL.var) option ref, (* the strand's output variable (only one for now) *)
26 : jhr 544 code : CL.decl list ref
27 :     }
28 : jhr 525
29 : jhr 527 datatype program = Prog of {
30 : jhr 1278 name : string, (* stem of source file *)
31 : jhr 1172 double : bool, (* true for double-precision support *)
32 :     parallel : bool, (* true for multithreaded (or multi-GPU) target *)
33 :     debug : bool, (* true for debug support in executable *)
34 : jhr 527 globals : CL.decl list ref,
35 : jhr 533 topDecls : CL.decl list ref,
36 : jhr 624 strands : strand AtomTable.hash_table,
37 :     initially : CL.decl ref
38 : jhr 527 }
39 :    
40 : jhr 842 datatype env = ENV of {
41 : jhr 839 info : env_info,
42 : jhr 840 vMap : var V.Map.map,
43 : jhr 839 scope : scope
44 :     }
45 : jhr 519
46 : jhr 839 and env_info = INFO of {
47 :     prog : program
48 :     }
49 : jhr 519
50 : jhr 839 and scope
51 :     = NoScope
52 :     | GlobalScope
53 :     | InitiallyScope
54 : jhr 1044 | StrandScope of TreeIL.var list (* strand initialization *)
55 : jhr 839 | MethodScope of TreeIL.var list (* method body; vars are state variables *)
56 : jhr 534
57 : jhr 839 (* the supprted widths of vectors of reals on the target. For the GNU vector extensions,
58 :     * the supported sizes are powers of two, but float2 is broken.
59 :     * NOTE: we should also consider the AVX vector hardware, which has 256-bit registers.
60 :     *)
61 : jhr 1262 fun vectorWidths () = if !N.doublePrecision
62 : jhr 839 then [2, 4, 8]
63 :     else [4, 8]
64 : jhr 528
65 : jhr 839 (* tests for whether various expression forms can appear inline *)
66 :     fun inlineCons n = (n < 2) (* vectors are inline, but not matrices *)
67 :     val inlineMatrixExp = false (* can matrix-valued expressions appear inline? *)
68 : jhr 548
69 : jhr 839 (* TreeIL to target translations *)
70 :     structure Tr =
71 : jhr 525 struct
72 : jhr 1153 fun fragment (ENV{info, vMap, scope}, blk) = let
73 :     val (vMap, stms) = ToC.trFragment (vMap, blk)
74 :     in
75 :     (ENV{info=info, vMap=vMap, scope=scope}, stms)
76 :     end
77 : jhr 1044 fun saveState cxt stateVars (env, args, stm) = (
78 :     ListPair.foldrEq
79 :     (fn (x, e, stms) => ToC.trAssign(env, x, e)@stms)
80 :     [stm]
81 :     (stateVars, args)
82 : jhr 1157 ) handle ListPair.UnequalLengths => (
83 :     print(concat["saveState ", cxt, ": length mismatch; ", Int.toString(List.length args), " args\n"]);
84 :     raise Fail(concat["saveState ", cxt, ": length mismatch"]))
85 : jhr 839 fun block (ENV{vMap, scope, ...}, blk) = (case scope
86 : jhr 1044 of StrandScope stateVars => ToC.trBlock (vMap, saveState "StrandScope" stateVars, blk)
87 :     | MethodScope stateVars => ToC.trBlock (vMap, saveState "MethodScope" stateVars, blk)
88 :     | _ => ToC.trBlock (vMap, fn (_, _, stm) => [stm], blk)
89 : jhr 839 (* end case *))
90 : jhr 840 fun exp (ENV{vMap, ...}, e) = ToC.trExp(vMap, e)
91 : jhr 519 end
92 :    
93 : jhr 839 (* variables *)
94 :     structure Var =
95 : jhr 525 struct
96 : jhr 1032 fun name (ToC.V(_, name)) = name
97 :     fun global (Prog{globals, ...}, name, ty) = let
98 :     val ty' = ToC.trType ty
99 : jhr 705 in
100 : jhr 1032 globals := CL.D_Var([], ty', name, NONE) :: !globals;
101 :     ToC.V(ty', name)
102 : jhr 705 end
103 : jhr 842 fun param x = ToC.V(ToC.trType(V.ty x), V.name x)
104 : jhr 840 fun state (Strand{state, ...}, x) = let
105 :     val ty' = ToC.trType(V.ty x)
106 :     val x' = ToC.V(ty', V.name x)
107 : jhr 623 in
108 : jhr 839 state := x' :: !state;
109 :     x'
110 : jhr 623 end
111 : jhr 839 end
112 : jhr 525
113 : jhr 839 (* environments *)
114 :     structure Env =
115 :     struct
116 :     (* create a new environment *)
117 :     fun new prog = ENV{
118 : jhr 840 info=INFO{prog = prog},
119 :     vMap = V.Map.empty,
120 : jhr 839 scope = NoScope
121 :     }
122 :     (* define the current translation context *)
123 :     fun setScope scope (ENV{info, vMap, ...}) = ENV{info=info, vMap=vMap, scope=scope}
124 :     val scopeGlobal = setScope GlobalScope
125 :     val scopeInitially = setScope InitiallyScope
126 : jhr 1044 fun scopeStrand (env, svars) = setScope (StrandScope svars) env
127 : jhr 839 fun scopeMethod (env, svars) = setScope (MethodScope svars) env
128 :     (* bind a TreeIL varaiable to a target variable *)
129 :     fun bind (ENV{info, vMap, scope}, x, x') = ENV{
130 :     info = info,
131 : jhr 840 vMap = V.Map.insert(vMap, x, x'),
132 : jhr 839 scope = scope
133 :     }
134 :     end
135 : jhr 525
136 : jhr 839 (* programs *)
137 : jhr 840 structure Program =
138 :     struct
139 : jhr 1278 fun new {name, double, parallel, debug} = (
140 : jhr 1261 N.initTargetSpec double;
141 : jhr 839 Prog{
142 : jhr 1278 name = name,
143 : jhr 1172 double = double, parallel = parallel, debug = debug,
144 : jhr 839 globals = ref [
145 :     CL.D_Verbatim[
146 : jhr 1172 if double
147 : jhr 839 then "#define DIDEROT_DOUBLE_PRECISION"
148 :     else "#define DIDEROT_SINGLE_PRECISION",
149 :     "#include \"Diderot/diderot.h\""
150 :     ]],
151 :     topDecls = ref [],
152 :     strands = AtomTable.mkTable (16, Fail "strand table"),
153 :     initially = ref(CL.D_Comment["missing initially"])
154 :     })
155 : jhr 1261 (* register the code that is used to register command-line options for input variables *)
156 :     fun inputs (Prog{topDecls, ...}, stm) = let
157 :     val inputsFn = CL.D_Func(
158 :     [], CL.voidTy, N.registerOpts,
159 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named N.optionsTy), "opts")],
160 :     stm)
161 :     in
162 :     topDecls := inputsFn :: !topDecls
163 :     end
164 : jhr 839 (* register the global initialization part of a program *)
165 :     fun init (Prog{topDecls, ...}, init) = let
166 : jhr 1261 val initFn = CL.D_Func([], CL.voidTy, N.initGlobals, [], init)
167 : jhr 1215 val shutdownFn = CL.D_Func(
168 : jhr 1261 [], CL.voidTy, N.shutdown,
169 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named N.worldTy), "wrld")],
170 : jhr 1215 CL.S_Block[])
171 : jhr 528 in
172 : jhr 1215 topDecls := shutdownFn :: initFn :: !topDecls
173 : jhr 528 end
174 : jhr 839 (* create and register the initially function for a program *)
175 :     fun initially {
176 :     prog = Prog{strands, initially, ...},
177 :     isArray : bool,
178 : jhr 1153 iterPrefix : stm list,
179 : jhr 839 iters : (var * exp * exp) list,
180 : jhr 1153 createPrefix : stm list,
181 : jhr 839 strand : Atom.atom,
182 :     args : exp list
183 :     } = let
184 :     val name = Atom.toString strand
185 :     val nDims = List.length iters
186 : jhr 1261 val worldTy = CL.T_Ptr(CL.T_Named N.worldTy)
187 : jhr 839 fun mapi f xs = let
188 :     fun mapf (_, []) = []
189 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
190 :     in
191 :     mapf (0, xs)
192 :     end
193 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
194 :     val sizeInit = mapi
195 : jhr 840 (fn (i, (ToC.V(ty, _), lo, hi)) =>
196 :     (i, CL.I_Exp(CL.mkBinOp(CL.mkBinOp(hi, CL.#-, lo), CL.#+, CL.E_Int(1, ty))))
197 : jhr 839 ) iters
198 :     val allocCode = [
199 :     CL.mkComment["allocate initial block of strands"],
200 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
201 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
202 :     CL.mkDecl(worldTy, "wrld",
203 : jhr 1261 SOME(CL.I_Exp(CL.E_Apply(N.allocInitially, [
204 :     CL.mkUnOp(CL.%&, CL.E_Var(N.strandDesc name)),
205 : jhr 839 CL.E_Bool isArray,
206 :     CL.E_Int(IntInf.fromInt nDims, CL.int32),
207 :     CL.E_Var "base",
208 :     CL.E_Var "size"
209 :     ]))))
210 :     ]
211 :     (* create the loop nest for the initially iterations *)
212 :     val indexVar = "ix"
213 : jhr 1261 val strandTy = CL.T_Ptr(CL.T_Named(N.strandTy name))
214 : jhr 839 fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
215 :     CL.mkDecl(strandTy, "sp",
216 :     SOME(CL.I_Exp(
217 :     CL.E_Cast(strandTy,
218 : jhr 1261 CL.E_Apply(N.inState, [CL.E_Var "wrld", CL.E_Var indexVar]))))),
219 :     CL.mkCall(N.strandInit name, CL.E_Var "sp" :: args),
220 : jhr 839 CL.mkAssign(CL.E_Var indexVar, CL.mkBinOp(CL.E_Var indexVar, CL.#+, CL.E_Int(1, CL.uint32)))
221 :     ])
222 : jhr 840 | mkLoopNest ((ToC.V(ty, param), lo, hi)::iters) = let
223 : jhr 839 val body = mkLoopNest iters
224 :     in
225 :     CL.mkFor(
226 : jhr 840 [(ty, param, lo)],
227 : jhr 839 CL.mkBinOp(CL.E_Var param, CL.#<=, hi),
228 :     [CL.mkPostOp(CL.E_Var param, CL.^++)],
229 :     body)
230 :     end
231 :     val iterCode = [
232 :     CL.mkComment["initially"],
233 :     CL.mkDecl(CL.uint32, indexVar, SOME(CL.I_Exp(CL.E_Int(0, CL.uint32)))),
234 :     mkLoopNest iters
235 :     ]
236 :     val body = CL.mkBlock(iterPrefix @ allocCode @ iterCode @ [CL.mkReturn(SOME(CL.E_Var "wrld"))])
237 : jhr 1261 val initFn = CL.D_Func([], worldTy, N.initially, [], body)
238 : jhr 548 in
239 : jhr 839 initially := initFn
240 : jhr 548 end
241 : jhr 839
242 :     (***** OUTPUT *****)
243 :     fun genStrand (Strand{name, tyName, state, output, code}) = let
244 :     (* the type declaration for the strand's state struct *)
245 :     val selfTyDef = CL.D_StructDef(
246 : jhr 840 List.rev (List.map (fn ToC.V(ty, x) => (ty, x)) (!state)),
247 : jhr 839 tyName)
248 :     (* the print function *)
249 :     val prFnName = concat[name, "_print"]
250 :     val prFn = let
251 :     val params = [
252 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
253 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
254 :     ]
255 : jhr 842 val SOME(ty, x) = !output
256 : jhr 839 val outState = CL.mkIndirect(CL.mkVar "self", x)
257 :     val prArgs = (case ty
258 : jhr 1261 of Ty.IVecTy 1 => [CL.E_Str(!N.gIntFormat ^ "\n"), outState]
259 : jhr 842 | Ty.IVecTy d => let
260 : jhr 839 val fmt = CL.E_Str(
261 : jhr 1261 String.concatWith " " (List.tabulate(d, fn _ => !N.gIntFormat))
262 : jhr 839 ^ "\n")
263 : jhr 842 val args = List.tabulate (d, fn i => ToC.ivecIndex(outState, d, i))
264 : jhr 839 in
265 :     fmt :: args
266 :     end
267 : jhr 842 | Ty.TensorTy[] => [CL.E_Str "%f\n", outState]
268 :     | Ty.TensorTy[d] => let
269 : jhr 839 val fmt = CL.E_Str(
270 : jhr 842 String.concatWith " " (List.tabulate(d, fn _ => "%f"))
271 : jhr 839 ^ "\n")
272 : jhr 842 val args = List.tabulate (d, fn i => ToC.vecIndex(outState, d, i))
273 : jhr 839 in
274 :     fmt :: args
275 :     end
276 : jhr 842 | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
277 : jhr 839 (* end case *))
278 :     in
279 :     CL.D_Func(["static"], CL.voidTy, prFnName, params,
280 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs))
281 :     end
282 :     (* the strand's descriptor object *)
283 :     val descI = let
284 :     fun fnPtr (ty, f) = CL.I_Exp(CL.mkCast(CL.T_Named ty, CL.mkVar f))
285 :     in
286 :     CL.I_Struct[
287 :     ("name", CL.I_Exp(CL.E_Str name)),
288 : jhr 1261 ("stateSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(N.strandTy name)))),
289 : jhr 839 ("update", fnPtr("update_method_t", name ^ "_update")),
290 :     ("print", fnPtr("print_method_t", prFnName))
291 :     ]
292 :     end
293 : jhr 1261 val desc = CL.D_Var([], CL.T_Named N.strandDescTy, N.strandDesc name, SOME descI)
294 : jhr 548 in
295 : jhr 839 selfTyDef :: List.rev (desc :: prFn :: !code)
296 : jhr 548 end
297 : jhr 839
298 :     (* generate the table of strand descriptors *)
299 :     fun genStrandTable (ppStrm, strands) = let
300 :     val nStrands = length strands
301 : jhr 1261 fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.E_Var(N.strandDesc name)))
302 : jhr 839 fun genInits (_, []) = []
303 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
304 :     fun ppDecl dcl = PrintAsC.output(ppStrm, dcl)
305 : jhr 547 in
306 : jhr 1261 ppDecl (CL.D_Var([], CL.int32, N.numStrands,
307 : jhr 839 SOME(CL.I_Exp(CL.E_Int(IntInf.fromInt nStrands, CL.int32)))));
308 :     ppDecl (CL.D_Var([],
309 : jhr 1261 CL.T_Array(CL.T_Ptr(CL.T_Named N.strandDescTy), SOME nStrands),
310 :     N.strands,
311 : jhr 839 SOME(CL.I_Array(genInits (0, strands)))))
312 : jhr 547 end
313 : jhr 519
314 : jhr 1172 fun genSrc (baseName, Prog{globals, topDecls, strands, initially, ...}) = let
315 : jhr 839 val fileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
316 :     val outS = TextIO.openOut fileName
317 :     val ppStrm = PrintAsC.new outS
318 :     fun ppDecl dcl = PrintAsC.output(ppStrm, dcl)
319 :     val strands = AtomTable.listItems strands
320 : jhr 695 in
321 : jhr 839 List.app ppDecl (List.rev (!globals));
322 :     List.app ppDecl (List.rev (!topDecls));
323 :     List.app (fn strand => List.app ppDecl (genStrand strand)) strands;
324 :     genStrandTable (ppStrm, strands);
325 :     ppDecl (!initially);
326 :     PrintAsC.close ppStrm;
327 :     TextIO.closeOut outS
328 : jhr 695 end
329 : jhr 547
330 : jhr 839 (* output the code to a file. The string is the basename of the file, the extension
331 :     * is provided by the target.
332 :     *)
333 : jhr 1278 fun generate (basename, prog as Prog{name, double, parallel, debug, ...}) = let
334 : jhr 1172 fun condCons (true, x, xs) = x::xs
335 :     | condCons (false, _, xs) = xs
336 :     (* generate the C compiler flags *)
337 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
338 :     val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
339 :     val cflags = if debug
340 :     then #debug Paths.cflags :: cflags
341 :     else #ndebug Paths.cflags :: cflags
342 :     val cflags = #base Paths.cflags :: cflags
343 :     (* generate the loader flags *)
344 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
345 : jhr 1209 val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
346 : jhr 1172 val rtLib = TargetUtil.runtimeName {
347 :     target = TargetUtil.TARGET_C,
348 :     parallel = parallel, double = double, debug = debug
349 :     }
350 :     val ldOpts = rtLib :: extraLibs
351 :     in
352 :     genSrc (basename, prog);
353 :     RunCC.compile (basename, cflags);
354 :     RunCC.link (basename, ldOpts)
355 :     end
356 : jhr 839
357 : jhr 519 end
358 :    
359 : jhr 839 (* strands *)
360 : jhr 544 structure Strand =
361 :     struct
362 :     fun define (Prog{strands, ...}, strandId) = let
363 : jhr 624 val name = Atom.toString strandId
364 : jhr 544 val strand = Strand{
365 : jhr 624 name = name,
366 : jhr 1261 tyName = N.strandTy name,
367 : jhr 544 state = ref [],
368 : jhr 654 output = ref NONE,
369 : jhr 544 code = ref []
370 :     }
371 :     in
372 : jhr 624 AtomTable.insert strands (strandId, strand);
373 : jhr 544 strand
374 :     end
375 :    
376 : jhr 624 (* return the strand with the given name *)
377 :     fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
378 :    
379 : jhr 544 (* register the strand-state initialization code. The variables are the strand
380 :     * parameters.
381 :     *)
382 :     fun init (Strand{name, tyName, code, ...}, params, init) = let
383 : jhr 1261 val fName = N.strandInit name
384 : jhr 544 val params =
385 : jhr 547 CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
386 : jhr 842 List.map (fn (ToC.V(ty, x)) => CL.PARAM([], ty, x)) params
387 : jhr 544 val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
388 :     in
389 :     code := initFn :: !code
390 :     end
391 : jhr 547
392 :     (* register a strand method *)
393 :     fun method (Strand{name, tyName, code, ...}, methName, body) = let
394 :     val fName = concat[name, "_", methName]
395 :     val params = [
396 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
397 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut")
398 :     ]
399 : jhr 654 val methFn = CL.D_Func(["static"], CL.int32, fName, params, body)
400 : jhr 547 in
401 :     code := methFn :: !code
402 :     end
403 : jhr 654
404 : jhr 842 fun output (Strand{output, ...}, ty, ToC.V(_, x)) = output := SOME(ty, x)
405 : jhr 544
406 : jhr 839 end
407 : jhr 624
408 : jhr 519 end
409 :    
410 :     structure CBackEnd = CodeGenFn(CTarget)

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