optimizer.ml 57 KB

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