nx64flw.pas 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. {
  2. Copyright (c) 2011 by Free Pascal development team
  3. Generate Win64-specific exception handling code
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit nx64flw;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. node,nflw,ncgflw,psub;
  22. type
  23. tx64raisenode=class(tcgraisenode)
  24. function pass_1 : tnode;override;
  25. end;
  26. tx64onnode=class(tcgonnode)
  27. procedure pass_generate_code;override;
  28. end;
  29. tx64tryexceptnode=class(tcgtryexceptnode)
  30. procedure pass_generate_code;override;
  31. end;
  32. tx64tryfinallynode=class(tcgtryfinallynode)
  33. finalizepi: tcgprocinfo;
  34. constructor create(l,r:TNode);override;
  35. constructor create_implicit(l,r,_t1:TNode);override;
  36. function simplify(forinline: boolean): tnode;override;
  37. procedure pass_generate_code;override;
  38. end;
  39. implementation
  40. uses
  41. cutils,globtype,globals,verbose,systems,
  42. nbas,ncal,nmem,nutils,
  43. symconst,symbase,symtable,symsym,symdef,
  44. cgbase,cgobj,cgcpu,cgutils,tgobj,
  45. cpubase,htypechk,
  46. parabase,paramgr,pdecsub,pass_1,pass_2,ncgutil,cga,
  47. aasmbase,aasmtai,aasmdata,aasmcpu,procinfo,cpupi;
  48. var
  49. endexceptlabel: tasmlabel;
  50. { tx64raisenode }
  51. function tx64raisenode.pass_1 : tnode;
  52. var
  53. statements : tstatementnode;
  54. raisenode : tcallnode;
  55. begin
  56. { difference from generic code is that address stack is not popped on reraise }
  57. if (target_info.system<>system_x86_64_win64) or assigned(left) then
  58. result:=inherited pass_1
  59. else
  60. begin
  61. result:=internalstatements(statements);
  62. raisenode:=ccallnode.createintern('fpc_reraise',nil);
  63. include(raisenode.callnodeflags,cnf_call_never_returns);
  64. addstatement(statements,raisenode);
  65. end;
  66. end;
  67. { tx64onnode }
  68. procedure tx64onnode.pass_generate_code;
  69. var
  70. oldflowcontrol : tflowcontrol;
  71. exceptvarsym : tlocalvarsym;
  72. begin
  73. if (target_info.system<>system_x86_64_win64) then
  74. begin
  75. inherited pass_generate_code;
  76. exit;
  77. end;
  78. location_reset(location,LOC_VOID,OS_NO);
  79. oldflowcontrol:=flowcontrol;
  80. flowcontrol:=flowcontrol*[fc_unwind]+[fc_inflowcontrol];
  81. { RTL will put exceptobject into RAX when jumping here }
  82. cg.a_reg_alloc(current_asmdata.CurrAsmList,NR_FUNCTION_RESULT_REG);
  83. { Retrieve exception variable }
  84. if assigned(excepTSymtable) then
  85. exceptvarsym:=tlocalvarsym(excepTSymtable.SymList[0])
  86. else
  87. exceptvarsym:=nil;
  88. if assigned(exceptvarsym) then
  89. begin
  90. exceptvarsym.localloc.loc:=LOC_REFERENCE;
  91. exceptvarsym.localloc.size:=OS_ADDR;
  92. tg.GetLocal(current_asmdata.CurrAsmList,sizeof(pint),voidpointertype,exceptvarsym.localloc.reference);
  93. cg.a_load_reg_ref(current_asmdata.CurrAsmList,OS_ADDR,OS_ADDR,NR_FUNCTION_RESULT_REG,exceptvarsym.localloc.reference);
  94. end;
  95. cg.a_reg_dealloc(current_asmdata.CurrAsmList,NR_FUNCTION_RESULT_REG);
  96. if assigned(right) then
  97. secondpass(right);
  98. { deallocate exception symbol }
  99. if assigned(exceptvarsym) then
  100. begin
  101. tg.UngetLocal(current_asmdata.CurrAsmList,exceptvarsym.localloc.reference);
  102. exceptvarsym.localloc.loc:=LOC_INVALID;
  103. end;
  104. cg.g_call(current_asmdata.CurrAsmList,'FPC_DONEEXCEPTION');
  105. cg.a_jmp_always(current_asmdata.CurrAsmList,endexceptlabel);
  106. flowcontrol:=oldflowcontrol+(flowcontrol-[fc_inflowcontrol]);
  107. end;
  108. { tx64tryfinallynode }
  109. var
  110. seq: longint=0;
  111. function create_pd: tprocdef;
  112. var
  113. st:TSymTable;
  114. checkstack: psymtablestackitem;
  115. sym:tprocsym;
  116. begin
  117. { get actual procedure symtable (skip withsymtables, etc.) }
  118. st:=nil;
  119. checkstack:=symtablestack.stack;
  120. while assigned(checkstack) do
  121. begin
  122. st:=checkstack^.symtable;
  123. if st.symtabletype in [staticsymtable,globalsymtable,localsymtable] then
  124. break;
  125. checkstack:=checkstack^.next;
  126. end;
  127. { Create a nested procedure, even from main_program_level. }
  128. result:=tprocdef.create(max(normal_function_level,st.symtablelevel)+1);
  129. result.struct:=current_procinfo.procdef.struct;
  130. result.proctypeoption:=potype_exceptfilter;
  131. handle_calling_convention(result);
  132. sym:=tprocsym.create('$fin$'+tostr(seq));
  133. st.insert(sym);
  134. inc(seq);
  135. result.procsym:=sym;
  136. proc_add_definition(result);
  137. result.forwarddef:=false;
  138. result.aliasnames.insert(result.mangledname);
  139. alloc_proc_symbol(result);
  140. end;
  141. function reset_regvars(var n: tnode; arg: pointer): foreachnoderesult;
  142. begin
  143. case n.nodetype of
  144. temprefn:
  145. make_not_regable(n,[]);
  146. calln:
  147. include(tprocinfo(arg).flags,pi_do_call);
  148. end;
  149. result:=fen_true;
  150. end;
  151. function copy_parasize(var n: tnode; arg: pointer): foreachnoderesult;
  152. begin
  153. case n.nodetype of
  154. calln:
  155. tcgprocinfo(arg).allocate_push_parasize(tcallnode(n).pushed_parasize);
  156. end;
  157. result:=fen_true;
  158. end;
  159. constructor tx64tryfinallynode.create(l, r: TNode);
  160. begin
  161. inherited create(l,r);
  162. if (target_info.system<>system_x86_64_win64) or (
  163. { Don't create child procedures for generic methods, their nested-like
  164. behavior causes compilation errors because real nested procedures
  165. aren't allowed for generics. Not creating them doesn't harm because
  166. generic node tree is discarded without generating code. }
  167. assigned(current_procinfo.procdef.struct) and
  168. (df_generic in current_procinfo.procdef.struct.defoptions)
  169. ) then
  170. exit;
  171. finalizepi:=tcgprocinfo(cprocinfo.create(current_procinfo));
  172. finalizepi.force_nested;
  173. finalizepi.procdef:=create_pd;
  174. finalizepi.entrypos:=r.fileinfo;
  175. finalizepi.entryswitches:=r.localswitches;
  176. finalizepi.exitpos:=current_filepos; // last_endtoken_pos?
  177. finalizepi.exitswitches:=current_settings.localswitches;
  178. { Regvar optimization for symbols is suppressed when using exceptions, but
  179. temps may be still placed into registers. This must be fixed. }
  180. foreachnodestatic(r,@reset_regvars,finalizepi);
  181. end;
  182. constructor tx64tryfinallynode.create_implicit(l, r, _t1: TNode);
  183. begin
  184. inherited create_implicit(l, r, _t1);
  185. if (target_info.system<>system_x86_64_win64) then
  186. exit;
  187. if assigned(current_procinfo.procdef.struct) and
  188. (df_generic in current_procinfo.procdef.struct.defoptions) then
  189. InternalError(2013012501);
  190. finalizepi:=tcgprocinfo(cprocinfo.create(current_procinfo));
  191. finalizepi.force_nested;
  192. finalizepi.procdef:=create_pd;
  193. finalizepi.entrypos:=current_filepos;
  194. finalizepi.exitpos:=current_filepos; // last_endtoken_pos?
  195. finalizepi.entryswitches:=r.localswitches;
  196. finalizepi.exitswitches:=current_settings.localswitches;
  197. include(finalizepi.flags,pi_do_call);
  198. finalizepi.allocate_push_parasize(32);
  199. end;
  200. function tx64tryfinallynode.simplify(forinline: boolean): tnode;
  201. begin
  202. result:=inherited simplify(forinline);
  203. if (target_info.system<>system_x86_64_win64) then
  204. exit;
  205. if (result=nil) then
  206. begin
  207. finalizepi.code:=right;
  208. foreachnodestatic(right,@copy_parasize,finalizepi);
  209. right:=ccallnode.create(nil,tprocsym(finalizepi.procdef.procsym),nil,nil,[]);
  210. firstpass(right);
  211. { For implicit frames, no actual code is available at this time,
  212. it is added later in assembler form. So store the nested procinfo
  213. for later use. }
  214. if implicitframe then
  215. begin
  216. current_procinfo.finalize_procinfo:=finalizepi;
  217. { don't leave dangling pointer }
  218. tcgprocinfo(current_procinfo).final_asmnode:=nil;
  219. end;
  220. end;
  221. end;
  222. procedure emit_nop;
  223. var
  224. dummy: TAsmLabel;
  225. begin
  226. { To avoid optimizing away the whole thing, prepend a jumplabel with increased refcount }
  227. current_asmdata.getjumplabel(dummy);
  228. dummy.increfs;
  229. cg.a_label(current_asmdata.CurrAsmList,dummy);
  230. current_asmdata.CurrAsmList.concat(Taicpu.op_none(A_NOP,S_NO));
  231. end;
  232. procedure tx64tryfinallynode.pass_generate_code;
  233. var
  234. trylabel,
  235. endtrylabel,
  236. finallylabel,
  237. endfinallylabel,
  238. oldexitlabel: tasmlabel;
  239. oldflowcontrol: tflowcontrol;
  240. catch_frame: boolean;
  241. begin
  242. if (target_info.system<>system_x86_64_win64) then
  243. begin
  244. inherited pass_generate_code;
  245. exit;
  246. end;
  247. location_reset(location,LOC_VOID,OS_NO);
  248. { Do not generate a frame that catches exceptions if the only action
  249. would be reraising it. Doing so is extremely inefficient with SEH
  250. (in contrast with setjmp/longjmp exception handling) }
  251. catch_frame:=implicitframe and ((not has_no_code(t1)) or
  252. (current_procinfo.procdef.proccalloption=pocall_safecall));
  253. oldflowcontrol:=flowcontrol;
  254. flowcontrol:=[fc_inflowcontrol];
  255. current_asmdata.getjumplabel(trylabel);
  256. current_asmdata.getjumplabel(endtrylabel);
  257. current_asmdata.getjumplabel(finallylabel);
  258. current_asmdata.getjumplabel(endfinallylabel);
  259. oldexitlabel:=current_procinfo.CurrExitLabel;
  260. if implicitframe then
  261. current_procinfo.CurrExitLabel:=finallylabel;
  262. { Start of scope }
  263. { Padding with NOP is necessary here because exceptions in called
  264. procedures are seen at the next instruction, while CPU/OS exceptions
  265. like AV are seen at the current instruction.
  266. So in the following code
  267. raise_some_exception; //(a)
  268. try
  269. pchar(nil)^:='0'; //(b)
  270. ...
  271. without NOP, exceptions (a) and (b) will be seen at the same address
  272. and fall into the same scope. However they should be seen in different scopes.
  273. }
  274. emit_nop;
  275. cg.a_label(current_asmdata.CurrAsmList,trylabel);
  276. { try code }
  277. if assigned(left) then
  278. begin
  279. { fc_unwind tells exit/continue/break statements to emit special
  280. unwind code instead of just JMP }
  281. if not implicitframe then
  282. include(flowcontrol,fc_unwind);
  283. secondpass(left);
  284. exclude(flowcontrol,fc_unwind);
  285. if codegenerror then
  286. exit;
  287. end;
  288. { If the immediately preceding instruction is CALL,
  289. its return address must not end up outside the scope, so pad with NOP. }
  290. if catch_frame then
  291. cg.a_jmp_always(current_asmdata.CurrAsmList,finallylabel)
  292. else
  293. emit_nop;
  294. cg.a_label(current_asmdata.CurrAsmList,endtrylabel);
  295. { Handle the except block first, so endtrylabel serves both
  296. as end of scope and as unwind target. This way it is possible to
  297. encode everything into a single scope record. }
  298. if catch_frame then
  299. begin
  300. flowcontrol:=[fc_inflowcontrol];
  301. secondpass(t1);
  302. { note 1: this is not a 'finally' block, no flow restrictions apply
  303. note 2: it contains autogenerated sequential code, flow away is impossible }
  304. if flowcontrol<>[fc_inflowcontrol] then
  305. CGMessage(cg_e_control_flow_outside_finally);
  306. if codegenerror then
  307. exit;
  308. if (current_procinfo.procdef.proccalloption=pocall_safecall) then
  309. begin
  310. handle_safecall_exception;
  311. cg.a_jmp_always(current_asmdata.CurrAsmList,endfinallylabel);
  312. end
  313. else
  314. cg.a_call_name(current_asmdata.CurrAsmList,'FPC_RERAISE_IMPLICIT',false);
  315. end;
  316. flowcontrol:=[fc_inflowcontrol];
  317. cg.a_label(current_asmdata.CurrAsmList,finallylabel);
  318. { generate finally code as a separate procedure }
  319. if not implicitframe then
  320. tcgprocinfo(current_procinfo).generate_exceptfilter(finalizepi);
  321. { right is a call to finalizer procedure }
  322. secondpass(right);
  323. if codegenerror then
  324. exit;
  325. { normal exit from safecall proc must zero the result register }
  326. if implicitframe and (current_procinfo.procdef.proccalloption=pocall_safecall) then
  327. cg.a_load_const_reg(current_asmdata.CurrAsmList,OS_INT,0,NR_FUNCTION_RESULT_REG);
  328. cg.a_label(current_asmdata.CurrAsmList,endfinallylabel);
  329. { generate the scope record in .xdata }
  330. tx86_64procinfo(current_procinfo).add_finally_scope(trylabel,endtrylabel,
  331. current_asmdata.RefAsmSymbol(finalizepi.procdef.mangledname),catch_frame);
  332. if implicitframe then
  333. current_procinfo.CurrExitLabel:=oldexitlabel;
  334. flowcontrol:=oldflowcontrol;
  335. end;
  336. { tx64tryexceptnode }
  337. procedure tx64tryexceptnode.pass_generate_code;
  338. var
  339. trylabel,
  340. exceptlabel,oldendexceptlabel,
  341. lastonlabel,
  342. exitexceptlabel,
  343. continueexceptlabel,
  344. breakexceptlabel,
  345. oldCurrExitLabel,
  346. oldContinueLabel,
  347. oldBreakLabel : tasmlabel;
  348. onlabel,
  349. filterlabel: tasmlabel;
  350. oldflowcontrol,tryflowcontrol,
  351. exceptflowcontrol : tflowcontrol;
  352. hnode : tnode;
  353. hlist : tasmlist;
  354. onnodecount : tai_const;
  355. label
  356. errorexit;
  357. begin
  358. if (target_info.system<>system_x86_64_win64) then
  359. begin
  360. inherited pass_generate_code;
  361. exit;
  362. end;
  363. location_reset(location,LOC_VOID,OS_NO);
  364. oldflowcontrol:=flowcontrol;
  365. flowcontrol:=flowcontrol*[fc_unwind]+[fc_inflowcontrol];
  366. { this can be called recursivly }
  367. oldBreakLabel:=nil;
  368. oldContinueLabel:=nil;
  369. oldendexceptlabel:=endexceptlabel;
  370. { save the old labels for control flow statements }
  371. oldCurrExitLabel:=current_procinfo.CurrExitLabel;
  372. current_asmdata.getjumplabel(exitexceptlabel);
  373. if assigned(current_procinfo.CurrBreakLabel) then
  374. begin
  375. oldContinueLabel:=current_procinfo.CurrContinueLabel;
  376. oldBreakLabel:=current_procinfo.CurrBreakLabel;
  377. current_asmdata.getjumplabel(breakexceptlabel);
  378. current_asmdata.getjumplabel(continueexceptlabel);
  379. end;
  380. current_asmdata.getjumplabel(exceptlabel);
  381. current_asmdata.getjumplabel(endexceptlabel);
  382. current_asmdata.getjumplabel(lastonlabel);
  383. filterlabel:=nil;
  384. { start of scope }
  385. current_asmdata.getjumplabel(trylabel);
  386. emit_nop;
  387. cg.a_label(current_asmdata.CurrAsmList,trylabel);
  388. { control flow in try block needs no special handling,
  389. just make sure that target labels are outside the scope }
  390. secondpass(left);
  391. tryflowcontrol:=flowcontrol;
  392. if codegenerror then
  393. goto errorexit;
  394. { jump over except handlers }
  395. cg.a_jmp_always(current_asmdata.CurrAsmList,endexceptlabel);
  396. { end of scope }
  397. cg.a_label(current_asmdata.CurrAsmList,exceptlabel);
  398. { set control flow labels for the except block }
  399. { and the on statements }
  400. current_procinfo.CurrExitLabel:=exitexceptlabel;
  401. if assigned(oldBreakLabel) then
  402. begin
  403. current_procinfo.CurrContinueLabel:=continueexceptlabel;
  404. current_procinfo.CurrBreakLabel:=breakexceptlabel;
  405. end;
  406. flowcontrol:=flowcontrol*[fc_unwind]+[fc_inflowcontrol];
  407. { on statements }
  408. if assigned(right) then
  409. begin
  410. { emit filter table to a temporary asmlist }
  411. hlist:=TAsmList.Create;
  412. current_asmdata.getdatalabel(filterlabel);
  413. new_section(hlist,sec_rodata_norel,filterlabel.name,4);
  414. cg.a_label(hlist,filterlabel);
  415. onnodecount:=tai_const.create_32bit(0);
  416. hlist.concat(onnodecount);
  417. hnode:=right;
  418. while assigned(hnode) do
  419. begin
  420. if hnode.nodetype<>onn then
  421. InternalError(2011103101);
  422. { TODO: make it done without using global label }
  423. current_asmdata.getglobaljumplabel(onlabel);
  424. hlist.concat(tai_const.create_rva_sym(current_asmdata.RefAsmSymbol(tonnode(hnode).excepttype.vmt_mangledname)));
  425. hlist.concat(tai_const.create_rva_sym(onlabel));
  426. cg.a_label(current_asmdata.CurrAsmList,onlabel);
  427. secondpass(hnode);
  428. inc(onnodecount.value);
  429. hnode:=tonnode(hnode).left;
  430. end;
  431. { add 'else' node to the filter list, too }
  432. if assigned(t1) then
  433. begin
  434. hlist.concat(tai_const.create_32bit(-1));
  435. hlist.concat(tai_const.create_rva_sym(lastonlabel));
  436. inc(onnodecount.value);
  437. end;
  438. { now move filter table to permanent list all at once }
  439. maybe_new_object_file(current_asmdata.asmlists[al_typedconsts]);
  440. current_asmdata.asmlists[al_typedconsts].concatlist(hlist);
  441. hlist.free;
  442. end;
  443. cg.a_label(current_asmdata.CurrAsmList,lastonlabel);
  444. if assigned(t1) then
  445. begin
  446. { here we don't have to reset flowcontrol }
  447. { the default and on flowcontrols are handled equal }
  448. secondpass(t1);
  449. cg.g_call(current_asmdata.CurrAsmList,'FPC_DONEEXCEPTION');
  450. if (flowcontrol*[fc_exit,fc_break,fc_continue]<>[]) then
  451. cg.a_jmp_always(current_asmdata.CurrAsmList,endexceptlabel);
  452. end;
  453. exceptflowcontrol:=flowcontrol;
  454. if fc_exit in exceptflowcontrol then
  455. begin
  456. { do some magic for exit in the try block }
  457. cg.a_label(current_asmdata.CurrAsmList,exitexceptlabel);
  458. cg.g_call(current_asmdata.CurrAsmList,'FPC_DONEEXCEPTION');
  459. if (fc_unwind in flowcontrol) then
  460. cg.g_local_unwind(current_asmdata.CurrAsmList,oldCurrExitLabel)
  461. else
  462. cg.a_jmp_always(current_asmdata.CurrAsmList,oldCurrExitLabel);
  463. end;
  464. if fc_break in exceptflowcontrol then
  465. begin
  466. cg.a_label(current_asmdata.CurrAsmList,breakexceptlabel);
  467. cg.g_call(current_asmdata.CurrAsmList,'FPC_DONEEXCEPTION');
  468. if (fc_unwind in flowcontrol) then
  469. cg.g_local_unwind(current_asmdata.CurrAsmList,oldCurrExitLabel)
  470. else
  471. cg.a_jmp_always(current_asmdata.CurrAsmList,oldBreakLabel);
  472. end;
  473. if fc_continue in exceptflowcontrol then
  474. begin
  475. cg.a_label(current_asmdata.CurrAsmList,continueexceptlabel);
  476. cg.g_call(current_asmdata.CurrAsmList,'FPC_DONEEXCEPTION');
  477. if (fc_unwind in flowcontrol) then
  478. cg.g_local_unwind(current_asmdata.CurrAsmList,oldCurrExitLabel)
  479. else
  480. cg.a_jmp_always(current_asmdata.CurrAsmList,oldContinueLabel);
  481. end;
  482. emit_nop;
  483. cg.a_label(current_asmdata.CurrAsmList,endexceptlabel);
  484. tx86_64procinfo(current_procinfo).add_except_scope(trylabel,exceptlabel,endexceptlabel,filterlabel);
  485. errorexit:
  486. { restore all saved labels }
  487. endexceptlabel:=oldendexceptlabel;
  488. { restore the control flow labels }
  489. current_procinfo.CurrExitLabel:=oldCurrExitLabel;
  490. if assigned(oldBreakLabel) then
  491. begin
  492. current_procinfo.CurrContinueLabel:=oldContinueLabel;
  493. current_procinfo.CurrBreakLabel:=oldBreakLabel;
  494. end;
  495. { return all used control flow statements }
  496. flowcontrol:=oldflowcontrol+(exceptflowcontrol +
  497. tryflowcontrol - [fc_inflowcontrol]);
  498. end;
  499. initialization
  500. craisenode:=tx64raisenode;
  501. connode:=tx64onnode;
  502. ctryexceptnode:=tx64tryexceptnode;
  503. ctryfinallynode:=tx64tryfinallynode;
  504. end.