optimizer.ml 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. (*
  2. * Copyright (C)2005-2013 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. *)
  22. open Ast
  23. open Type
  24. open Common
  25. open Typecore
  26. (* ---------------------------------------------------------------------- *)
  27. (* API OPTIMIZATIONS *)
  28. (* tells if an expression causes side effects. This does not account for potential null accesses (fields/arrays/ops) *)
  29. let has_side_effect e =
  30. let rec loop e =
  31. match e.eexpr with
  32. | TConst _ | TLocal _ | TTypeExpr _ | TFunction _ -> ()
  33. | TCall ({ eexpr = TField(_,FStatic({ cl_path = ([],"Std") },{ cf_name = "string" })) },args) -> Type.iter loop e
  34. | TNew _ | TCall _ | TBinop ((OpAssignOp _ | OpAssign),_,_) | TUnop ((Increment|Decrement),_,_) -> raise Exit
  35. | TReturn _ | TBreak | TContinue | TThrow _ | TCast (_,Some _) -> raise Exit
  36. | TArray _ | TEnumParameter _ | TCast (_,None) | TBinop _ | TUnop _ | TParenthesis _ | TMeta _ | TWhile _ | TFor _
  37. | TField _ | TIf _ | TTry _ | TSwitch _ | TArrayDecl _ | TBlock _ | TObjectDecl _ | TVar _ -> Type.iter loop e
  38. in
  39. try
  40. loop e; false
  41. with Exit ->
  42. true
  43. let mk_untyped_call name p params =
  44. {
  45. eexpr = TCall({ eexpr = TLocal(alloc_unbound_var name t_dynamic); etype = t_dynamic; epos = p }, params);
  46. etype = t_dynamic;
  47. epos = p;
  48. }
  49. let api_inline ctx c field params p =
  50. match c.cl_path, field, params with
  51. | ([],"Type"),"enumIndex",[{ eexpr = TField (_,FEnum (en,f)) }] -> (match ctx.com.platform with
  52. | Cs when en.e_extern && not (Meta.has Meta.HxGen en.e_meta) ->
  53. (* We don't want to optimize enums from external sources; as they might change unexpectedly *)
  54. (* and since native C# enums don't have the concept of index - they have rather a value, *)
  55. (* which can't be mapped to a native API - this kind of substitution is dangerous *)
  56. None
  57. | _ ->
  58. Some (mk (TConst (TInt (Int32.of_int f.ef_index))) ctx.t.tint p))
  59. | ([],"Type"),"enumIndex",[{ eexpr = TCall({ eexpr = TField (_,FEnum (en,f)) },pl) }] when List.for_all (fun e -> not (has_side_effect e)) pl ->
  60. (match ctx.com.platform with
  61. | Cs when en.e_extern && not (Meta.has Meta.HxGen en.e_meta) ->
  62. (* see comment above *)
  63. None
  64. | _ ->
  65. Some (mk (TConst (TInt (Int32.of_int f.ef_index))) ctx.t.tint p))
  66. | ([],"Std"),"int",[{ eexpr = TConst (TInt _) } as e] ->
  67. Some { e with epos = p }
  68. | ([],"String"),"fromCharCode",[{ eexpr = TConst (TInt i) }] when i > 0l && i < 128l ->
  69. Some (mk (TConst (TString (String.make 1 (char_of_int (Int32.to_int i))))) ctx.t.tstring p)
  70. | ([],"Std"),"string",[{ eexpr = TConst c } as e] ->
  71. (match c with
  72. | TString s ->
  73. Some { e with epos = p }
  74. | TInt i ->
  75. Some { eexpr = TConst (TString (Int32.to_string i)); epos = p; etype = ctx.t.tstring }
  76. | TBool b ->
  77. Some { eexpr = TConst (TString (if b then "true" else "false")); epos = p; etype = ctx.t.tstring }
  78. | _ ->
  79. None)
  80. | ([],"Std"),"string",[{ eexpr = TIf (_,{ eexpr = TConst (TString _)},Some { eexpr = TConst (TString _) }) } as e] ->
  81. Some e
  82. | ([],"Std"),"string",[{ eexpr = TLocal _ | TField({ eexpr = TLocal _ },_) } as v] when ctx.com.platform = Js || ctx.com.platform = Flash ->
  83. let pos = v.epos in
  84. let stringv() =
  85. let to_str = mk (TBinop (Ast.OpAdd, mk (TConst (TString "")) ctx.t.tstring pos, v)) ctx.t.tstring pos in
  86. if ctx.com.platform = Js || is_nullable v.etype then
  87. let chk_null = mk (TBinop (Ast.OpEq, v, mk (TConst TNull) t_dynamic pos)) ctx.t.tbool pos in
  88. mk (TIf (chk_null, mk (TConst (TString "null")) ctx.t.tstring pos, Some to_str)) ctx.t.tstring pos
  89. else
  90. to_str
  91. in
  92. (match follow v.etype with
  93. | TInst ({ cl_path = [],"String" }, []) ->
  94. Some (stringv())
  95. | TAbstract ({ a_path = [],"Float" }, []) ->
  96. Some (stringv())
  97. | TAbstract ({ a_path = [],"Int" }, []) ->
  98. Some (stringv())
  99. | TAbstract ({ a_path = [],"UInt" }, []) ->
  100. Some (stringv())
  101. | TAbstract ({ a_path = [],"Bool" }, []) ->
  102. Some (stringv())
  103. | _ ->
  104. None)
  105. | ([],"Std"),"is",[o;t] | (["js"],"Boot"),"__instanceof",[o;t] when ctx.com.platform = Js ->
  106. let mk_local ctx n t pos =
  107. mk (TLocal (try
  108. PMap.find n ctx.locals
  109. with _ ->
  110. let v = add_local ctx n t in
  111. v.v_meta <- [Meta.Unbound,[],p];
  112. v
  113. )) t pos in
  114. let tstring = ctx.com.basic.tstring in
  115. let tbool = ctx.com.basic.tbool in
  116. let tint = ctx.com.basic.tint in
  117. let is_trivial e =
  118. match e.eexpr with
  119. | TConst _ | TLocal _ -> true
  120. | _ -> false
  121. in
  122. let typeof t =
  123. let tof = mk_local ctx "__typeof__" (tfun [o.etype] tstring) p in
  124. let tof = mk (TCall (tof, [o])) tstring p in
  125. mk (TBinop (Ast.OpEq, tof, (mk (TConst (TString t)) tstring p))) tbool p
  126. in
  127. (match t.eexpr with
  128. (* generate simple typeof checks for basic types *)
  129. | TTypeExpr (TClassDecl ({ cl_path = [],"String" })) -> Some (typeof "string")
  130. | TTypeExpr (TAbstractDecl ({ a_path = [],"Bool" })) -> Some (typeof "boolean")
  131. | TTypeExpr (TAbstractDecl ({ a_path = [],"Float" })) -> Some (typeof "number")
  132. | TTypeExpr (TAbstractDecl ({ a_path = [],"Int" })) when is_trivial o ->
  133. (* generate (o|0) === o check *)
  134. let teq = mk_local ctx "__strict_eq__" (tfun [tint; tint] tbool) p in
  135. let lhs = mk (TBinop (Ast.OpOr, o, mk (TConst (TInt Int32.zero)) tint p)) tint p in
  136. Some (mk (TCall (teq, [lhs; o])) tbool p)
  137. | TTypeExpr (TClassDecl ({ cl_path = [],"Array" })) ->
  138. (* generate (o instanceof Array) && o.__enum__ == null check *)
  139. let iof = mk_local ctx "__instanceof__" (tfun [o.etype;t.etype] tbool) p in
  140. let iof = mk (TCall (iof, [o; t])) tbool p in
  141. let enum = mk (TField (o, FDynamic "__enum__")) (mk_mono()) p in
  142. let null = mk (TConst TNull) (mk_mono()) p in
  143. let not_enum = mk (TBinop (Ast.OpEq, enum, null)) tbool p in
  144. Some (mk (TBinop (Ast.OpBoolAnd, iof, not_enum)) tbool p)
  145. | _ ->
  146. None)
  147. | ([],"Std"),"int",[{ eexpr = TConst (TFloat f) }] ->
  148. let f = float_of_string f in
  149. (match classify_float f with
  150. | FP_infinite | FP_nan ->
  151. None
  152. | _ when f <= Int32.to_float Int32.min_int -. 1. || f >= Int32.to_float Int32.max_int +. 1. ->
  153. None (* out range, keep platform-specific behavior *)
  154. | _ ->
  155. Some { eexpr = TConst (TInt (Int32.of_float f)); etype = ctx.t.tint; epos = p })
  156. | (["cs"],"Lib"),("fixed" | "checked" | "unsafe"),[e] ->
  157. Some (mk_untyped_call ("__" ^ field ^ "__") p [e])
  158. | (["cs"],"Lib"),("lock"),[obj;block] ->
  159. Some (mk_untyped_call ("__lock__") p [obj;mk_block block])
  160. | (["java"],"Lib"),("lock"),[obj;block] ->
  161. Some (mk_untyped_call ("__lock__") p [obj;mk_block block])
  162. | (["cs" | "java"],"Lib"),("nativeArray"),[{ eexpr = TArrayDecl args } as edecl; _]
  163. | (["haxe";"ds";"_Vector"],"Vector_Impl_"),("fromArrayCopy"),[{ eexpr = TArrayDecl args } as edecl] -> (try
  164. let platf = match ctx.com.platform with
  165. | Cs -> "cs"
  166. | Java -> "java"
  167. | _ -> raise Exit
  168. in
  169. let mpath = if field = "fromArrayCopy" then
  170. (["haxe";"ds"],"Vector")
  171. else
  172. ([platf],"NativeArray")
  173. in
  174. let m = ctx.g.do_load_module ctx mpath null_pos in
  175. let main = List.find (function | TClassDecl _ | TAbstractDecl _ -> true | _ -> false) m.m_types in
  176. let t = match follow edecl.etype, main with
  177. | TInst({ cl_path = [],"Array" }, [t]), TClassDecl(cl) ->
  178. TInst(cl,[t])
  179. | TInst({ cl_path = [],"Array" }, [t]), TAbstractDecl(a) ->
  180. TAbstract(a,[t])
  181. | _ -> assert false
  182. in
  183. Some ({ (mk_untyped_call "__array__" p args) with etype = t })
  184. with | Exit ->
  185. None)
  186. | _ ->
  187. None
  188. (* ---------------------------------------------------------------------- *)
  189. (* INLINING *)
  190. type in_local = {
  191. i_var : tvar;
  192. i_subst : tvar;
  193. mutable i_captured : bool;
  194. mutable i_write : bool;
  195. mutable i_read : int;
  196. mutable i_force_temp : bool;
  197. }
  198. let inline_default_config cf t =
  199. (* type substitution on both class and function type parameters *)
  200. let rec get_params c pl =
  201. match c.cl_super with
  202. | None -> c.cl_params, pl
  203. | Some (csup,spl) ->
  204. let spl = (match apply_params c.cl_params pl (TInst (csup,spl)) with
  205. | TInst (_,pl) -> pl
  206. | _ -> assert false
  207. ) in
  208. let ct, cpl = get_params csup spl in
  209. c.cl_params @ ct, pl @ cpl
  210. in
  211. let tparams = (match follow t with
  212. | TInst (c,pl) -> get_params c pl
  213. | _ -> ([],[]))
  214. in
  215. let pmonos = List.map (fun _ -> mk_mono()) cf.cf_params in
  216. let tmonos = snd tparams @ pmonos in
  217. let tparams = fst tparams @ cf.cf_params in
  218. tparams <> [], apply_params tparams tmonos
  219. let rec type_inline ctx cf f ethis params tret config p ?(self_calling_closure=false) force =
  220. (* perform some specific optimization before we inline the call since it's not possible to detect at final optimization time *)
  221. try
  222. let cl = (match follow ethis.etype with
  223. | TInst (c,_) -> c
  224. | TAnon a -> (match !(a.a_status) with Statics c -> c | _ -> raise Exit)
  225. | _ -> raise Exit
  226. ) in
  227. (match api_inline ctx cl cf.cf_name params p with
  228. | None -> raise Exit
  229. | Some e -> Some e)
  230. with Exit ->
  231. let has_params,map_type = match config with Some config -> config | None -> inline_default_config cf ethis.etype in
  232. (* locals substitution *)
  233. let locals = Hashtbl.create 0 in
  234. let local v =
  235. try
  236. Hashtbl.find locals v.v_id
  237. with Not_found ->
  238. let v' = alloc_var v.v_name v.v_type in
  239. if Meta.has Meta.Unbound v.v_meta then v'.v_meta <- [Meta.Unbound,[],p];
  240. let i = {
  241. i_var = v;
  242. i_subst = v';
  243. i_captured = false;
  244. i_write = false;
  245. i_force_temp = false;
  246. i_read = 0;
  247. } in
  248. i.i_subst.v_meta <- v.v_meta;
  249. Hashtbl.add locals v.v_id i;
  250. Hashtbl.add locals i.i_subst.v_id i;
  251. i
  252. in
  253. let in_local_fun = ref false in
  254. let read_local v =
  255. let l = try
  256. Hashtbl.find locals v.v_id
  257. with Not_found ->
  258. (* make sure to duplicate unbound inline variable to prevent dependency leak when unifying monomorph *)
  259. if has_meta Meta.Unbound v.v_meta then local v else
  260. {
  261. i_var = v;
  262. i_subst = v;
  263. i_captured = false;
  264. i_write = false;
  265. i_force_temp = false;
  266. i_read = 0;
  267. }
  268. in
  269. if !in_local_fun then l.i_captured <- true;
  270. l
  271. in
  272. (* use default values for null/unset arguments *)
  273. let rec loop pl al first =
  274. match pl, al with
  275. | _, [] -> []
  276. | e :: pl, (v, opt) :: al ->
  277. (*
  278. if we pass a Null<T> var to an inlined method that needs a T.
  279. we need to force a local var to be created on some platforms.
  280. *)
  281. if ctx.com.config.pf_static && not (is_nullable v.v_type) && is_null e.etype then (local v).i_force_temp <- true;
  282. (*
  283. if we cast from Dynamic, create a local var as well to do the cast
  284. once and allow DCE to perform properly.
  285. *)
  286. if v.v_type != t_dynamic && follow e.etype == t_dynamic then (local v).i_write <- true;
  287. (match e.eexpr, opt with
  288. | TConst TNull , Some c -> mk (TConst c) v.v_type e.epos
  289. (*
  290. This is really weird and should be reviewed again. The problem is that we cannot insert a TCast here because
  291. the abstract `this` value could be written to, which is not possible if it is wrapped in a cast.
  292. The original problem here is that we do not generate a temporary variable and thus mute the type of the
  293. `this` variable, which leads to unification errors down the line. See issues #2236 and #3713.
  294. *)
  295. (* | _ when first && (Meta.has Meta.Impl cf.cf_meta) -> {e with etype = v.v_type} *)
  296. | _ -> e) :: loop pl al false
  297. | [], (v,opt) :: al ->
  298. (mk (TConst (match opt with None -> TNull | Some c -> c)) v.v_type p) :: loop [] al false
  299. in
  300. (*
  301. Build the expr/var subst list
  302. *)
  303. let ethis = (match ethis.eexpr with TConst TSuper -> { ethis with eexpr = TConst TThis } | _ -> ethis) in
  304. let vthis = alloc_var "_this" ethis.etype in
  305. let inlined_vars = List.map2 (fun e (v,_) ->
  306. let l = local v in
  307. if has_side_effect e then l.i_force_temp <- true; (* force tmp var *)
  308. l, e
  309. ) (ethis :: loop params f.tf_args true) ((vthis,None) :: f.tf_args) in
  310. let inlined_vars = List.rev inlined_vars in
  311. (*
  312. here, we try to eliminate final returns from the expression tree.
  313. However, this is not entirely correct since we don't yet correctly propagate
  314. the type of returned expressions upwards ("return" expr itself being Dynamic).
  315. We also substitute variables with fresh ones that might be renamed at later stage.
  316. *)
  317. let opt f = function
  318. | None -> None
  319. | Some e -> Some (f e)
  320. in
  321. let has_vars = ref false in
  322. let in_loop = ref false in
  323. let cancel_inlining = ref false in
  324. let has_return_value = ref false in
  325. let ret_val = (match follow f.tf_type with TAbstract ({ a_path = ([],"Void") },[]) -> false | _ -> true) in
  326. let map_pos = if self_calling_closure then (fun e -> e) else (fun e -> { e with epos = p }) in
  327. let rec map term e =
  328. let po = e.epos in
  329. let e = map_pos e in
  330. match e.eexpr with
  331. | TLocal v ->
  332. let l = read_local v in
  333. l.i_read <- l.i_read + (if !in_loop then 2 else 1);
  334. (* never inline a function which contain a delayed macro because its bound
  335. to its variables and not the calling method *)
  336. if v.v_name = "__dollar__delay_call" then cancel_inlining := true;
  337. let e = { e with eexpr = TLocal l.i_subst } in
  338. if Meta.has Meta.This v.v_meta then mk (TCast(e,None)) v.v_type e.epos else e
  339. | TConst TThis ->
  340. let l = read_local vthis in
  341. l.i_read <- l.i_read + (if !in_loop then 2 else 1);
  342. { e with eexpr = TLocal l.i_subst }
  343. | TVar (v,eo) ->
  344. has_vars := true;
  345. { e with eexpr = TVar ((local v).i_subst,opt (map false) eo)}
  346. | TReturn eo when not !in_local_fun ->
  347. if not term then error "Cannot inline a not final return" po;
  348. (match eo with
  349. | None -> mk (TConst TNull) f.tf_type p
  350. | Some e ->
  351. has_return_value := true;
  352. map term e)
  353. | TFor (v,e1,e2) ->
  354. let i = local v in
  355. let e1 = map false e1 in
  356. let old = !in_loop in
  357. in_loop := true;
  358. let e2 = map false e2 in
  359. in_loop := old;
  360. { e with eexpr = TFor (i.i_subst,e1,e2) }
  361. | TWhile (cond,eloop,flag) ->
  362. let cond = map false cond in
  363. let old = !in_loop in
  364. in_loop := true;
  365. let eloop = map false eloop in
  366. in_loop := old;
  367. { e with eexpr = TWhile (cond,eloop,flag) }
  368. | TSwitch (e1,cases,def) when term ->
  369. let term = term && def <> None in
  370. let cases = List.map (fun (el,e) ->
  371. let el = List.map (map false) el in
  372. el, map term e
  373. ) cases in
  374. let def = opt (map term) def in
  375. { e with eexpr = TSwitch (map false e1,cases,def); etype = if ret_val then unify_min ctx ((List.map snd cases) @ (match def with None -> [] | Some e -> [e])) else e.etype }
  376. | TTry (e1,catches) ->
  377. { e with eexpr = TTry (map term e1,List.map (fun (v,e) ->
  378. let lv = (local v).i_subst in
  379. let e = map term e in
  380. lv,e
  381. ) catches); etype = if term && ret_val then unify_min ctx (e1::List.map snd catches) else e.etype }
  382. | TBlock l ->
  383. let old = save_locals ctx in
  384. let t = ref e.etype in
  385. let has_return e =
  386. let rec loop e = match e.eexpr with
  387. | TReturn _ -> raise Exit
  388. | _ -> Type.iter loop e
  389. in
  390. try loop e; false with Exit -> true
  391. in
  392. let rec loop = function
  393. | [] when term ->
  394. t := mk_mono();
  395. [mk (TConst TNull) (!t) p]
  396. | [] -> []
  397. | [e] ->
  398. let e = map term e in
  399. if term then t := e.etype;
  400. [e]
  401. | ({ eexpr = TIf (cond,e1,None) } as e) :: l when term && has_return e1 ->
  402. loop [{ e with eexpr = TIf (cond,e1,Some (mk (TBlock l) e.etype e.epos)); epos = punion e.epos (match List.rev l with e :: _ -> e.epos | [] -> assert false) }]
  403. | e :: l ->
  404. let e = map false e in
  405. e :: loop l
  406. in
  407. let l = loop l in
  408. old();
  409. { e with eexpr = TBlock l; etype = !t }
  410. | TIf (econd,eif,Some eelse) when term ->
  411. let econd = map false econd in
  412. let eif = map term eif in
  413. let eelse = map term eelse in
  414. { e with eexpr = TIf(econd,eif,Some eelse); etype = if ret_val then unify_min ctx [eif;eelse] else e.etype }
  415. | TParenthesis e1 ->
  416. let e1 = map term e1 in
  417. mk (TParenthesis e1) e1.etype e.epos
  418. | TUnop ((Increment|Decrement) as op,flag,({ eexpr = TLocal v } as e1)) ->
  419. let l = read_local v in
  420. l.i_write <- true;
  421. {e with eexpr = TUnop(op,flag,{e1 with eexpr = TLocal l.i_subst})}
  422. | TBinop ((OpAssign | OpAssignOp _) as op,({ eexpr = TLocal v } as e1),e2) ->
  423. let l = read_local v in
  424. l.i_write <- true;
  425. let e2 = map false e2 in
  426. {e with eexpr = TBinop(op,{e1 with eexpr = TLocal l.i_subst},e2)}
  427. (* | TCall({eexpr = TLocal v} as e1,el) ->
  428. let el = List.map (map false) el in
  429. let l = read_local v in
  430. let edef() = {e with eexpr = TCall({e1 with eexpr = TLocal l.i_subst},el)} in
  431. begin try
  432. begin match List.assq l inlined_vars with
  433. | {eexpr = TField(_, (FStatic(_,cf) | FInstance(_,_,cf)))} as e' when cf.cf_kind = Method MethInline ->
  434. make_call ctx e' el e.etype e.epos
  435. | _ ->
  436. edef()
  437. end
  438. with Not_found ->
  439. edef()
  440. end *)
  441. | TFunction f ->
  442. (match f.tf_args with [] -> () | _ -> has_vars := true);
  443. let old = save_locals ctx and old_fun = !in_local_fun in
  444. let args = List.map (function(v,c) -> (local v).i_subst, c) f.tf_args in
  445. in_local_fun := true;
  446. let expr = map false f.tf_expr in
  447. in_local_fun := old_fun;
  448. old();
  449. { e with eexpr = TFunction { tf_args = args; tf_expr = expr; tf_type = f.tf_type } }
  450. | TConst TSuper ->
  451. error "Cannot inline function containing super" po
  452. | _ ->
  453. Type.map_expr (map false) e
  454. in
  455. let e = map true f.tf_expr in
  456. (*
  457. if variables are not written and used with a const value, let's substitute
  458. with the actual value, either create a temp var
  459. *)
  460. let subst = ref PMap.empty in
  461. let is_constant e =
  462. let rec loop e =
  463. match e.eexpr with
  464. | TLocal _
  465. | TConst TThis (* not really, but should not be move inside a function body *)
  466. -> raise Exit
  467. | TField (_,FEnum _)
  468. | TTypeExpr _
  469. | TConst _ -> ()
  470. | _ ->
  471. Type.iter loop e
  472. in
  473. try loop e; true with Exit -> false
  474. in
  475. let is_writable e =
  476. match e.eexpr with
  477. | TField _ | TEnumParameter _ | TLocal _ | TArray _ -> true
  478. | _ -> false
  479. in
  480. let force = ref force in
  481. let vars = List.fold_left (fun acc (i,e) ->
  482. let flag = not i.i_force_temp && (match e.eexpr with
  483. | TLocal v when Meta.has Meta.This v.v_meta -> true
  484. | TLocal _ | TConst _ -> not i.i_write
  485. | TFunction _ -> if i.i_write then error "Cannot modify a closure parameter inside inline method" p; true
  486. | _ -> not i.i_write && i.i_read <= 1
  487. ) in
  488. let flag = flag && (not i.i_captured || is_constant e) in
  489. (* force inlining if we modify 'this' *)
  490. if i.i_write && (Meta.has Meta.This i.i_var.v_meta) then force := true;
  491. (* force inlining of 'this' variable if it is written *)
  492. let flag = if not flag && (Meta.has Meta.This i.i_var.v_meta) && i.i_write then begin
  493. if not (is_writable e) then error "Cannot modify the abstract value, store it into a local first" p;
  494. true
  495. end else flag in
  496. if flag then begin
  497. subst := PMap.add i.i_subst.v_id e !subst;
  498. acc
  499. end else
  500. (i.i_subst,Some e) :: acc
  501. ) [] inlined_vars in
  502. let subst = !subst in
  503. let rec inline_params e =
  504. match e.eexpr with
  505. | TLocal v -> (try PMap.find v.v_id subst with Not_found -> e)
  506. | _ -> Type.map_expr inline_params e
  507. in
  508. let e = (if PMap.is_empty subst then e else inline_params e) in
  509. let init = match vars with [] -> None | l -> Some l in
  510. (*
  511. If we have local variables and returning a value, then this will result in
  512. unoptimized JS code, so let's instead skip inlining.
  513. This could be fixed with better post process code cleanup (planed)
  514. *)
  515. if !cancel_inlining || (not (Common.defined ctx.com Define.Analyzer) && Common.platform ctx.com Js && not !force && (init <> None || !has_vars)) then
  516. None
  517. else
  518. let wrap e =
  519. (* we can't mute the type of the expression because it is not correct to do so *)
  520. let etype = if has_params then map_type e.etype else e.etype in
  521. (* if the expression is "untyped" and we don't want to unify it accidentally ! *)
  522. try (match follow e.etype with
  523. | TMono _ | TInst ({cl_kind = KTypeParameter _ },_) ->
  524. (match follow tret with
  525. | TAbstract ({ a_path = [],"Void" },_) -> e
  526. | _ -> raise (Unify_error []))
  527. | _ ->
  528. type_eq (if ctx.com.config.pf_static then EqDoNotFollowNull else EqStrict) etype tret;
  529. e)
  530. with Unify_error _ ->
  531. mk (TCast (e,None)) tret e.epos
  532. in
  533. let e = (match e.eexpr, init with
  534. | _, None when not !has_return_value ->
  535. {e with etype = tret}
  536. | TBlock [e] , None -> wrap e
  537. | _ , None -> wrap e
  538. | TBlock l, Some vl ->
  539. let el_v = List.map (fun (v,eo) -> mk (TVar (v,eo)) ctx.t.tvoid e.epos) vl in
  540. mk (TBlock (el_v @ l)) tret e.epos
  541. | _, Some vl ->
  542. let el_v = List.map (fun (v,eo) -> mk (TVar (v,eo)) ctx.t.tvoid e.epos) vl in
  543. mk (TBlock (el_v @ [e])) tret e.epos
  544. ) in
  545. let inline_meta e meta = match meta with
  546. | Meta.Deprecated,_,_ -> mk (TMeta(meta,e)) e.etype e.epos
  547. | _ -> e
  548. in
  549. let e = List.fold_left inline_meta e cf.cf_meta in
  550. (* we need to replace type-parameters that were used in the expression *)
  551. if not has_params then
  552. Some e
  553. else
  554. let mt = map_type cf.cf_type in
  555. let unify_func () = unify_raise ctx mt (TFun (List.map (fun e -> "",false,e.etype) params,tret)) p in
  556. (match follow ethis.etype with
  557. | TAnon a -> (match !(a.a_status) with
  558. | Statics {cl_kind = KAbstractImpl a } when Meta.has Meta.Impl cf.cf_meta ->
  559. if cf.cf_name <> "_new" then begin
  560. (* the first argument must unify with a_this for abstract implementation functions *)
  561. let tb = (TFun(("",false,map_type a.a_this) :: List.map (fun e -> "",false,e.etype) (List.tl params),tret)) in
  562. unify_raise ctx mt tb p
  563. end
  564. | _ -> unify_func())
  565. | _ -> unify_func());
  566. (*
  567. this is very expensive since we are building the substitution list for
  568. every expression, but hopefully in such cases the expression size is small
  569. *)
  570. let vars = Hashtbl.create 0 in
  571. let map_var v =
  572. if not (Hashtbl.mem vars v.v_id) then begin
  573. Hashtbl.add vars v.v_id ();
  574. v.v_type <- map_type v.v_type;
  575. end;
  576. v
  577. in
  578. let rec map_expr_type e = Type.map_expr_type map_expr_type map_type map_var e in
  579. Some (map_expr_type e)
  580. (* ---------------------------------------------------------------------- *)
  581. (* LOOPS *)
  582. let rec optimize_for_loop ctx (i,pi) e1 e2 p =
  583. let t_void = ctx.t.tvoid in
  584. let t_int = ctx.t.tint in
  585. let lblock el = Some (mk (TBlock el) t_void p) in
  586. let mk_field e n =
  587. TField (e,try quick_field e.etype n with Not_found -> assert false)
  588. in
  589. let gen_int_iter pt f_get f_length =
  590. let i = add_local ctx i pt in
  591. let index = gen_local ctx t_int in
  592. let arr, avars = (match e1.eexpr with
  593. | TLocal _ -> e1, None
  594. | _ ->
  595. let atmp = gen_local ctx e1.etype in
  596. mk (TLocal atmp) e1.etype e1.epos, (Some (atmp,Some e1))
  597. ) in
  598. let iexpr = mk (TLocal index) t_int p in
  599. let e2 = type_expr ctx e2 NoValue in
  600. let aget = mk (TVar (i,Some (f_get arr iexpr pt p))) t_void pi in
  601. let incr = mk (TUnop (Increment,Prefix,iexpr)) t_int p in
  602. let block = match e2.eexpr with
  603. | TBlock el -> mk (TBlock (aget :: incr :: el)) t_void e2.epos
  604. | _ -> mk (TBlock [aget;incr;e2]) t_void p
  605. in
  606. let ivar = Some (mk (TConst (TInt 0l)) t_int p) in
  607. let elength = f_length arr p in
  608. let el = [mk (TWhile (
  609. mk (TBinop (OpLt, iexpr, elength)) ctx.t.tbool p,
  610. block,
  611. NormalWhile
  612. )) t_void p;
  613. ] in
  614. let el = match avars with None -> el | Some (v,eo) -> (mk (TVar (v,eo)) t_void p) :: el in
  615. let el = (mk (TVar (index,ivar)) t_void p) :: el in
  616. lblock el
  617. in
  618. let get_next_array_element arr iexpr pt p =
  619. (mk (TArray (arr,iexpr)) pt p)
  620. in
  621. let get_array_length arr p =
  622. mk (mk_field arr "length") ctx.com.basic.tint p
  623. in
  624. match e1.eexpr, follow e1.etype with
  625. | TNew ({ cl_path = ([],"IntIterator") },[],[i1;i2]) , _ ->
  626. let max = (match i1.eexpr , i2.eexpr with
  627. | TConst (TInt a), TConst (TInt b) when Int32.compare b a < 0 -> error "Range operator can't iterate backwards" p
  628. | _, TConst _ | _ , TLocal _ -> None
  629. | _ -> Some (gen_local ctx t_int)
  630. ) in
  631. let tmp = gen_local ctx t_int in
  632. let i = add_local ctx i t_int in
  633. let rec check e =
  634. match e.eexpr with
  635. | TBinop (OpAssign,{ eexpr = TLocal l },_)
  636. | TBinop (OpAssignOp _,{ eexpr = TLocal l },_)
  637. | TUnop (Increment,_,{ eexpr = TLocal l })
  638. | TUnop (Decrement,_,{ eexpr = TLocal l }) when l == i ->
  639. error "Loop variable cannot be modified" e.epos
  640. | _ ->
  641. Type.iter check e
  642. in
  643. let e2 = type_expr ctx e2 NoValue in
  644. check e2;
  645. let etmp = mk (TLocal tmp) t_int p in
  646. let incr = mk (TUnop (Increment,Postfix,etmp)) t_int p in
  647. let init = mk (TVar (i,Some incr)) t_void pi in
  648. let block = match e2.eexpr with
  649. | TBlock el -> mk (TBlock (init :: el)) t_void e2.epos
  650. | _ -> mk (TBlock [init;e2]) t_void p
  651. in
  652. (*
  653. force locals to be of Int type (to prevent Int/UInt issues)
  654. *)
  655. let i2 = match follow i2.etype with
  656. | TAbstract ({ a_path = ([],"Int") }, []) -> i2
  657. | _ -> { i2 with eexpr = TCast(i2, None); etype = t_int }
  658. in
  659. (match max with
  660. | None ->
  661. lblock [
  662. mk (TVar (tmp,Some i1)) t_void p;
  663. mk (TWhile (
  664. mk (TBinop (OpLt, etmp, i2)) ctx.t.tbool p,
  665. block,
  666. NormalWhile
  667. )) t_void p;
  668. ]
  669. | Some max ->
  670. lblock [
  671. mk (TVar (tmp,Some i1)) t_void p;
  672. mk (TVar (max,Some i2)) t_void p;
  673. mk (TWhile (
  674. mk (TBinop (OpLt, etmp, mk (TLocal max) t_int p)) ctx.t.tbool p,
  675. block,
  676. NormalWhile
  677. )) t_void p;
  678. ])
  679. | TArrayDecl el, TInst({ cl_path = [],"Array" },[pt]) when false ->
  680. begin try
  681. let num_expr = ref 0 in
  682. let rec loop e = match fst e with
  683. | EContinue | EBreak ->
  684. raise Exit
  685. | _ ->
  686. incr num_expr;
  687. Ast.map_expr loop e
  688. in
  689. ignore(loop e2);
  690. let v = add_local ctx i pt in
  691. let e2 = type_expr ctx e2 NoValue in
  692. let cost = (List.length el) * !num_expr in
  693. let max_cost = try
  694. int_of_string (Common.defined_value ctx.com Define.LoopUnrollMaxCost)
  695. with Not_found ->
  696. 250
  697. in
  698. if cost > max_cost then raise Exit;
  699. let eloc = mk (TLocal v) v.v_type p in
  700. let el = List.map (fun e ->
  701. let e_assign = mk (TBinop(OpAssign,eloc,e)) e.etype e.epos in
  702. concat e_assign e2
  703. ) el in
  704. let ev = mk (TVar(v, None)) ctx.t.tvoid p in
  705. Some (mk (TBlock (ev :: el)) ctx.t.tvoid p)
  706. with Exit ->
  707. gen_int_iter pt get_next_array_element get_array_length
  708. end
  709. | _ , TInst({ cl_path = [],"Array" },[pt])
  710. | _ , TInst({ cl_path = ["flash"],"Vector" },[pt]) ->
  711. gen_int_iter pt get_next_array_element get_array_length
  712. | _ , TInst({ cl_array_access = Some pt } as c,pl) when (try match follow (PMap.find "length" c.cl_fields).cf_type with TAbstract ({ a_path = [],"Int" },[]) -> true | _ -> false with Not_found -> false) && not (PMap.mem "iterator" c.cl_fields) ->
  713. gen_int_iter (apply_params c.cl_params pl pt) get_next_array_element get_array_length
  714. | _, TAbstract({a_impl = Some c} as a,tl) ->
  715. begin try
  716. let cf_length = PMap.find "get_length" c.cl_statics in
  717. let get_length e p =
  718. make_static_call ctx c cf_length (apply_params a.a_params tl) [e] ctx.com.basic.tint p
  719. in
  720. begin match follow cf_length.cf_type with
  721. | TFun(_,tr) ->
  722. begin match follow tr with
  723. | TAbstract({a_path = [],"Int"},_) -> ()
  724. | _ -> raise Not_found
  725. end
  726. | _ ->
  727. raise Not_found
  728. end;
  729. begin try
  730. (* first try: do we have an @:arrayAccess getter field? *)
  731. let todo = mk (TConst TNull) ctx.t.tint p in
  732. let cf,_,r,_,_ = (!find_array_access_raise_ref) ctx a tl todo None p in
  733. let get_next e_base e_index t p =
  734. make_static_call ctx c cf (apply_params a.a_params tl) [e_base;e_index] r p
  735. in
  736. gen_int_iter r get_next get_length
  737. with Not_found ->
  738. (* second try: do we have @:arrayAccess on the abstract itself? *)
  739. if not (Meta.has Meta.ArrayAccess a.a_meta) then raise Not_found;
  740. (* let's allow this only for core-type abstracts *)
  741. if not (Meta.has Meta.CoreType a.a_meta) then raise Not_found;
  742. (* in which case we assume that a singular type parameter is the element type *)
  743. let t = match tl with [t] -> t | _ -> raise Not_found in
  744. gen_int_iter t get_next_array_element get_length
  745. end with Not_found ->
  746. None
  747. end
  748. | _ , TInst ({ cl_kind = KGenericInstance ({ cl_path = ["haxe";"ds"],"GenericStack" },[t]) } as c,[]) ->
  749. let tcell = (try (PMap.find "head" c.cl_fields).cf_type with Not_found -> assert false) in
  750. let i = add_local ctx i t in
  751. let cell = gen_local ctx tcell in
  752. let cexpr = mk (TLocal cell) tcell p in
  753. let e2 = type_expr ctx e2 NoValue in
  754. let evar = mk (TVar (i,Some (mk (mk_field cexpr "elt") t p))) t_void pi in
  755. let enext = mk (TBinop (OpAssign,cexpr,mk (mk_field cexpr "next") tcell p)) tcell p in
  756. let block = match e2.eexpr with
  757. | TBlock el -> mk (TBlock (evar :: enext :: el)) t_void e2.epos
  758. | _ -> mk (TBlock [evar;enext;e2]) t_void p
  759. in
  760. lblock [
  761. mk (TVar (cell,Some (mk (mk_field e1 "head") tcell p))) t_void p;
  762. mk (TWhile (
  763. mk (TBinop (OpNotEq, cexpr, mk (TConst TNull) tcell p)) ctx.t.tbool p,
  764. block,
  765. NormalWhile
  766. )) t_void p
  767. ]
  768. | _ ->
  769. None
  770. let optimize_for_loop_iterator ctx v e1 e2 p =
  771. let c,tl = (match follow e1.etype with TInst (c,pl) -> c,pl | _ -> raise Exit) in
  772. let _, _, fhasnext = (try raw_class_field (fun cf -> apply_params c.cl_params tl cf.cf_type) c tl "hasNext" with Not_found -> raise Exit) in
  773. if fhasnext.cf_kind <> Method MethInline then raise Exit;
  774. let tmp = gen_local ctx e1.etype in
  775. let eit = mk (TLocal tmp) e1.etype p in
  776. let ehasnext = make_call ctx (mk (TField (eit,FInstance (c, tl, fhasnext))) (TFun([],ctx.t.tbool)) p) [] ctx.t.tbool p in
  777. let enext = mk (TVar (v,Some (make_call ctx (mk (TField (eit,quick_field_dynamic eit.etype "next")) (TFun ([],v.v_type)) p) [] v.v_type p))) ctx.t.tvoid p in
  778. let eblock = (match e2.eexpr with
  779. | TBlock el -> { e2 with eexpr = TBlock (enext :: el) }
  780. | _ -> mk (TBlock [enext;e2]) ctx.t.tvoid p
  781. ) in
  782. mk (TBlock [
  783. mk (TVar (tmp,Some e1)) ctx.t.tvoid p;
  784. mk (TWhile (ehasnext,eblock,NormalWhile)) ctx.t.tvoid p
  785. ]) ctx.t.tvoid p
  786. (* ---------------------------------------------------------------------- *)
  787. (* SANITIZE *)
  788. (*
  789. makes sure that when an AST get generated to source code, it will not
  790. generate expressions that evaluate differently. It is then necessary to
  791. add parenthesises around some binary expressions when the AST does not
  792. correspond to the natural operand priority order for the platform
  793. *)
  794. (*
  795. this is the standard C++ operator precedence, which is also used by both JS and PHP
  796. *)
  797. let standard_precedence op =
  798. let left = true and right = false in
  799. match op with
  800. | OpMult | OpDiv | OpMod -> 5, left
  801. | OpAdd | OpSub -> 6, left
  802. | OpShl | OpShr | OpUShr -> 7, left
  803. | OpLt | OpLte | OpGt | OpGte -> 8, left
  804. | OpEq | OpNotEq -> 9, left
  805. | OpAnd -> 10, left
  806. | OpXor -> 11, left
  807. | OpOr -> 12, left
  808. | OpInterval -> 13, right (* haxe specific *)
  809. | OpBoolAnd -> 14, left
  810. | OpBoolOr -> 15, left
  811. | OpArrow -> 16, left
  812. | OpAssignOp OpAssign -> 17, right (* mimics ?: *)
  813. | OpAssign | OpAssignOp _ -> 18, right
  814. let rec need_parent e =
  815. match e.eexpr with
  816. | TConst _ | TLocal _ | TArray _ | TField _ | TEnumParameter _ | TParenthesis _ | TMeta _ | TCall _ | TNew _ | TTypeExpr _ | TObjectDecl _ | TArrayDecl _ -> false
  817. | TCast (e,None) -> need_parent e
  818. | TCast _ | TThrow _ | TReturn _ | TTry _ | TSwitch _ | TFor _ | TIf _ | TWhile _ | TBinop _ | TContinue | TBreak
  819. | TBlock _ | TVar _ | TFunction _ | TUnop _ -> true
  820. let sanitize_expr com e =
  821. let parent e =
  822. match e.eexpr with
  823. | TParenthesis _ -> e
  824. | _ -> mk (TParenthesis e) e.etype e.epos
  825. in
  826. let block e =
  827. match e.eexpr with
  828. | TBlock _ -> e
  829. | _ -> mk (TBlock [e]) e.etype e.epos
  830. in
  831. let complex e =
  832. (* complex expressions are the one that once generated to source consists in several expressions *)
  833. match e.eexpr with
  834. | TVar _ (* needs to be put into blocks *)
  835. | TFor _ (* a temp var is needed for holding iterator *)
  836. | TCall ({ eexpr = TLocal { v_name = "__js__" } },_) (* we never know *)
  837. -> block e
  838. | _ -> e
  839. in
  840. (* tells if the printed expresssion ends with an if without else *)
  841. let rec has_if e =
  842. match e.eexpr with
  843. | TIf (_,_,None) -> true
  844. | TWhile (_,e,NormalWhile) -> has_if e
  845. | TFor (_,_,e) -> has_if e
  846. | _ -> false
  847. in
  848. match e.eexpr with
  849. | TConst TNull ->
  850. if com.config.pf_static && not (is_nullable e.etype) then begin
  851. let rec loop t = match follow t with
  852. | TMono _ -> () (* in these cases the null will cast to default value *)
  853. | TFun _ -> () (* this is a bit a particular case, maybe flash-specific actually *)
  854. (* TODO: this should use get_underlying_type, but we do not have access to Codegen here. *)
  855. | TAbstract(a,tl) when not (Meta.has Meta.CoreType a.a_meta) -> loop (apply_params a.a_params tl a.a_this)
  856. | _ -> com.error ("On static platforms, null can't be used as basic type " ^ s_type (print_context()) e.etype) e.epos
  857. in
  858. loop e.etype
  859. end;
  860. e
  861. | TBinop (op,e1,e2) ->
  862. let swap op1 op2 =
  863. let p1, left1 = standard_precedence op1 in
  864. let p2, _ = standard_precedence op2 in
  865. left1 && p1 <= p2
  866. in
  867. let rec loop ee left =
  868. match ee.eexpr with
  869. | TBinop (op2,_,_) -> if left then not (swap op2 op) else swap op op2
  870. | TIf _ -> if left then not (swap (OpAssignOp OpAssign) op) else swap op (OpAssignOp OpAssign)
  871. | TCast (e,None) -> loop e left
  872. | _ -> false
  873. in
  874. let e1 = if loop e1 true then parent e1 else e1 in
  875. let e2 = if loop e2 false then parent e2 else e2 in
  876. { e with eexpr = TBinop (op,e1,e2) }
  877. | TUnop (op,mode,e1) ->
  878. let rec loop ee =
  879. match ee.eexpr with
  880. | TBinop _ | TIf _ | TUnop _ -> parent e1
  881. | TCast (e,None) -> loop e
  882. | _ -> e1
  883. in
  884. { e with eexpr = TUnop (op,mode,loop e1)}
  885. | TIf (e1,e2,eelse) ->
  886. let e1 = parent e1 in
  887. let e2 = (if (eelse <> None && has_if e2) || (match e2.eexpr with TIf _ -> true | _ -> false) then block e2 else complex e2) in
  888. let eelse = (match eelse with None -> None | Some e -> Some (complex e)) in
  889. { e with eexpr = TIf (e1,e2,eelse) }
  890. | TWhile (e1,e2,flag) ->
  891. let e1 = parent e1 in
  892. let e2 = complex e2 in
  893. { e with eexpr = TWhile (e1,e2,flag) }
  894. | TFor (v,e1,e2) ->
  895. let e2 = complex e2 in
  896. { e with eexpr = TFor (v,e1,e2) }
  897. | TFunction f ->
  898. let f = (match f.tf_expr.eexpr with
  899. | TBlock _ -> f
  900. | _ -> { f with tf_expr = block f.tf_expr }
  901. ) in
  902. { e with eexpr = TFunction f }
  903. | TCall (e2,args) ->
  904. if need_parent e2 then { e with eexpr = TCall(parent e2,args) } else e
  905. | TEnumParameter (e2,ef,i) ->
  906. if need_parent e2 then { e with eexpr = TEnumParameter(parent e2,ef,i) } else e
  907. | TField (e2,f) ->
  908. if need_parent e2 then { e with eexpr = TField(parent e2,f) } else e
  909. | TArray (e1,e2) ->
  910. if need_parent e1 then { e with eexpr = TArray(parent e1,e2) } else e
  911. | TTry (e1,catches) ->
  912. let e1 = block e1 in
  913. let catches = List.map (fun (v,e) -> v, block e) catches in
  914. { e with eexpr = TTry (e1,catches) }
  915. | TSwitch (e1,cases,def) ->
  916. let e1 = parent e1 in
  917. let cases = List.map (fun (el,e) -> el, complex e) cases in
  918. let def = (match def with None -> None | Some e -> Some (complex e)) in
  919. { e with eexpr = TSwitch (e1,cases,def) }
  920. | _ ->
  921. e
  922. let reduce_expr com e =
  923. match e.eexpr with
  924. | TSwitch (_,cases,_) ->
  925. List.iter (fun (cl,_) ->
  926. List.iter (fun e ->
  927. match e.eexpr with
  928. | TCall ({ eexpr = TField (_,FEnum _) },_) -> error "Not-constant enum in switch cannot be matched" e.epos
  929. | _ -> ()
  930. ) cl
  931. ) cases;
  932. e
  933. | TBlock l ->
  934. (match List.rev l with
  935. | [] -> e
  936. | ec :: l ->
  937. (* remove all no-ops : not-final constants in blocks *)
  938. match List.filter (fun e -> match e.eexpr with
  939. | TConst _
  940. | TBlock []
  941. | TObjectDecl [] ->
  942. false
  943. | _ ->
  944. true
  945. ) l with
  946. | [] -> ec
  947. | l -> { e with eexpr = TBlock (List.rev (ec :: l)) })
  948. | TParenthesis ec ->
  949. { ec with epos = e.epos }
  950. | TTry (e,[]) ->
  951. e
  952. | _ ->
  953. e
  954. let rec sanitize com e =
  955. sanitize_expr com (reduce_expr com (Type.map_expr (sanitize com) e))
  956. (* ---------------------------------------------------------------------- *)
  957. (* REDUCE *)
  958. let optimize_binop e op e1 e2 =
  959. let is_float t =
  960. match follow t with
  961. | TAbstract({ a_path = [],"Float" },_) -> true
  962. | _ -> false
  963. in
  964. let is_numeric t =
  965. match follow t with
  966. | TAbstract({ a_path = [],("Float"|"Int") },_) -> true
  967. | _ -> false
  968. in
  969. let check_float op f1 f2 =
  970. let f = op f1 f2 in
  971. let fstr = float_repres f in
  972. if (match classify_float f with FP_nan | FP_infinite -> false | _ -> float_of_string fstr = f) then { e with eexpr = TConst (TFloat fstr) } else e
  973. in
  974. (match e1.eexpr, e2.eexpr with
  975. | TConst (TInt 0l) , _ when op = OpAdd && is_numeric e2.etype -> e2
  976. | TConst (TInt 1l) , _ when op = OpMult -> e2
  977. | TConst (TFloat v) , _ when op = OpAdd && float_of_string v = 0. && is_float e2.etype -> e2
  978. | TConst (TFloat v) , _ when op = OpMult && float_of_string v = 1. && is_float e2.etype -> e2
  979. | _ , TConst (TInt 0l) when (match op with OpAdd -> is_numeric e1.etype | OpSub | OpShr | OpShl -> true | _ -> false) -> e1 (* bits operations might cause overflow *)
  980. | _ , TConst (TInt 1l) when op = OpMult -> e1
  981. | _ , TConst (TFloat v) when (match op with OpAdd | OpSub -> float_of_string v = 0. && is_float e1.etype | _ -> false) -> e1 (* bits operations might cause overflow *)
  982. | _ , TConst (TFloat v) when op = OpMult && float_of_string v = 1. && is_float e1.etype -> e1
  983. | TConst TNull, TConst TNull ->
  984. (match op with
  985. | OpEq -> { e with eexpr = TConst (TBool true) }
  986. | OpNotEq -> { e with eexpr = TConst (TBool false) }
  987. | _ -> e)
  988. | TFunction _, TConst TNull ->
  989. (match op with
  990. | OpEq -> { e with eexpr = TConst (TBool false) }
  991. | OpNotEq -> { e with eexpr = TConst (TBool true) }
  992. | _ -> e)
  993. | TConst TNull, TFunction _ ->
  994. (match op with
  995. | OpEq -> { e with eexpr = TConst (TBool false) }
  996. | OpNotEq -> { e with eexpr = TConst (TBool true) }
  997. | _ -> e)
  998. | TConst (TInt a), TConst (TInt b) ->
  999. let opt f = try { e with eexpr = TConst (TInt (f a b)) } with Exit -> e in
  1000. let check_overflow f =
  1001. opt (fun a b ->
  1002. let v = f (Int64.of_int32 a) (Int64.of_int32 b) in
  1003. let iv = Int64.to_int32 v in
  1004. if Int64.compare (Int64.of_int32 iv) v <> 0 then raise Exit;
  1005. iv
  1006. )
  1007. in
  1008. let ebool t =
  1009. { e with eexpr = TConst (TBool (t (Int32.compare a b) 0)) }
  1010. in
  1011. (match op with
  1012. | OpAdd -> check_overflow Int64.add
  1013. | OpSub -> check_overflow Int64.sub
  1014. | OpMult -> check_overflow Int64.mul
  1015. | OpDiv -> check_float ( /. ) (Int32.to_float a) (Int32.to_float b)
  1016. | OpAnd -> opt Int32.logand
  1017. | OpOr -> opt Int32.logor
  1018. | OpXor -> opt Int32.logxor
  1019. | OpShl -> opt (fun a b -> Int32.shift_left a (Int32.to_int b))
  1020. | OpShr -> opt (fun a b -> Int32.shift_right a (Int32.to_int b))
  1021. | OpUShr -> opt (fun a b -> Int32.shift_right_logical a (Int32.to_int b))
  1022. | OpEq -> ebool (=)
  1023. | OpNotEq -> ebool (<>)
  1024. | OpGt -> ebool (>)
  1025. | OpGte -> ebool (>=)
  1026. | OpLt -> ebool (<)
  1027. | OpLte -> ebool (<=)
  1028. | _ -> e)
  1029. | TConst ((TFloat _ | TInt _) as ca), TConst ((TFloat _ | TInt _) as cb) ->
  1030. let fa = (match ca with
  1031. | TFloat a -> float_of_string a
  1032. | TInt a -> Int32.to_float a
  1033. | _ -> assert false
  1034. ) in
  1035. let fb = (match cb with
  1036. | TFloat b -> float_of_string b
  1037. | TInt b -> Int32.to_float b
  1038. | _ -> assert false
  1039. ) in
  1040. let fop op = check_float op fa fb in
  1041. let ebool t =
  1042. { e with eexpr = TConst (TBool (t (compare fa fb) 0)) }
  1043. in
  1044. (match op with
  1045. | OpAdd -> fop (+.)
  1046. | OpDiv -> fop (/.)
  1047. | OpSub -> fop (-.)
  1048. | OpMult -> fop ( *. )
  1049. | OpEq -> ebool (=)
  1050. | OpNotEq -> ebool (<>)
  1051. | OpGt -> ebool (>)
  1052. | OpGte -> ebool (>=)
  1053. | OpLt -> ebool (<)
  1054. | OpLte -> ebool (<=)
  1055. | _ -> e)
  1056. | TConst (TBool a), TConst (TBool b) ->
  1057. let ebool f =
  1058. { e with eexpr = TConst (TBool (f a b)) }
  1059. in
  1060. (match op with
  1061. | OpEq -> ebool (=)
  1062. | OpNotEq -> ebool (<>)
  1063. | OpBoolAnd -> ebool (&&)
  1064. | OpBoolOr -> ebool (||)
  1065. | _ -> e)
  1066. | TConst a, TConst b when op = OpEq || op = OpNotEq ->
  1067. let ebool b =
  1068. { e with eexpr = TConst (TBool (if op = OpEq then b else not b)) }
  1069. in
  1070. (match a, b with
  1071. | TInt a, TFloat b | TFloat b, TInt a -> ebool (Int32.to_float a = float_of_string b)
  1072. | _ -> ebool (a = b))
  1073. | TConst (TBool a), _ ->
  1074. (match op with
  1075. | OpBoolAnd -> if a then e2 else { e with eexpr = TConst (TBool false) }
  1076. | OpBoolOr -> if a then { e with eexpr = TConst (TBool true) } else e2
  1077. | _ -> e)
  1078. | _ , TConst (TBool a) ->
  1079. (match op with
  1080. | OpBoolAnd when a -> e1
  1081. | OpBoolOr when not a -> e1
  1082. | _ -> e)
  1083. | TField (_,FEnum (e1,f1)), TField (_,FEnum (e2,f2)) when e1 == e2 ->
  1084. (match op with
  1085. | OpEq -> { e with eexpr = TConst (TBool (f1 == f2)) }
  1086. | OpNotEq -> { e with eexpr = TConst (TBool (f1 != f2)) }
  1087. | _ -> e)
  1088. | _, TCall ({ eexpr = TField (_,FEnum _) },_) | TCall ({ eexpr = TField (_,FEnum _) },_), _ ->
  1089. (match op with
  1090. | OpAssign -> e
  1091. | _ ->
  1092. error "You cannot directly compare enums with arguments. Use either 'switch' or 'Type.enumEq'" e.epos)
  1093. | _ ->
  1094. e)
  1095. let optimize_unop e op flag esub =
  1096. match op, esub.eexpr with
  1097. | Not, (TConst (TBool f) | TParenthesis({eexpr = TConst (TBool f)})) -> { e with eexpr = TConst (TBool (not f)) }
  1098. | Neg, TConst (TInt i) -> { e with eexpr = TConst (TInt (Int32.neg i)) }
  1099. | NegBits, TConst (TInt i) -> { e with eexpr = TConst (TInt (Int32.lognot i)) }
  1100. | Neg, TConst (TFloat f) ->
  1101. let v = 0. -. float_of_string f in
  1102. let vstr = float_repres v in
  1103. if float_of_string vstr = v then
  1104. { e with eexpr = TConst (TFloat vstr) }
  1105. else
  1106. e
  1107. | _ -> e
  1108. let rec reduce_loop ctx e =
  1109. let e = Type.map_expr (reduce_loop ctx) e in
  1110. sanitize_expr ctx.com (match e.eexpr with
  1111. | TIf ({ eexpr = TConst (TBool t) },e1,e2) ->
  1112. (if t then e1 else match e2 with None -> { e with eexpr = TBlock [] } | Some e -> e)
  1113. | TWhile ({ eexpr = TConst (TBool false) },sub,flag) ->
  1114. (match flag with
  1115. | NormalWhile -> { e with eexpr = TBlock [] } (* erase sub *)
  1116. | DoWhile -> e) (* we cant remove while since sub can contain continue/break *)
  1117. | TBinop (op,e1,e2) ->
  1118. optimize_binop e op e1 e2
  1119. | TUnop (op,flag,esub) ->
  1120. optimize_unop e op flag esub
  1121. | TCall ({ eexpr = TField ({ eexpr = TTypeExpr (TClassDecl c) },field) },params) ->
  1122. (match api_inline ctx c (field_name field) params e.epos with
  1123. | None -> reduce_expr ctx e
  1124. | Some e -> reduce_loop ctx e)
  1125. | TCall ({ eexpr = TFunction func } as ef,el) ->
  1126. let cf = mk_field "" ef.etype e.epos in
  1127. let ethis = mk (TConst TThis) t_dynamic e.epos in
  1128. let rt = (match follow ef.etype with TFun (_,rt) -> rt | _ -> assert false) in
  1129. let inl = (try type_inline ctx cf func ethis el rt None e.epos ~self_calling_closure:true false with Error (Custom _,_) -> None) in
  1130. (match inl with
  1131. | None -> reduce_expr ctx e
  1132. | Some e -> reduce_loop ctx e)
  1133. | TCall ({ eexpr = TField (o,FClosure (c,cf)) } as f,el) ->
  1134. let fmode = (match c with None -> FAnon cf | Some (c,tl) -> FInstance (c,tl,cf)) in
  1135. { e with eexpr = TCall ({ f with eexpr = TField (o,fmode) },el) }
  1136. | TSwitch (e1,[[{eexpr = TConst (TBool true)}],{eexpr = TConst (TBool true)}],Some ({eexpr = TConst (TBool false)})) ->
  1137. (* introduced by extractors in some cases *)
  1138. e1
  1139. | _ ->
  1140. reduce_expr ctx e)
  1141. let reduce_expression ctx e =
  1142. if ctx.com.foptimize then reduce_loop ctx e else e
  1143. let rec make_constant_expression ctx ?(concat_strings=false) e =
  1144. let e = reduce_loop ctx e in
  1145. match e.eexpr with
  1146. | TConst _ -> Some e
  1147. | TBinop ((OpAdd|OpSub|OpMult|OpDiv|OpMod) as op,e1,e2) -> (match make_constant_expression ctx e1,make_constant_expression ctx e2 with
  1148. | Some ({eexpr = TConst (TString s1)}), Some ({eexpr = TConst (TString s2)}) when concat_strings ->
  1149. Some (mk (TConst (TString (s1 ^ s2))) ctx.com.basic.tstring (punion e1.epos e2.epos))
  1150. | Some e1, Some e2 -> Some (mk (TBinop(op, e1, e2)) e.etype e.epos)
  1151. | _ -> None)
  1152. | TCast (e1, None) ->
  1153. (match make_constant_expression ctx e1 with
  1154. | None -> None
  1155. | Some e1 -> Some {e with eexpr = TCast(e1,None)})
  1156. | TParenthesis e1 ->
  1157. begin match make_constant_expression ctx ~concat_strings e1 with
  1158. | None -> None
  1159. | Some e1 -> Some {e with eexpr = TParenthesis e1}
  1160. end
  1161. | TMeta(m,e1) ->
  1162. begin match make_constant_expression ctx ~concat_strings e1 with
  1163. | None -> None
  1164. | Some e1 -> Some {e with eexpr = TMeta(m,e1)}
  1165. end
  1166. | TTypeExpr _ -> Some e
  1167. (* try to inline static function calls *)
  1168. | TCall ({ etype = TFun(_,ret); eexpr = TField (_,FStatic (c,cf)) },el) ->
  1169. (try
  1170. let func = match cf.cf_expr with Some ({eexpr = TFunction func}) -> func | _ -> raise Not_found in
  1171. let ethis = mk (TConst TThis) t_dynamic e.epos in
  1172. let inl = (try type_inline ctx cf func ethis el ret None e.epos false with Error (Custom _,_) -> None) in
  1173. (match inl with
  1174. | None -> None
  1175. | Some e -> make_constant_expression ctx e)
  1176. with Not_found -> None)
  1177. | _ -> None
  1178. (* ---------------------------------------------------------------------- *)
  1179. (* INLINE CONSTRUCTORS *)
  1180. (*
  1181. First pass :
  1182. We will look at local variables in the form var v = new ....
  1183. we only capture the ones which have constructors marked as inlined
  1184. then we make sure that these locals are no more referenced except for fields accesses
  1185. Second pass :
  1186. We replace the variables by their fields lists, and the corresponding fields accesses as well
  1187. *)
  1188. type inline_kind =
  1189. | IKCtor of tfunc * tclass_field * tclass * t list * texpr list * texpr list
  1190. | IKArray of texpr list * t
  1191. | IKStructure of (string * texpr) list
  1192. | IKNone
  1193. let inline_constructors ctx e =
  1194. let vars = ref PMap.empty in
  1195. let is_valid_ident s =
  1196. try
  1197. if String.length s = 0 then raise Exit;
  1198. begin match String.unsafe_get s 0 with
  1199. | 'a'..'z' | 'A'..'Z' | '_' -> ()
  1200. | _ -> raise Exit
  1201. end;
  1202. for i = 1 to String.length s - 1 do
  1203. match String.unsafe_get s i with
  1204. | 'a'..'z' | 'A'..'Z' | '_' -> ()
  1205. | '0'..'9' when i > 0 -> ()
  1206. | _ -> raise Exit
  1207. done;
  1208. true
  1209. with Exit ->
  1210. false
  1211. in
  1212. let rec get_inline_ctor_info e = match e.eexpr with
  1213. | TNew ({ cl_constructor = Some ({ cf_kind = Method MethInline; cf_expr = Some { eexpr = TFunction f } } as cst) } as c,tl,pl) ->
  1214. IKCtor (f,cst,c,tl,pl,[])
  1215. | TObjectDecl [] | TArrayDecl [] ->
  1216. IKNone
  1217. | TArrayDecl el ->
  1218. begin match follow e.etype with
  1219. | TInst({cl_path = [],"Array"},[t]) ->
  1220. IKArray(el,t)
  1221. | _ ->
  1222. IKNone
  1223. end
  1224. | TObjectDecl fl ->
  1225. if (List.exists (fun (s,_) -> not (is_valid_ident s)) fl) then
  1226. IKNone
  1227. else
  1228. IKStructure fl
  1229. | TCast(e,None) | TParenthesis e ->
  1230. get_inline_ctor_info e
  1231. | TBlock el ->
  1232. begin match List.rev el with
  1233. | e :: el ->
  1234. begin match get_inline_ctor_info e with
  1235. | IKCtor(f,cst,c,tl,pl,e_init) ->
  1236. IKCtor(f,cst,c,tl,pl,(List.rev el) @ e_init)
  1237. | _ ->
  1238. IKNone
  1239. end
  1240. | [] ->
  1241. IKNone
  1242. end
  1243. | _ ->
  1244. IKNone
  1245. in
  1246. let check_field v s e t =
  1247. let (a,b,fields,c,d) = PMap.find (-v.v_id) !vars in
  1248. if not (List.exists (fun (s2,_,_) -> s = s2) fields) then
  1249. vars := PMap.add (-v.v_id) (a,b,(s,e,t) :: fields,c,d) !vars
  1250. in
  1251. let cancel v =
  1252. v.v_id <- -v.v_id;
  1253. (* error if the constructor is extern *)
  1254. (match PMap.find v.v_id !vars with
  1255. | _,_,_,true,p ->
  1256. display_error ctx "Extern constructor could not be inlined" p;
  1257. error "Variable is used here" e.epos
  1258. | _ -> ());
  1259. vars := PMap.remove v.v_id !vars;
  1260. in
  1261. let rec skip_to_var e = match e.eexpr with
  1262. | TLocal v when v.v_id < 0 -> Some v
  1263. (* | TCast(e1,None) | TMeta(_,e1) | TParenthesis(e1) -> skip_to_var e1 *)
  1264. | _ -> None
  1265. in
  1266. let rec find_locals e =
  1267. match e.eexpr with
  1268. | TVar (v,eo) ->
  1269. Type.iter find_locals e;
  1270. begin match eo with
  1271. | Some n ->
  1272. begin match get_inline_ctor_info n with
  1273. | IKCtor (f,cst,c,tl,pl,el_init) when type_iseq v.v_type n.etype ->
  1274. (* inline the constructor *)
  1275. (match (try type_inline ctx cst f (mk (TLocal v) (TInst (c,tl)) n.epos) pl ctx.t.tvoid None n.epos true with Error (Custom _,_) -> None) with
  1276. | None -> ()
  1277. | Some ecst ->
  1278. let assigns = ref [] in
  1279. (* add field inits here because the filter has not run yet (issue #2336) *)
  1280. List.iter (fun cf -> match cf.cf_kind,cf.cf_expr with
  1281. | Var _,Some e -> assigns := (cf.cf_name,e,cf.cf_type) :: !assigns
  1282. | _ -> ()
  1283. ) c.cl_ordered_fields;
  1284. (* make sure we only have v.field = expr calls *)
  1285. let rec get_assigns e =
  1286. match e.eexpr with
  1287. | TBlock el ->
  1288. List.iter get_assigns el
  1289. | TBinop (OpAssign, { eexpr = TField ({ eexpr = TLocal vv },FInstance(_,_,cf)); etype = t }, e) when v == vv ->
  1290. assigns := (cf.cf_name,e,t) :: !assigns
  1291. | _ ->
  1292. raise Exit
  1293. in
  1294. try
  1295. get_assigns ecst;
  1296. (* mark variable as candidate for inlining *)
  1297. vars := PMap.add v.v_id (v,el_init,List.rev !assigns,c.cl_extern || Meta.has Meta.Extern cst.cf_meta,n.epos) !vars;
  1298. v.v_id <- -v.v_id; (* mark *)
  1299. (* recurse with the constructor code which will be inlined here *)
  1300. find_locals ecst
  1301. with Exit ->
  1302. ())
  1303. | IKArray (el,t) ->
  1304. vars := PMap.add v.v_id (v,[],ExtList.List.mapi (fun i e -> string_of_int i,e,t) el, false, n.epos) !vars;
  1305. v.v_id <- -v.v_id;
  1306. | IKStructure fl ->
  1307. vars := PMap.add v.v_id (v,[],List.map (fun (s,e) -> s,e,e.etype) fl, false, n.epos) !vars;
  1308. v.v_id <- -v.v_id;
  1309. | _ ->
  1310. ()
  1311. end
  1312. | _ -> ()
  1313. end
  1314. | TField(e1, (FInstance(_, _, {cf_kind = Var _; cf_name = s}) | FAnon({cf_kind = Var _; cf_name = s}))) ->
  1315. (match skip_to_var e1 with None -> find_locals e1 | Some _ -> ())
  1316. | TArray (e1,{eexpr = TConst (TInt i)}) ->
  1317. begin match skip_to_var e1 with
  1318. | None -> find_locals e1
  1319. | Some v ->
  1320. let (_,_,fields,_,_) = PMap.find (-v.v_id) !vars in
  1321. let i = Int32.to_int i in
  1322. if i < 0 || i >= List.length fields then cancel v
  1323. end
  1324. | TBinop((OpAssign | OpAssignOp _),e1,e2) ->
  1325. begin match e1.eexpr with
  1326. | TArray ({eexpr = TLocal v},{eexpr = TConst (TInt i)}) when v.v_id < 0 ->
  1327. check_field v (Int32.to_string i) e2 e2.etype
  1328. | TField({eexpr = TLocal v}, (FInstance(_, _, {cf_kind = Var _; cf_name = s}) | FAnon({cf_kind = Var _; cf_name = s}))) when v.v_id < 0 ->
  1329. check_field v s e2 e2.etype
  1330. | _ ->
  1331. find_locals e1
  1332. end;
  1333. find_locals e2
  1334. | TLocal v when v.v_id < 0 ->
  1335. cancel v
  1336. | _ ->
  1337. Type.iter find_locals e
  1338. in
  1339. find_locals e;
  1340. let vars = !vars in
  1341. if PMap.is_empty vars then
  1342. e
  1343. else begin
  1344. let vfields = PMap.map (fun (v,el_init,assigns,_,_) ->
  1345. (List.fold_left (fun (acc,map) (name,e,t) ->
  1346. let vf = alloc_var (v.v_name ^ "_" ^ name) t in
  1347. ((vf,e) :: acc, PMap.add name vf map)
  1348. ) ([],PMap.empty) assigns),el_init
  1349. ) vars in
  1350. let el_b = ref [] in
  1351. let append e = el_b := e :: !el_b in
  1352. let inline_field c cf v =
  1353. let (_, vars),el_init = PMap.find (-v.v_id) vfields in
  1354. (try
  1355. let v = PMap.find cf.cf_name vars in
  1356. mk (TLocal v) v.v_type e.epos
  1357. with Not_found ->
  1358. if (c.cl_path = ([],"Array") && cf.cf_name = "length") then begin
  1359. (* this can only occur for inlined array declarations, so we can use the statically known length here (issue #2568)*)
  1360. let l = PMap.fold (fun _ i -> i + 1) vars 0 in
  1361. mk (TConst (TInt (Int32.of_int l))) ctx.t.tint e.epos
  1362. end else
  1363. (* the variable was not set in the constructor, assume null *)
  1364. mk (TConst TNull) e.etype e.epos)
  1365. in
  1366. let inline_anon_field cf v =
  1367. let (_, vars),_ = PMap.find (-v.v_id) vfields in
  1368. (try
  1369. let v = PMap.find cf.cf_name vars in
  1370. mk (TLocal v) v.v_type e.epos
  1371. with Not_found ->
  1372. (* this could happen in untyped code, assume null *)
  1373. mk (TConst TNull) e.etype e.epos)
  1374. in
  1375. let inline_array_access i v =
  1376. let (_, vars),_ = PMap.find (-v.v_id) vfields in
  1377. (try
  1378. let v = PMap.find (Int32.to_string i) vars in
  1379. mk (TLocal v) v.v_type e.epos
  1380. with Not_found ->
  1381. (* probably out-of-bounds, assume null *)
  1382. mk (TConst TNull) e.etype e.epos)
  1383. in
  1384. let rec subst e =
  1385. match e.eexpr with
  1386. | TBlock el ->
  1387. let old = !el_b in
  1388. el_b := [];
  1389. List.iter (fun e -> append (subst e)) el;
  1390. let n = !el_b in
  1391. el_b := old;
  1392. {e with eexpr = TBlock (List.rev n)}
  1393. | TVar (v,Some e) when v.v_id < 0 ->
  1394. let (vars, _),el_init = PMap.find (-v.v_id) vfields in
  1395. List.iter (fun e ->
  1396. append (subst e)
  1397. ) el_init;
  1398. let (v_first,e_first),vars = match vars with
  1399. | v :: vl -> v,vl
  1400. | [] -> assert false
  1401. in
  1402. List.iter (fun (v,e) -> append (mk (TVar(v,Some (subst e))) ctx.t.tvoid e.epos)) (List.rev vars);
  1403. mk (TVar (v_first, Some (subst e_first))) ctx.t.tvoid e.epos
  1404. | TField (e1,FInstance (c,_,cf)) ->
  1405. begin match skip_to_var e1 with
  1406. | None -> Type.map_expr subst e
  1407. | Some v -> inline_field c cf v
  1408. end
  1409. | TArray (e1,{eexpr = TConst (TInt i)}) ->
  1410. begin match skip_to_var e1 with
  1411. | None -> Type.map_expr subst e
  1412. | Some v -> inline_array_access i v
  1413. end
  1414. | TField (e1,FAnon(cf)) ->
  1415. begin match skip_to_var e1 with
  1416. | None -> Type.map_expr subst e
  1417. | Some v -> inline_anon_field cf v
  1418. end
  1419. | _ ->
  1420. Type.map_expr subst e
  1421. in
  1422. let e = (try subst e with Not_found -> assert false) in
  1423. PMap.iter (fun _ (v,_,_,_,_) -> v.v_id <- -v.v_id) vars;
  1424. e
  1425. end
  1426. (* ---------------------------------------------------------------------- *)
  1427. (* COMPLETION *)
  1428. exception Return of Ast.expr
  1429. type compl_locals = {
  1430. mutable r : (string, (complex_type option * (int * Ast.expr * compl_locals) option)) PMap.t;
  1431. }
  1432. let optimize_completion_expr e =
  1433. let iid = ref 0 in
  1434. let typing_side_effect = ref false in
  1435. let locals : compl_locals = { r = PMap.empty } in
  1436. let save() = let old = locals.r in (fun() -> locals.r <- old) in
  1437. let get_local n = PMap.find n locals.r in
  1438. let maybe_typed e =
  1439. match fst e with
  1440. | EConst (Ident "null") -> false
  1441. | _ -> true
  1442. in
  1443. let decl n t e =
  1444. typing_side_effect := true;
  1445. locals.r <- PMap.add n (t,(match e with Some e when maybe_typed e -> incr iid; Some (!iid,e,{ r = locals.r }) | _ -> None)) locals.r
  1446. in
  1447. let rec loop e =
  1448. let p = snd e in
  1449. match fst e with
  1450. | EConst (Ident n) ->
  1451. (try
  1452. (match get_local n with
  1453. | Some _ , _ -> ()
  1454. | _ -> typing_side_effect := true)
  1455. with Not_found ->
  1456. ());
  1457. e
  1458. | EBinop (OpAssign,(EConst (Ident n),_),esub) ->
  1459. (try
  1460. (match get_local n with
  1461. | None, None when maybe_typed esub -> decl n None (Some esub)
  1462. | _ -> ())
  1463. with Not_found ->
  1464. ());
  1465. map e
  1466. | EVars vl ->
  1467. let vl = List.map (fun (v,t,e) ->
  1468. let e = (match e with None -> None | Some e -> Some (loop e)) in
  1469. decl v t e;
  1470. (v,t,e)
  1471. ) vl in
  1472. (EVars vl,p)
  1473. | EBlock el ->
  1474. let old = save() in
  1475. let told = ref (!typing_side_effect) in
  1476. let el = List.fold_left (fun acc e ->
  1477. typing_side_effect := false;
  1478. let e = loop e in
  1479. if !typing_side_effect then begin told := true; e :: acc end else acc
  1480. ) [] el in
  1481. old();
  1482. typing_side_effect := !told;
  1483. (EBlock (List.rev el),p)
  1484. | EFunction (v,f) ->
  1485. (match v with
  1486. | None -> ()
  1487. | Some name ->
  1488. decl name None (Some e));
  1489. let old = save() in
  1490. List.iter (fun (n,_,t,e) -> decl n t e) f.f_args;
  1491. let e = map e in
  1492. old();
  1493. e
  1494. | EFor ((EIn ((EConst (Ident n),_) as id,it),p),efor) ->
  1495. let it = loop it in
  1496. let old = save() in
  1497. let etmp = (EConst (Ident "$tmp"),p) in
  1498. decl n None (Some (EBlock [
  1499. (EVars ["$tmp",None,None],p);
  1500. (EFor ((EIn (id,it),p),(EBinop (OpAssign,etmp,(EConst (Ident n),p)),p)),p);
  1501. etmp
  1502. ],p));
  1503. let efor = loop efor in
  1504. old();
  1505. (EFor ((EIn (id,it),p),efor),p)
  1506. | EReturn _ ->
  1507. typing_side_effect := true;
  1508. map e
  1509. | ESwitch (e,cases,def) ->
  1510. let e = loop e in
  1511. let cases = List.map (fun (el,eg,eo) -> match eo with
  1512. | None ->
  1513. el,eg,eo
  1514. | Some e ->
  1515. let el = List.map loop el in
  1516. let old = save() in
  1517. List.iter (fun e ->
  1518. match fst e with
  1519. | ECall (_,pl) ->
  1520. List.iter (fun p ->
  1521. match fst p with
  1522. | EConst (Ident i) -> decl i None None (* sadly *)
  1523. | _ -> ()
  1524. ) pl
  1525. | _ -> ()
  1526. ) el;
  1527. let e = loop e in
  1528. old();
  1529. el, eg, Some e
  1530. ) cases in
  1531. let def = match def with
  1532. | None -> None
  1533. | Some None -> Some None
  1534. | Some (Some e) -> Some (Some (loop e))
  1535. in
  1536. (ESwitch (e,cases,def),p)
  1537. | ETry (et,cl) ->
  1538. let et = loop et in
  1539. let cl = List.map (fun (n,t,e) ->
  1540. let old = save() in
  1541. decl n (Some t) None;
  1542. let e = loop e in
  1543. old();
  1544. n, t, e
  1545. ) cl in
  1546. (ETry (et,cl),p)
  1547. | EDisplay (s,call) ->
  1548. typing_side_effect := true;
  1549. let tmp_locals = ref [] in
  1550. let tmp_hlocals = ref PMap.empty in
  1551. let rec subst_locals locals e =
  1552. match fst e with
  1553. | EConst (Ident n) ->
  1554. let p = snd e in
  1555. (try
  1556. (match PMap.find n locals.r with
  1557. | Some t , _ -> (ECheckType ((EConst (Ident "null"),p),t),p)
  1558. | _, Some (id,e,lc) ->
  1559. let name = (try
  1560. PMap.find id (!tmp_hlocals)
  1561. with Not_found ->
  1562. let e = subst_locals lc e in
  1563. let name = "$tmp_" ^ string_of_int id in
  1564. tmp_locals := (name,None,Some e) :: !tmp_locals;
  1565. tmp_hlocals := PMap.add id name !tmp_hlocals;
  1566. name
  1567. ) in
  1568. (EConst (Ident name),p)
  1569. | None, None ->
  1570. (* we can't replace the var *)
  1571. raise Exit)
  1572. with Not_found ->
  1573. (* not found locals are most likely to be member/static vars *)
  1574. e)
  1575. | EFunction (_,f) ->
  1576. Ast.map_expr (subst_locals { r = PMap.foldi (fun n i acc -> if List.exists (fun (a,_,_,_) -> a = n) f.f_args then acc else PMap.add n i acc) locals.r PMap.empty }) e
  1577. | _ ->
  1578. Ast.map_expr (subst_locals locals) e
  1579. in
  1580. (try
  1581. let e = subst_locals locals s in
  1582. let e = (EBlock [(EVars (List.rev !tmp_locals),p);(EDisplay (e,call),p)],p) in
  1583. raise (Return e)
  1584. with Exit ->
  1585. map e)
  1586. | EDisplayNew _ ->
  1587. raise (Return e)
  1588. | _ ->
  1589. map e
  1590. and map e =
  1591. Ast.map_expr loop e
  1592. in
  1593. (try loop e with Return e -> e)
  1594. (* ---------------------------------------------------------------------- *)