diff --git a/BEAM/eam_gc.c b/BEAM/eam_gc.c index d04ca67cb..0043a3a24 100644 --- a/BEAM/eam_gc.c +++ b/BEAM/eam_gc.c @@ -53,7 +53,7 @@ Cell *C, OldC; Cell move_structures(Cell c) { Cell *NewC, *NewH; -Cell OldC,OldH; +Cell OldC,LOCAL_OldH; OldC=deref((Cell) c); /* @@ -67,7 +67,7 @@ Cell OldC,OldH; return(OldC); } - OldH=(Cell) beam_H; + LOCAL_OldH=(Cell) beam_H; NewH=beam_H; if (isappl(OldC)) { int i,arity; @@ -81,7 +81,7 @@ Cell OldC,OldH; NewH++; NewC++; } - return(absappl(OldH)); + return(absappl(LOCAL_OldH)); } /* else if (ispair(c)) { */ NewC=(Cell *) reppair(OldC); @@ -90,7 +90,7 @@ Cell OldC,OldH; NewC++; NewH++; *NewH=move_structures((Cell) NewC); - return(abspair(OldH)); + return(abspair(LOCAL_OldH)); } diff --git a/BEAM/eam_split.c b/BEAM/eam_split.c index 04895a766..674da02c8 100644 --- a/BEAM/eam_split.c +++ b/BEAM/eam_split.c @@ -440,7 +440,7 @@ if (a==NULL) return; Cell copy_structures(Cell c) { Cell *NewC, *NewH; -Cell OldC,OldH; +Cell OldC,LOCAL_OldH; OldC=deref((Cell) c); @@ -451,7 +451,7 @@ Cell OldC,OldH; return(OldC); } - OldH=(Cell) beam_H; + LOCAL_OldH=(Cell) beam_H; NewH=beam_H; if (isappl(OldC)) { int i,arity; @@ -465,7 +465,7 @@ Cell OldC,OldH; NewH++; NewC++; } - return(absappl(OldH)); + return(absappl(LOCAL_OldH)); } /* else if (ispair(c)) { */ NewC=(Cell *) reppair(OldC); @@ -474,5 +474,5 @@ Cell OldC,OldH; NewC++; NewH++; *NewH=copy_structures((Cell) NewC); - return(abspair(OldH)); + return(abspair(LOCAL_OldH)); } diff --git a/BEAM/toeam.c b/BEAM/toeam.c index 0f98fdb7f..ce016f5a8 100644 --- a/BEAM/toeam.c +++ b/BEAM/toeam.c @@ -748,13 +748,13 @@ void ShowCode_new2(int op, int new1,CELL new4) Yap_plwrite(MkIntTerm(new4), Yap_DebugPutc, 0, 1200); break; default: - Yap_DebugPutc (Yap_c_error_stream,'%'); - Yap_DebugPutc (Yap_c_error_stream,ch); + Yap_DebugPutc (LOCAL_c_error_stream,'%'); + Yap_DebugPutc (LOCAL_c_error_stream,ch); } else - Yap_DebugPutc (Yap_c_error_stream,ch); + Yap_DebugPutc (LOCAL_c_error_stream,ch); } - Yap_DebugPutc (Yap_c_error_stream,'\n'); + Yap_DebugPutc (LOCAL_c_error_stream,'\n'); } diff --git a/C/absmi.c b/C/absmi.c index 4bf57bea4..169f6721a 100755 --- a/C/absmi.c +++ b/C/absmi.c @@ -725,7 +725,7 @@ Yap_absmi(int inp) /* the registers are all set up, let's swap */ #ifdef THREADS pthread_setspecific(Yap_yaamregs_key, (const void *)&absmi_regs); - MY_ThreadHandle.current_yaam_regs = &absmi_regs; + LOCAL_ThreadHandle.current_yaam_regs = &absmi_regs; regcache = &absmi_regs; #else Yap_regp = &absmi_regs; @@ -784,8 +784,8 @@ Yap_absmi(int inp) op_switch: #ifdef ANALYST - Yap_opcount[opcode]++; - Yap_2opcount[old_op][opcode]++; + GLOBAL_opcount[opcode]++; + GLOBAL_2opcount[old_op][opcode]++; #ifdef DEBUG_XX ops_done++; /* if (B->cp_b > 0x103fff90) @@ -806,7 +806,7 @@ Yap_absmi(int inp) saveregs(); /* do a garbage collection first to check if we can recover memory */ if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -1186,15 +1186,15 @@ Yap_absmi(int inp) LOCK(PREG->u.p.p->StatisticsForPred.lock); PREG->u.p.p->StatisticsForPred.NOfEntries++; UNLOCK(PREG->u.p.p->StatisticsForPred.lock); - ReductionsCounter--; - if (ReductionsCounter == 0 && ReductionsCounterOn) { + LOCAL_ReductionsCounter--; + if (LOCAL_ReductionsCounter == 0 && LOCAL_ReductionsCounterOn) { saveregs(); Yap_Error(CALL_COUNTER_UNDERFLOW,TermNil,""); setregs(); JMPNext(); } - PredEntriesCounter--; - if (PredEntriesCounter == 0 && PredEntriesCounterOn) { + LOCAL_PredEntriesCounter--; + if (LOCAL_PredEntriesCounter == 0 && LOCAL_PredEntriesCounterOn) { saveregs(); Yap_Error(PRED_ENTRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); @@ -1209,8 +1209,8 @@ Yap_absmi(int inp) LOCK(PREG->u.p.p->StatisticsForPred.lock); PREG->u.p.p->StatisticsForPred.NOfRetries++; UNLOCK(PREG->u.p.p->StatisticsForPred.lock); - RetriesCounter--; - if (RetriesCounter == 0 && RetriesCounterOn) { + LOCAL_RetriesCounter--; + if (LOCAL_RetriesCounter == 0 && LOCAL_RetriesCounterOn) { /* act as if we had backtracked */ ENV = B->cp_env; saveregs(); @@ -1218,8 +1218,8 @@ Yap_absmi(int inp) setregs(); JMPNext(); } - PredEntriesCounter--; - if (PredEntriesCounter == 0 && PredEntriesCounterOn) { + LOCAL_PredEntriesCounter--; + if (LOCAL_PredEntriesCounter == 0 && LOCAL_PredEntriesCounterOn) { ENV = B->cp_env; saveregs(); Yap_Error(PRED_ENTRY_COUNTER_UNDERFLOW,TermNil,""); @@ -1248,15 +1248,15 @@ Yap_absmi(int inp) LOCK(((PredEntry *)(PREG->u.Otapl.p))->StatisticsForPred.lock); ((PredEntry *)(PREG->u.Otapl.p))->StatisticsForPred.NOfRetries++; UNLOCK(((PredEntry *)(PREG->u.Otapl.p))->StatisticsForPred.lock); - RetriesCounter--; - if (RetriesCounter == 0 && RetriesCounterOn) { + LOCAL_RetriesCounter--; + if (LOCAL_RetriesCounter == 0 && LOCAL_RetriesCounterOn) { saveregs(); Yap_Error(RETRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); JMPNext(); } - PredEntriesCounter--; - if (PredEntriesCounter == 0 && PredEntriesCounterOn) { + LOCAL_PredEntriesCounter--; + if (LOCAL_PredEntriesCounter == 0 && LOCAL_PredEntriesCounterOn) { saveregs(); Yap_Error(PRED_ENTRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); @@ -1292,15 +1292,15 @@ Yap_absmi(int inp) } SET_BB(B_YREG); ENDCACHE_Y(); - RetriesCounter--; - if (RetriesCounter == 0) { + LOCAL_RetriesCounter--; + if (LOCAL_RetriesCounter == 0) { saveregs(); Yap_Error(RETRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); JMPNext(); } - PredEntriesCounter--; - if (PredEntriesCounter == 0) { + LOCAL_PredEntriesCounter--; + if (LOCAL_PredEntriesCounter == 0) { saveregs(); Yap_Error(PRED_ENTRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); @@ -1327,15 +1327,15 @@ Yap_absmi(int inp) } restore_yaam_regs(PREG->u.OtaLl.n); restore_args(PREG->u.OtaLl.s); - RetriesCounter--; - if (RetriesCounter == 0) { + LOCAL_RetriesCounter--; + if (LOCAL_RetriesCounter == 0) { saveregs(); Yap_Error(RETRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); JMPNext(); } - PredEntriesCounter--; - if (PredEntriesCounter == 0) { + LOCAL_PredEntriesCounter--; + if (LOCAL_PredEntriesCounter == 0) { saveregs(); Yap_Error(PRED_ENTRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); @@ -1372,15 +1372,15 @@ Yap_absmi(int inp) /* jump to next alternative */ PREG = FAILCODE; } else { - RetriesCounter--; - if (RetriesCounter == 0) { + LOCAL_RetriesCounter--; + if (LOCAL_RetriesCounter == 0) { saveregs(); Yap_Error(RETRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); JMPNext(); } - PredEntriesCounter--; - if (PredEntriesCounter == 0) { + LOCAL_PredEntriesCounter--; + if (LOCAL_PredEntriesCounter == 0) { saveregs(); Yap_Error(PRED_ENTRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); @@ -1556,24 +1556,24 @@ Yap_absmi(int inp) SET_ASP(YREG, E_CB*sizeof(CELL)); saveregs(); while ((t = Yap_FetchTermFromDB(cl->ClSource)) == 0L) { - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { UNLOCKPE(3,PP); #if defined(YAPOR) || defined(THREADS) PP = NULL; #endif - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); FAIL(); } } else { - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_gc(3, ENV, CP)) { UNLOCKPE(4,PP); #if defined(YAPOR) || defined(THREADS) PP = NULL; #endif - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); FAIL(); } } @@ -1606,7 +1606,7 @@ Yap_absmi(int inp) if (!(cl->ClFlags & InUseMask)) { /* Clause *cl = (Clause *)PREG->u.EC.ClBase; - PREG->u.EC.ClTrail = TR-(tr_fr_ptr)Yap_TrailBase; + PREG->u.EC.ClTrail = TR-(tr_fr_ptr)LOCAL_TrailBase; PREG->u.EC.ClENV = LCL0-YREG;*/ cl->ClFlags |= InUseMask; TRAIL_CLREF(cl); @@ -1658,7 +1658,7 @@ Yap_absmi(int inp) if (!(cl->ClFlags & InUseMask)) { /* Clause *cl = (Clause *)PREG->u.EC.ClBase; - PREG->u.EC.ClTrail = TR-(tr_fr_ptr)Yap_TrailBase; + PREG->u.EC.ClTrail = TR-(tr_fr_ptr)LOCAL_TrailBase; PREG->u.EC.ClENV = LCL0-YREG;*/ cl->ClFlags |= InUseMask; TRAIL_CLREF(cl); @@ -1693,7 +1693,7 @@ Yap_absmi(int inp) SET_ASP(YREG, PREG->u.Osbpi.s); saveregs(); if (!Yap_gcl(sz, arity, YENV, PREG)) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); setregs(); FAIL(); } else { @@ -1778,15 +1778,15 @@ Yap_absmi(int inp) ENDBOp(); BOp(count_retry_and_mark, Otapl); - RetriesCounter--; - if (RetriesCounter == 0) { + LOCAL_RetriesCounter--; + if (LOCAL_RetriesCounter == 0) { saveregs(); Yap_Error(RETRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); JMPNext(); } - PredEntriesCounter--; - if (PredEntriesCounter == 0) { + LOCAL_PredEntriesCounter--; + if (LOCAL_PredEntriesCounter == 0) { saveregs(); Yap_Error(PRED_ENTRY_COUNTER_UNDERFLOW,TermNil,""); setregs(); @@ -2021,7 +2021,7 @@ Yap_absmi(int inp) #endif /* LOW_LEVEL_TRACER */ #ifdef FROZEN_STACKS #ifdef YAPOR_SBA - if (pt0 < TR_FZ || pt0 > (tr_fr_ptr)Yap_TrailTop) + if (pt0 < TR_FZ || pt0 > (tr_fr_ptr)LOCAL_TrailTop) #else if (pt0 < TR_FZ) #endif /* YAPOR_SBA */ @@ -2057,7 +2057,7 @@ Yap_absmi(int inp) register CELL flags; CELL *pt1 = RepPair(d1); #ifdef LIMIT_TABLING - if ((ADDR) pt1 == Yap_TrailBase) { + if ((ADDR) pt1 == LOCAL_TrailBase) { sg_fr_ptr sg_fr = (sg_fr_ptr) TrailVal(pt0); TrailTerm(pt0) = AbsPair((CELL *)(pt0 - 1)); SgFr_state(sg_fr)--; /* complete_in_use --> complete : compiled_in_use --> compiled */ @@ -2071,7 +2071,7 @@ Yap_absmi(int inp) #ifdef YAPOR_SBA (ADDR) pt1 >= HeapTop #else - IN_BETWEEN(Yap_TrailBase, pt1, Yap_TrailTop) + IN_BETWEEN(LOCAL_TrailBase, pt1, LOCAL_TrailTop) #endif /* YAPOR_SBA */ ) { @@ -2444,12 +2444,12 @@ Yap_absmi(int inp) NoStackExecute: SREG = (CELL *) PREG->u.pp.p; PP = PREG->u.pp.p0; - if (ActiveSignals & YAP_CDOVF_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { SET_ASP(YREG, E_CB*sizeof(CELL)); SREG = YENV; goto noheapleft; } - if (ActiveSignals) + if (LOCAL_ActiveSignals) goto creep; else goto NoStackExec; @@ -2586,30 +2586,30 @@ Yap_absmi(int inp) NoStackCall: PP = PREG->u.Osbpp.p0; /* on X86 machines S will not actually be holding the pointer to pred */ - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); goto fail; } - if (ActiveSignals & YAP_CREEP_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL) { PredEntry *ap = PREG->u.Osbpp.p; SREG = (CELL *) ap; goto creepc; } SREG = (CELL *) PREG->u.Osbpp.p; - if (ActiveSignals & YAP_CDOVF_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { SET_ASP(YREG, PREG->u.Osbpp.s); SREG = YENV; goto noheapleft; } - if (ActiveSignals) { + if (LOCAL_ActiveSignals) { goto creepc; } SET_ASP(YREG, PREG->u.Osbpp.s); saveregs(); if (!Yap_gc(((PredEntry *)SREG)->ArityOfPE, YREG, NEXTOP(PREG, Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); } setregs(); @@ -2624,18 +2624,18 @@ Yap_absmi(int inp) { CELL cut_b = LCL0-(CELL *)(SREG[E_CB]); - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); goto fail; } /* don't do a creep here; also, if our instruction is followed by a execute_c, just wait a bit more */ - if ( (ActiveSignals & YAP_CREEP_SIGNAL && + if ( (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL && /* keep on going if there is something else */ - !(ActiveSignals & ~YAP_CREEP_SIGNAL)) || + !(LOCAL_ActiveSignals & ~YAP_CREEP_SIGNAL)) || (PREG->opc != Yap_opcode(_procceed) && PREG->opc != Yap_opcode(_cut_e))) { GONext(); @@ -2648,10 +2648,10 @@ Yap_absmi(int inp) } if (ASP > (CELL *)PROTECT_FROZEN_B(B)) ASP = (CELL *)PROTECT_FROZEN_B(B); - if (ActiveSignals & YAP_CDOVF_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { goto noheapleft; } - if (ActiveSignals) { + if (LOCAL_ActiveSignals) { if (Yap_op_from_opcode(PREG->opc) == _cut_e) { /* followed by a cut */ ARG1 = MkIntegerTerm(LCL0-(CELL *)SREG[E_CB]); @@ -2663,7 +2663,7 @@ Yap_absmi(int inp) } saveregs(); if (!Yap_gc(0, ENV, CPREG)) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); } setregs(); SREG = ASP; @@ -2676,16 +2676,16 @@ Yap_absmi(int inp) /* This is easier: I know there is an environment so I cannot do allocate */ NoStackCut: /* find something to fool S */ - if (!ActiveSignals || ActiveSignals & YAP_CDOVF_SIGNAL) { + if (!LOCAL_ActiveSignals || LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { goto do_cut; } - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); FAIL(); } - if (!(ActiveSignals & YAP_CREEP_SIGNAL)) { + if (!(LOCAL_ActiveSignals & YAP_CREEP_SIGNAL)) { SREG = (CELL *)PredRestoreRegs; XREGS[0] = MkIntegerTerm(LCL0-(CELL *)YREG[E_CB]); PREG = NEXTOP(PREG,e); @@ -2696,16 +2696,16 @@ Yap_absmi(int inp) NoStackCutT: /* find something to fool S */ - if (!ActiveSignals || ActiveSignals & YAP_CDOVF_SIGNAL) { + if (!LOCAL_ActiveSignals || LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { goto do_cut_t; } - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); FAIL(); } - if (!(ActiveSignals & YAP_CREEP_SIGNAL)) { + if (!(LOCAL_ActiveSignals & YAP_CREEP_SIGNAL)) { SREG = (CELL *)PredRestoreRegs; XREGS[0] = MkIntegerTerm(LCL0-(CELL *)SREG[E_CB]); PREG = NEXTOP(PREG,e); @@ -2715,16 +2715,16 @@ Yap_absmi(int inp) goto do_cut_t; NoStackCutE: - if (!ActiveSignals || ActiveSignals & YAP_CDOVF_SIGNAL) { + if (!LOCAL_ActiveSignals || LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { goto do_cut_t; } - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); FAIL(); } - if (!(ActiveSignals & YAP_CREEP_SIGNAL)) { + if (!(LOCAL_ActiveSignals & YAP_CREEP_SIGNAL)) { SREG = (CELL *)PredRestoreRegs; XREGS[0] = MkIntegerTerm(LCL0-(CELL *)SREG[E_CB]); PREG = NEXTOP(PREG,e); @@ -2737,16 +2737,16 @@ Yap_absmi(int inp) NoStackCommitY: PP = PREG->u.yps.p0; /* find something to fool S */ - if (!ActiveSignals || ActiveSignals & YAP_CDOVF_SIGNAL) { + if (!LOCAL_ActiveSignals || LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { goto do_commit_b_y; } - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); FAIL(); } - if (!(ActiveSignals & YAP_CREEP_SIGNAL)) { + if (!(LOCAL_ActiveSignals & YAP_CREEP_SIGNAL)) { SREG = (CELL *)PredRestoreRegs; XREGS[0] = YREG[PREG->u.yps.y]; PREG = NEXTOP(PREG,yps); @@ -2759,16 +2759,16 @@ Yap_absmi(int inp) NoStackCommitX: PP = PREG->u.xps.p0; /* find something to fool S */ - if (!ActiveSignals || ActiveSignals & YAP_CDOVF_SIGNAL) { + if (!LOCAL_ActiveSignals || LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { goto do_commit_b_x; } - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); FAIL(); } - if (!(ActiveSignals & YAP_CREEP_SIGNAL)) { + if (!(LOCAL_ActiveSignals & YAP_CREEP_SIGNAL)) { SREG = (CELL *)PredRestoreRegs; #if USE_THREADED_CODE if (PREG->opc == (OPCODE)OpAddress[_fcall]) @@ -2794,18 +2794,18 @@ Yap_absmi(int inp) /* Problem: have I got an environment or not? */ NoStackFail: - if (ActiveSignals && ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals && LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); /* we're happy */ goto fail; } /* find something to fool S */ - if (!ActiveSignals || ActiveSignals & (YAP_CDOVF_SIGNAL)) { + if (!LOCAL_ActiveSignals || LOCAL_ActiveSignals & (YAP_CDOVF_SIGNAL)) { goto fail; } - if (!(ActiveSignals & YAP_CREEP_SIGNAL)) { + if (!(LOCAL_ActiveSignals & YAP_CREEP_SIGNAL)) { SREG = (CELL *)RepPredProp(Yap_GetPredPropByAtom(AtomFail,0)); /* make sure we have the correct environment for continuation */ ENV = B->cp_env; @@ -2817,24 +2817,24 @@ Yap_absmi(int inp) /* don't forget I cannot creep at ; */ NoStackEither: - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); goto fail; } PP = PREG->u.Osblp.p0; - if (ActiveSignals & YAP_CREEP_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL) { goto either_notest; } /* find something to fool S */ SREG = (CELL *)RepPredProp(Yap_GetPredPropByFunc(FunctorRestoreRegs1,0)); - if (ActiveSignals & YAP_CDOVF_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { SET_ASP(YREG, PREG->u.Osbpp.s); SREG = YENV; goto noheapleft; } - if (ActiveSignals) { + if (LOCAL_ActiveSignals) { goto creep_either; } ASP = (CELL *) (((char *) YREG) + PREG->u.Osbpp.s); @@ -2842,7 +2842,7 @@ Yap_absmi(int inp) ASP = (CELL *)PROTECT_FROZEN_B(B); saveregs(); if (!Yap_gc(0, YREG, NEXTOP(PREG, Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); } setregs(); JMPNext(); @@ -2899,14 +2899,14 @@ Yap_absmi(int inp) goto creep; NoStackDExecute: - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); goto fail; } PP = PREG->u.pp.p0; - if (ActiveSignals & YAP_CREEP_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL) { PredEntry *ap = PREG->u.pp.p; if (ap->PredFlags & HiddenPredFlag) { @@ -2951,14 +2951,14 @@ Yap_absmi(int inp) } /* set SREG for next instructions */ SREG = (CELL *) PREG->u.p.p; - if (ActiveSignals & YAP_CDOVF_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { ASP = YREG+E_CB; if (ASP > (CELL *)PROTECT_FROZEN_B(B)) ASP = (CELL *)PROTECT_FROZEN_B(B); SREG = YENV; goto noheapleft; } - if (ActiveSignals) + if (LOCAL_ActiveSignals) goto creepde; /* try performing garbage collection */ @@ -2967,7 +2967,7 @@ Yap_absmi(int inp) ASP = (CELL *)PROTECT_FROZEN_B(B); saveregs(); if (!Yap_gc(((PredEntry *)(SREG))->ArityOfPE, (CELL *)YREG[E_E], (yamop *)YREG[E_CP])) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); } setregs(); /* hopefully, gc will succeeded, and we will retry @@ -2978,9 +2978,9 @@ Yap_absmi(int inp) /* try performing garbage collection */ - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); goto fail; } @@ -2989,7 +2989,7 @@ Yap_absmi(int inp) ASP = (CELL *)PROTECT_FROZEN_B(B); saveregs(); if (!Yap_gc(((PredEntry *)(SREG))->ArityOfPE, ENV, CPREG)) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); } setregs(); /* hopefully, gc will succeeded, and we will retry @@ -3027,22 +3027,22 @@ Yap_absmi(int inp) /* and now CREEP */ creep: - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); goto fail; } #if defined(_MSC_VER) || defined(__MINGW32__) /* I need this for Windows and other systems where SIGINT is not proceesed by same thread as absmi */ - LOCK(SignalLock); - if (Yap_PrologMode & (AbortMode|InterruptMode)) { + LOCK(LOCAL_SignalLock); + if (LOCAL_PrologMode & (AbortMode|InterruptMode)) { CreepFlag = CalculateStackGap(); - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); /* same instruction */ - if (Yap_PrologMode & InterruptMode) { - Yap_PrologMode &= ~InterruptMode; + if (LOCAL_PrologMode & InterruptMode) { + LOCAL_PrologMode &= ~InterruptMode; SET_ASP(YREG, E_CB*sizeof(CELL)); saveregs(); Yap_ProcessSIGINT(); @@ -3050,7 +3050,7 @@ Yap_absmi(int inp) } JMPNext(); } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); #endif #ifdef SHADOW_S S = SREG; @@ -3105,22 +3105,22 @@ Yap_absmi(int inp) ARG1 = (Term) AbsPair(H); H += 2; - LOCK(SignalLock); + LOCK(LOCAL_SignalLock); #ifdef COROUTINING - if (ActiveSignals & YAP_WAKEUP_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_WAKEUP_SIGNAL) { CreepFlag = CalculateStackGap(); - ActiveSignals &= ~YAP_WAKEUP_SIGNAL; - UNLOCK(SignalLock); + LOCAL_ActiveSignals &= ~YAP_WAKEUP_SIGNAL; + UNLOCK(LOCAL_SignalLock); ARG2 = Yap_ListOfWokenGoals(); SREG = (CELL *) (WakeUpCode); /* no more goals to wake up */ - Yap_UpdateTimedVar(WokenGoals, TermNil); + Yap_UpdateTimedVar(LOCAL_WokenGoals, TermNil); } else #endif { CreepFlag = CalculateStackGap(); SREG = (CELL *) CreepCode; - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); } PREG = ((PredEntry *)SREG)->CodeOfPred; #ifdef LOW_LEVEL_TRACER @@ -7102,7 +7102,7 @@ Yap_absmi(int inp) yamop *savedP; Yap_StartSlots( PASS_REGS1 ); - Yap_PrologMode = UserCCallMode; + LOCAL_PrologMode = UserCCallMode; { PredEntry *p = PREG->u.Osbpp.p; @@ -7115,7 +7115,7 @@ Yap_absmi(int inp) } Yap_CloseSlots( PASS_REGS1 ); setregs(); - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; restore_machine_regs(); PREG = savedP; } @@ -7283,7 +7283,7 @@ Yap_absmi(int inp) #endif SET_BB(B_YREG); ENDCACHE_Y(); - Yap_PrologMode = UserCCallMode; + LOCAL_PrologMode = UserCCallMode; ASP = YREG; /* for slots to work */ Yap_StartSlots( PASS_REGS1 ); @@ -7293,7 +7293,7 @@ Yap_absmi(int inp) EX = 0L; restore_machine_regs(); setregs(); - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; Yap_CloseSlots( PASS_REGS1 ); if (!SREG) { FAIL(); @@ -7326,7 +7326,7 @@ Yap_absmi(int inp) restore_args(PREG->u.OtapFs.s); ENDCACHE_Y(); - Yap_PrologMode = UserCCallMode; + LOCAL_PrologMode = UserCCallMode; SET_ASP(YREG, E_CB*sizeof(CELL)); /* for slots to work */ Yap_StartSlots( PASS_REGS1 ); @@ -7336,7 +7336,7 @@ Yap_absmi(int inp) EX = 0L; restore_machine_regs(); setregs(); - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; Yap_CloseSlots( PASS_REGS1 ); if (!SREG) { #ifdef CUT_C @@ -7625,16 +7625,16 @@ Yap_absmi(int inp) LOCK(pe->StatisticsForPred.lock); pe->StatisticsForPred.NOfEntries++; UNLOCK(pe->StatisticsForPred.lock); - ReductionsCounter--; - if (ReductionsCounter == 0 && ReductionsCounterOn) { + LOCAL_ReductionsCounter--; + if (LOCAL_ReductionsCounter == 0 && LOCAL_ReductionsCounterOn) { UNLOCKPE(20,pe); saveregs(); Yap_Error(CALL_COUNTER_UNDERFLOW,TermNil,""); setregs(); JMPNext(); } - PredEntriesCounter--; - if (PredEntriesCounter == 0 && PredEntriesCounterOn) { + LOCAL_PredEntriesCounter--; + if (LOCAL_PredEntriesCounter == 0 && LOCAL_PredEntriesCounterOn) { UNLOCKPE(21,pe); saveregs(); Yap_Error(PRED_ENTRY_COUNTER_UNDERFLOW,TermNil,""); @@ -7659,7 +7659,7 @@ Yap_absmi(int inp) JMPNext(); } } - if (!DebugOn) { + if (!LOCAL_DebugOn) { PREG = pe->cs.p_code.TrueCodeOfPred; UNLOCKPE(24,pe); JMPNext(); @@ -7711,14 +7711,14 @@ Yap_absmi(int inp) { PredEntry *pt0; #ifdef THREADS - LOCK(Yap_ThreadHandlesLock); + LOCK(GLOBAL_ThreadHandlesLock); #endif pt0 = SpyCode; P_before_spy = PREG; PREG = pt0->CodeOfPred; /* for profiler */ #ifdef THREADS - UNLOCK(Yap_ThreadHandlesLock); + UNLOCK(GLOBAL_ThreadHandlesLock); #endif save_pc(); CACHE_A1(); @@ -9164,7 +9164,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9209,7 +9209,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9222,7 +9222,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, plus_vc_unk, plus_vc_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A+B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A+ " Int_FORMAT, PREG->u.xxn.c); setregs(); FAIL(); ENDP(pt0); @@ -9250,7 +9250,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9302,7 +9302,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9322,7 +9322,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, plus_y_vc_unk, plus_y_vc_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A+B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A+ " Int_FORMAT, PREG->u.yxn.c); setregs(); FAIL(); ENDP(pt0); @@ -9350,7 +9350,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9395,7 +9395,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9408,7 +9408,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, minus_cv_unk, minus_cv_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A-B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is " Int_FORMAT "-A", PREG->u.xxn.c); setregs(); FAIL(); ENDP(pt0); @@ -9436,7 +9436,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9488,7 +9488,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9508,7 +9508,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, minus_y_cv_unk, minus_y_cv_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A-B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is " Int_FORMAT "-A", PREG->u.yxn.c); setregs(); FAIL(); ENDP(pt0); @@ -9536,7 +9536,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9581,7 +9581,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9594,7 +9594,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, times_vc_unk, times_vc_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A*B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A* " Int_FORMAT, PREG->u.xxn.c); setregs(); FAIL(); ENDP(pt0); @@ -9622,7 +9622,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9674,7 +9674,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9694,7 +9694,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, times_y_vc_unk, times_y_vc_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A*B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A* " Int_FORMAT, PREG->u.yxn.c); setregs(); FAIL(); ENDP(pt0); @@ -9729,7 +9729,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9774,7 +9774,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9817,7 +9817,7 @@ Yap_absmi(int inp) d0 = p_div(MkIntegerTerm(d1),Yap_Eval(d0)); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9830,7 +9830,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, div_cv_unk, div_cv_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A//B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is " Int_FORMAT "// A", PREG->u.xxn.c); setregs(); FAIL(); ENDP(pt0); @@ -9865,7 +9865,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9917,7 +9917,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9968,7 +9968,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -9988,7 +9988,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, div_y_cv_unk, div_y_cv_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A//B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is " Int_FORMAT "// A", PREG->u.yxn.c); setregs(); FAIL(); ENDP(pt0); @@ -10017,7 +10017,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10062,7 +10062,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10075,7 +10075,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, and_vc_unk, and_vc_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A/\\B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A /\\ " Int_FORMAT , PREG->u.xxn.c); setregs(); FAIL(); ENDP(pt0); @@ -10103,7 +10103,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10155,7 +10155,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10175,7 +10175,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, and_y_vc_unk, and_y_vc_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A/\\B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A /\\ " Int_FORMAT , PREG->u.yxn.c); setregs(); FAIL(); ENDP(pt0); @@ -10204,7 +10204,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10248,7 +10248,7 @@ Yap_absmi(int inp) d0 = p_or(Yap_Eval(d0), MkIntegerTerm(d1)); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10261,7 +10261,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, or_vc_unk, or_vc_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A\\/B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A \\/ " Int_FORMAT , PREG->u.xxn.c); setregs(); FAIL(); ENDP(pt0); @@ -10289,7 +10289,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10341,7 +10341,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10361,7 +10361,7 @@ Yap_absmi(int inp) BEGP(pt0); deref_body(d0, pt0, or_y_vc_unk, or_y_vc_nvar); saveregs(); - Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A\\/B"); + Yap_Error(INSTANTIATION_ERROR, TermNil, "X is A \\/ " Int_FORMAT , PREG->u.yxn.c); setregs(); FAIL(); ENDP(pt0); @@ -10394,7 +10394,7 @@ Yap_absmi(int inp) } if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10440,7 +10440,7 @@ Yap_absmi(int inp) } if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10481,7 +10481,7 @@ Yap_absmi(int inp) } if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10525,7 +10525,7 @@ Yap_absmi(int inp) } if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10578,7 +10578,7 @@ Yap_absmi(int inp) } if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10627,7 +10627,7 @@ Yap_absmi(int inp) } if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10678,7 +10678,7 @@ Yap_absmi(int inp) } if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10722,7 +10722,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10765,7 +10765,7 @@ Yap_absmi(int inp) } if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10810,7 +10810,7 @@ Yap_absmi(int inp) BEGP(pt0); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10860,7 +10860,7 @@ Yap_absmi(int inp) setregs(); if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -10909,7 +10909,7 @@ Yap_absmi(int inp) } if (d0 == 0L) { saveregs(); - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); setregs(); FAIL(); } @@ -11285,9 +11285,9 @@ Yap_absmi(int inp) * We may wake up goals during our attempt to unify the * two terms. If we are adding to the tail of a list of * woken goals that should be ok, but otherwise we need - * to restore WokenGoals to its previous value. + * to restore LOCAL_WokenGoals to its previous value. */ - CELL OldWokenGoals = Yap_ReadTimedVar(WokenGoals); + CELL OldWokenGoals = Yap_ReadTimedVar(LOCAL_WokenGoals); #endif /* We will have to look inside compound terms */ @@ -11307,7 +11307,7 @@ Yap_absmi(int inp) opresult = Yap_IUnify(d0, d1); #ifdef COROUTINING /* now restore Woken Goals to its old value */ - Yap_UpdateTimedVar(WokenGoals, OldWokenGoals); + Yap_UpdateTimedVar(LOCAL_WokenGoals, OldWokenGoals); if (OldWokenGoals == TermNil) { Yap_undo_signal(YAP_WAKEUP_SIGNAL); } @@ -12007,7 +12007,7 @@ Yap_absmi(int inp) /* make sure we have something to show for our trouble */ saveregs(); if (!Yap_gcl((1+d1)*sizeof(CELL), 0, YREG, NEXTOP(NEXTOP(PREG,xxx),Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); setregs(); JMPNext(); } else { @@ -12124,7 +12124,7 @@ Yap_absmi(int inp) /* make sure we have something to show for our trouble */ saveregs(); if (!Yap_gcl((1+d1)*sizeof(CELL), 0, YREG, NEXTOP(NEXTOP(PREG,xxc),Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); setregs(); JMPNext(); } else { @@ -12234,7 +12234,7 @@ Yap_absmi(int inp) /* make sure we have something to show for our trouble */ saveregs(); if (!Yap_gc(0, YREG, NEXTOP(NEXTOP(PREG,xxn),Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); setregs(); JMPNext(); } else { @@ -12345,7 +12345,7 @@ Yap_absmi(int inp) /* make sure we have something to show for our trouble */ saveregs(); if (!Yap_gcl((1+d1)*sizeof(CELL), 0, YREG, NEXTOP(NEXTOP(PREG,yxx),Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); setregs(); JMPNext(); } else { @@ -12484,7 +12484,7 @@ Yap_absmi(int inp) /* make sure we have something to show for our trouble */ saveregs(); if (!Yap_gcl((1+d1)*sizeof(CELL), 0, YREG, NEXTOP(NEXTOP(PREG,yxn),Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); setregs(); JMPNext(); } else { @@ -12628,7 +12628,7 @@ Yap_absmi(int inp) /* make sure we have something to show for our trouble */ saveregs(); if (!Yap_gcl((1+d1)*sizeof(CELL), 0, YREG, NEXTOP(NEXTOP(PREG,yxn),Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); setregs(); JMPNext(); } else { @@ -13008,7 +13008,7 @@ Yap_absmi(int inp) /* make sure we have something to show for our trouble */ saveregs(); if (!Yap_gcl((1+d1)*sizeof(CELL), 3, YREG, NEXTOP(NEXTOP(PREG,e),Osbmp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); setregs(); JMPNext(); } else { @@ -13234,9 +13234,9 @@ Yap_absmi(int inp) ENDD(d0); NoStackPExecute2: - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); goto fail; } @@ -13248,12 +13248,12 @@ Yap_absmi(int inp) /* setup GB */ WRITEBACK_Y_AS_ENV(); YREG[E_CB] = (CELL) B; - if (ActiveSignals) { + if (LOCAL_ActiveSignals) { goto creep_pe; } saveregs_and_ycache(); if (!Yap_gc(((PredEntry *)SREG)->ArityOfPE, ENV, NEXTOP(PREG, Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); } setregs_and_ycache(); goto execute2_end; @@ -13439,9 +13439,9 @@ Yap_absmi(int inp) ENDD(d0); NoStackPExecute: - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); goto fail; } @@ -13453,12 +13453,12 @@ Yap_absmi(int inp) /* setup GB */ WRITEBACK_Y_AS_ENV(); YREG[E_CB] = (CELL) B; - if (ActiveSignals) { + if (LOCAL_ActiveSignals) { goto creep_pe; } saveregs_and_ycache(); if (!Yap_gc(((PredEntry *)SREG)->ArityOfPE, ENV, NEXTOP(PREG, Osbmp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); } setregs_and_ycache(); goto execute_end; @@ -13671,9 +13671,9 @@ Yap_absmi(int inp) ENDD(d0); ENDP(pt0); NoStackPTExecute: - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); goto fail; } @@ -13683,26 +13683,26 @@ Yap_absmi(int inp) ASP = ENV_YREG; if (ASP > (CELL *)PROTECT_FROZEN_B(B)) ASP = (CELL *)PROTECT_FROZEN_B(B); - LOCK(SignalLock); - if (ActiveSignals & YAP_CDOVF_SIGNAL) { - UNLOCK(SignalLock); + LOCK(LOCAL_SignalLock); + if (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { + UNLOCK(LOCAL_SignalLock); saveregs_and_ycache(); if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", LOCAL_ErrorMessage); setregs_and_ycache(); FAIL(); } setregs_and_ycache(); - LOCK(SignalLock); - ActiveSignals &= ~YAP_CDOVF_SIGNAL; + LOCK(LOCAL_SignalLock); + LOCAL_ActiveSignals &= ~YAP_CDOVF_SIGNAL; CreepFlag = CalculateStackGap(); - if (!ActiveSignals) { - UNLOCK(SignalLock); + if (!LOCAL_ActiveSignals) { + UNLOCK(LOCAL_SignalLock); goto execute_after_comma; } } - if (ActiveSignals & YAP_TROVF_SIGNAL) { - UNLOCK(SignalLock); + if (LOCAL_ActiveSignals & YAP_TROVF_SIGNAL) { + UNLOCK(LOCAL_SignalLock); #ifdef SHADOW_S S = SREG; #endif @@ -13713,26 +13713,26 @@ Yap_absmi(int inp) FAIL(); } setregs_and_ycache(); - ActiveSignals &= ~YAP_TROVF_SIGNAL; + LOCAL_ActiveSignals &= ~YAP_TROVF_SIGNAL; CreepFlag = CalculateStackGap(); - if (!ActiveSignals) { - UNLOCK(SignalLock); + if (!LOCAL_ActiveSignals) { + UNLOCK(LOCAL_SignalLock); goto execute_after_comma; } } - if (ActiveSignals) { - if (ActiveSignals & YAP_CDOVF_SIGNAL) { - UNLOCK(SignalLock); + if (LOCAL_ActiveSignals) { + if (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { + UNLOCK(LOCAL_SignalLock); SREG = YENV; goto noheapleft; } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); goto creep; } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); saveregs_and_ycache(); if (!Yap_gc(((PredEntry *)SREG)->ArityOfPE, ENV, NEXTOP(PREG, Osbpp))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); } setregs_and_ycache(); goto execute_after_comma; diff --git a/C/adtdefs.c b/C/adtdefs.c index 7c637dca0..cf7cea954 100755 --- a/C/adtdefs.c +++ b/C/adtdefs.c @@ -840,8 +840,8 @@ Yap_NewThreadPred(PredEntry *ap USES_REGS) p->beamTable = NULL; #endif /* careful that they don't cross MkFunctor */ - p->NextOfPE = AbsPredProp(MY_ThreadHandle.local_preds); - MY_ThreadHandle.local_preds = p; + p->NextOfPE = AbsPredProp(LOCAL_ThreadHandle.local_preds); + LOCAL_ThreadHandle.local_preds = p; p->FunctorOfPred = ap->FunctorOfPred; #ifdef LOW_PROF if (ProfilerOn && diff --git a/C/agc.c b/C/agc.c index 6f91934be..a8fe53696 100755 --- a/C/agc.c +++ b/C/agc.c @@ -18,7 +18,6 @@ static char SccsId[] = "@(#)agc.c 1.3 3/15/90"; #endif - #include "absmi.h" #include "Foreign.h" #include "alloc.h" @@ -30,20 +29,12 @@ static char SccsId[] = "@(#)agc.c 1.3 3/15/90"; /* #define DEBUG_RESTORE1 1 */ /* #define DEBUG_RESTORE2 1 */ /* #define DEBUG_RESTORE3 1 */ -#define errout Yap_stderr +#define errout GLOBAL_stderr #endif STATIC_PROTO(void RestoreEntries, (PropEntry *, int USES_REGS)); STATIC_PROTO(void CleanCode, (PredEntry * USES_REGS)); -static int agc_calls; - -static YAP_ULONG_LONG agc_collected; - -static Int tot_agc_time = 0; /* total time spent in GC */ - -static Int tot_agc_recovered = 0; /* number of heap objects in all garbage collections */ - #define AtomMarkedBit 1 static inline void @@ -225,16 +216,16 @@ RestoreHashPreds( USES_REGS1 ) static void init_reg_copies(USES_REGS1) { - OldASP = ASP; - OldLCL0 = LCL0; - OldTR = TR; - OldGlobalBase = (CELL *)Yap_GlobalBase; - OldH = H; - OldH0 = H0; - OldTrailBase = Yap_TrailBase; - OldTrailTop = Yap_TrailTop; - OldHeapBase = Yap_HeapBase; - OldHeapTop = HeapTop; + LOCAL_OldASP = ASP; + LOCAL_OldLCL0 = LCL0; + LOCAL_OldTR = TR; + LOCAL_OldGlobalBase = (CELL *)LOCAL_GlobalBase; + LOCAL_OldH = H; + LOCAL_OldH0 = H0; + LOCAL_OldTrailBase = LOCAL_TrailBase; + LOCAL_OldTrailTop = LOCAL_TrailTop; + LOCAL_OldHeapBase = Yap_HeapBase; + LOCAL_OldHeapTop = HeapTop; } @@ -262,7 +253,7 @@ mark_trail(USES_REGS1) pt = TR; /* moving the trail is simple */ - while (pt != (tr_fr_ptr)Yap_TrailBase) { + while (pt != (tr_fr_ptr)LOCAL_TrailBase) { CELL reg = TrailTerm(pt-1); if (!IsVarTerm(reg)) { @@ -384,7 +375,7 @@ clean_atom_list(AtomHashEntry *HashPtr) AtomEntry *at = RepAtom(atm); if (AtomResetMark(at) || at->PropsOfAE != NIL || - (Yap_AGCHook != NULL && !Yap_AGCHook(atm))) { + (GLOBAL_AGCHook != NULL && !GLOBAL_AGCHook(atm))) { patm = &(at->NextOfAE); atm = at->NextOfAE; } else { @@ -393,12 +384,12 @@ clean_atom_list(AtomHashEntry *HashPtr) #ifdef DEBUG_RESTORE3 fprintf(stderr, "Purged %p:%S\n", at, at->WStrOfAE); #endif - agc_collected += sizeof(AtomEntry)+wcslen(at->WStrOfAE); + GLOBAL_agc_collected += sizeof(AtomEntry)+wcslen(at->WStrOfAE); } else { #ifdef DEBUG_RESTORE3 fprintf(stderr, "Purged %p:%s patm=%p %p\n", at, at->StrOfAE, patm, at->NextOfAE); #endif - agc_collected += sizeof(AtomEntry)+strlen(at->StrOfAE); + GLOBAL_agc_collected += sizeof(AtomEntry)+strlen(at->StrOfAE); } *patm = atm = at->NextOfAE; Yap_FreeCodeSpace((char *)at); @@ -448,13 +439,13 @@ atom_gc(USES_REGS1) if (Yap_GetValue(AtomGcTrace) != TermNil) gc_trace = 1; - agc_calls++; - agc_collected = 0; + GLOBAL_agc_calls++; + GLOBAL_agc_collected = 0; if (gc_trace) { - fprintf(Yap_stderr, "%% agc:\n"); + fprintf(GLOBAL_stderr, "%% agc:\n"); } else if (gc_verbose) { - fprintf(Yap_stderr, "%% Start of atom garbage collection %d:\n", agc_calls); + fprintf(GLOBAL_stderr, "%% Start of atom garbage collection %d:\n", GLOBAL_agc_calls); } time_start = Yap_cputime(); /* get the number of active registers */ @@ -463,18 +454,17 @@ atom_gc(USES_REGS1) mark_stacks(PASS_REGS1); restore_codes(); clean_atoms(); - Yap_AGcLastCall = NOfAtoms; YAPLeaveCriticalSection(); agc_time = Yap_cputime()-time_start; - tot_agc_time += agc_time; - tot_agc_recovered += agc_collected; + GLOBAL_tot_agc_time += agc_time; + GLOBAL_tot_agc_recovered += GLOBAL_agc_collected; if (gc_verbose) { #ifdef _WIN32 - fprintf(Yap_stderr, "%% Collected %I64d bytes.\n", agc_collected); + fprintf(GLOBAL_stderr, "%% Collected %I64d bytes.\n", GLOBAL_agc_collected); #else - fprintf(Yap_stderr, "%% Collected %lld bytes.\n", agc_collected); + fprintf(GLOBAL_stderr, "%% Collected %lld bytes.\n", GLOBAL_agc_collected); #endif - fprintf(Yap_stderr, "%% GC %d took %g sec, total of %g sec doing GC so far.\n", agc_calls, (double)agc_time/1000, (double)tot_agc_time/1000); + fprintf(GLOBAL_stderr, "%% GC %d took %g sec, total of %g sec doing GC so far.\n", GLOBAL_agc_calls, (double)agc_time/1000, (double)GLOBAL_tot_agc_time/1000); } } @@ -496,9 +486,9 @@ p_atom_gc(USES_REGS1) static Int p_inform_agc(USES_REGS1) { - Term tn = MkIntegerTerm(tot_agc_time); - Term tt = MkIntegerTerm(agc_calls); - Term ts = MkIntegerTerm(tot_agc_recovered); + Term tn = MkIntegerTerm(GLOBAL_tot_agc_time); + Term tt = MkIntegerTerm(GLOBAL_agc_calls); + Term ts = MkIntegerTerm(GLOBAL_tot_agc_recovered); return Yap_unify(tn, ARG2) && @@ -511,7 +501,7 @@ p_agc_threshold(USES_REGS1) { Term t = Deref(ARG1); if (IsVarTerm(t)) { - return Yap_unify(ARG1, MkIntegerTerm(Yap_AGcThreshold)); + return Yap_unify(ARG1, MkIntegerTerm(GLOBAL_AGcThreshold)); } else if (!IsIntegerTerm(t)) { Yap_Error(TYPE_ERROR_INTEGER,t,"prolog_flag/2 agc_margin"); return FALSE; @@ -521,7 +511,7 @@ p_agc_threshold(USES_REGS1) Yap_Error(DOMAIN_ERROR_NOT_LESS_THAN_ZERO,t,"prolog_flag/2 agc_margin"); return FALSE; } else { - Yap_AGcThreshold = i; + GLOBAL_AGcThreshold = i; return TRUE; } } diff --git a/C/alloc.c b/C/alloc.c index 4d0b5362a..0f636d142 100755 --- a/C/alloc.c +++ b/C/alloc.c @@ -128,6 +128,7 @@ long long unsigned int tmalloc; static inline char * call_malloc(unsigned long int size) { + CACHE_REGS char *out; #if USE_DL_MALLOC LOCK(DLMallocLock); @@ -137,13 +138,13 @@ call_malloc(unsigned long int size) tmalloc += size; size += sizeof(CELL); #endif - Yap_PrologMode |= MallocMode; + LOCAL_PrologMode |= MallocMode; out = (char *) my_malloc(size); #if INSTRUMENT_MALLOC *(CELL*)out = size-sizeof(CELL); out += sizeof(CELL); #endif - Yap_PrologMode &= ~MallocMode; + LOCAL_PrologMode &= ~MallocMode; #if USE_DL_MALLOC UNLOCK(DLMallocLock); #endif @@ -160,6 +161,7 @@ Yap_AllocCodeSpace(unsigned long int size) static inline char * call_realloc(char *p, unsigned long int size) { + CACHE_REGS char *out; #if USE_DL_MALLOC LOCK(DLMallocLock); @@ -171,13 +173,13 @@ call_realloc(char *p, unsigned long int size) p -= sizeof(CELL); tmalloc -= *(CELL*)p; #endif - Yap_PrologMode |= MallocMode; + LOCAL_PrologMode |= MallocMode; out = (char *) my_realloc0(p, size); #if INSTRUMENT_MALLOC *(CELL*)out = size-sizeof(CELL); out += sizeof(CELL); #endif - Yap_PrologMode &= ~MallocMode; + LOCAL_PrologMode &= ~MallocMode; #if USE_DL_MALLOC UNLOCK(DLMallocLock); #endif @@ -194,17 +196,18 @@ Yap_ReallocCodeSpace(char *p, unsigned long int size) void Yap_FreeCodeSpace(char *p) { + CACHE_REGS #if USE_DL_MALLOC LOCK(DLMallocLock); #endif - Yap_PrologMode |= MallocMode; + LOCAL_PrologMode |= MallocMode; #if INSTRUMENT_MALLOC p -= sizeof(CELL); tmalloc -= *(CELL*)p; frees++; #endif my_free (p); - Yap_PrologMode &= ~MallocMode; + LOCAL_PrologMode &= ~MallocMode; #if USE_DL_MALLOC UNLOCK(DLMallocLock); #endif @@ -220,17 +223,18 @@ Yap_AllocAtomSpace(unsigned long int size) void Yap_FreeAtomSpace(char *p) { + CACHE_REGS #if USE_DL_MALLOC LOCK(DLMallocLock); #endif - Yap_PrologMode |= MallocMode; + LOCAL_PrologMode |= MallocMode; #if INSTRUMENT_MALLOC p -= sizeof(CELL); tmalloc -= *(CELL*)p; frees++; #endif my_free (p); - Yap_PrologMode &= ~MallocMode; + LOCAL_PrologMode &= ~MallocMode; #if USE_DL_MALLOC UNLOCK(DLMallocLock); #endif @@ -245,24 +249,24 @@ Yap_InitPreAllocCodeSpace(void) { CACHE_REGS char *ptr; - UInt sz = ScratchPad.msz; - if (ScratchPad.ptr == NULL) { + UInt sz = LOCAL_ScratchPad.msz; + if (LOCAL_ScratchPad.ptr == NULL) { #if USE_DL_MALLOC LOCK(DLMallocLock); #endif - Yap_PrologMode |= MallocMode; + LOCAL_PrologMode |= MallocMode; #if INSTRUMENT_MALLOC mallocs++; tmalloc += sz; sz += sizeof(CELL); #endif while (!(ptr = my_malloc(sz))) { - Yap_PrologMode &= ~MallocMode; + LOCAL_PrologMode &= ~MallocMode; #if USE_DL_MALLOC UNLOCK(DLMallocLock); #endif - if (!Yap_growheap(FALSE, Yap_Error_Size, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) { + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return(NULL); } #if INSTRUMENT_MALLOC @@ -273,18 +277,18 @@ Yap_InitPreAllocCodeSpace(void) #if USE_DL_MALLOC LOCK(DLMallocLock); #endif - Yap_PrologMode |= MallocMode; + LOCAL_PrologMode |= MallocMode; } - Yap_PrologMode &= ~MallocMode; + LOCAL_PrologMode &= ~MallocMode; #if USE_DL_MALLOC UNLOCK(DLMallocLock); #endif - ScratchPad.ptr = ptr; + LOCAL_ScratchPad.ptr = ptr; } else { - ptr = ScratchPad.ptr; + ptr = LOCAL_ScratchPad.ptr; } AuxBase = (ADDR)(ptr); - AuxSp = (CELL *)(AuxTop = AuxBase+ScratchPad.sz); + AuxSp = (CELL *)(AuxTop = AuxBase+LOCAL_ScratchPad.sz); return ptr; } @@ -293,11 +297,11 @@ Yap_ExpandPreAllocCodeSpace(UInt sz0, void *cip, int safe) { CACHE_REGS char *ptr; - UInt sz = ScratchPad.msz; + UInt sz = LOCAL_ScratchPad.msz; if (sz0 < SCRATCH_INC_SIZE) sz0 = SCRATCH_INC_SIZE; - if (sz0 < ScratchPad.sz) - sz = ScratchPad.sz+sz0; + if (sz0 < LOCAL_ScratchPad.sz) + sz = LOCAL_ScratchPad.sz+sz0; else sz = sz0; sz = AdjustLargePageSize(sz+sz/4); @@ -305,25 +309,25 @@ Yap_ExpandPreAllocCodeSpace(UInt sz0, void *cip, int safe) #if USE_DL_MALLOC LOCK(DLMallocLock); #endif - Yap_PrologMode |= MallocMode; + LOCAL_PrologMode |= MallocMode; #if INSTRUMENT_MALLOC reallocs++; - tmalloc -= ScratchPad.sz; + tmalloc -= LOCAL_ScratchPad.sz; tmalloc += sz; #endif - if (!(ptr = my_realloc(ScratchPad.ptr, sz, ScratchPad.sz, safe))) { - Yap_PrologMode &= ~MallocMode; + if (!(ptr = my_realloc(LOCAL_ScratchPad.ptr, sz, LOCAL_ScratchPad.sz, safe))) { + LOCAL_PrologMode &= ~MallocMode; #if USE_DL_MALLOC UNLOCK(DLMallocLock); #endif return NULL; } - Yap_PrologMode &= ~MallocMode; + LOCAL_PrologMode &= ~MallocMode; #if USE_DL_MALLOC UNLOCK(DLMallocLock); #endif - ScratchPad.sz = ScratchPad.msz = sz; - ScratchPad.ptr = ptr; + LOCAL_ScratchPad.sz = LOCAL_ScratchPad.msz = sz; + LOCAL_ScratchPad.ptr = ptr; AuxBase = ptr; AuxSp = (CELL *)(AuxTop = ptr+sz); return ptr; @@ -336,11 +340,7 @@ struct various_codes *Yap_heap_regs; static void InitHeap(void) { - CACHE_REGS Yap_heap_regs = (struct various_codes *)calloc(1, sizeof(struct various_codes)); -#if defined(YAPOR) || defined(TABLING) - LOCAL = REMOTE; /* point to the first area */ -#endif /* YAPOR || TABLING */ } void @@ -368,22 +368,22 @@ InitExStacks(int Trail, int Stack) #ifdef THREADS if (worker_id) - Yap_GlobalBase = (ADDR)MY_ThreadHandle.stack_address; + LOCAL_GlobalBase = (ADDR)LOCAL_ThreadHandle.stack_address; #endif - Yap_TrailTop = Yap_GlobalBase + pm; - Yap_LocalBase = Yap_GlobalBase + sa; - Yap_TrailBase = Yap_LocalBase + sizeof(CELL); + LOCAL_TrailTop = LOCAL_GlobalBase + pm; + LOCAL_LocalBase = LOCAL_GlobalBase + sa; + LOCAL_TrailBase = LOCAL_LocalBase + sizeof(CELL); - ScratchPad.ptr = NULL; - ScratchPad.sz = ScratchPad.msz = SCRATCH_START_SIZE; + LOCAL_ScratchPad.ptr = NULL; + LOCAL_ScratchPad.sz = LOCAL_ScratchPad.msz = SCRATCH_START_SIZE; AuxSp = NULL; #ifdef DEBUG - if (Yap_output_msg) { + if (GLOBAL_output_msg) { UInt ta; fprintf(stderr, "HeapBase = %p GlobalBase = %p\n LocalBase = %p TrailTop = %p\n", - Yap_HeapBase, Yap_GlobalBase, Yap_LocalBase, Yap_TrailTop); + Yap_HeapBase, LOCAL_GlobalBase, LOCAL_LocalBase, LOCAL_TrailTop); ta = Trail*K; /* trail area size */ fprintf(stderr, "Heap+Aux: %lu\tLocal+Global: %lu\tTrail: %lu\n", @@ -402,19 +402,19 @@ Yap_InitExStacks(int Trail, int Stack) void Yap_KillStacks(int wid) { - ADDR gb = FOREIGN_ThreadHandle(wid).stack_address; + ADDR gb = REMOTE_ThreadHandle(wid).stack_address; if (gb) { free(gb); - FOREIGN_ThreadHandle(wid).stack_address = NULL; + REMOTE_ThreadHandle(wid).stack_address = NULL; } } #else void Yap_KillStacks(void) { - if (Yap_GlobalBase) { - free(Yap_GlobalBase); - Yap_GlobalBase = NULL; + if (LOCAL_GlobalBase) { + free(LOCAL_GlobalBase); + LOCAL_GlobalBase = NULL; } } #endif @@ -429,15 +429,15 @@ int Yap_ExtendWorkSpace(Int s) { CACHE_REGS - void *basebp = (void *)Yap_GlobalBase, *nbp; - UInt s0 = (char *)Yap_TrailTop-(char *)Yap_GlobalBase; + void *basebp = (void *)LOCAL_GlobalBase, *nbp; + UInt s0 = (char *)LOCAL_TrailTop-(char *)LOCAL_GlobalBase; nbp = realloc(basebp, s+s0); if (nbp == NULL) return FALSE; #if defined(THREADS) - MY_ThreadHandle.stack_address = (char *)nbp; + LOCAL_ThreadHandle.stack_address = (char *)nbp; #endif - Yap_GlobalBase = (char *)nbp; + LOCAL_GlobalBase = (char *)nbp; return TRUE; } @@ -686,7 +686,7 @@ AllocHeap(unsigned long int size) HeapUsed += size * sizeof(CELL) + sizeof(YAP_SEG_SIZE); #ifdef YAPOR - if (HeapTop > Addr(Yap_GlobalBase) - MinHeapGap) + if (HeapTop > Addr(LOCAL_GlobalBase) - MinHeapGap) Yap_Error(INTERNAL_ERROR, TermNil, "no heap left (AllocHeap)"); #else if (HeapTop > HeapLim - MinHeapGap) { @@ -707,8 +707,8 @@ AllocHeap(unsigned long int size) UNLOCK(HeapTopLock); Yap_signal(YAP_CDOVF_SIGNAL); } else { - if (size > Yap_SizeOfOverflow) - Yap_SizeOfOverflow = size*sizeof(CELL) + sizeof(YAP_SEG_SIZE); + if (size > GLOBAL_SizeOfOverflow) + GLOBAL_SizeOfOverflow = size*sizeof(CELL) + sizeof(YAP_SEG_SIZE); /* big allocations, the caller must handle the problem */ UNLOCK(HeapUsedLock); UNLOCK(HeapTopLock); @@ -822,9 +822,9 @@ static int ExtendWorkSpace(Int s, int fixed_allocation) { LPVOID b = brk; - prolog_exec_mode OldPrologMode = Yap_PrologMode; + prolog_exec_mode OldPrologMode = LOCAL_PrologMode; - Yap_PrologMode = ExtendStackMode; + LOCAL_PrologMode = ExtendStackMode; #if DEBUG_WIN32_ALLOC fprintf(stderr,"trying: %p (" Int_FORMAT "K) %d\n",b, s/1024, fixed_allocation); @@ -838,7 +838,7 @@ ExtendWorkSpace(Int s, int fixed_allocation) } } if (!b) { - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; #if DEBUG_WIN32_ALLOC { char msg[256]; @@ -853,11 +853,11 @@ ExtendWorkSpace(Int s, int fixed_allocation) } b = VirtualAlloc(b, s, MEM_COMMIT, PAGE_READWRITE); if (!b) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "VirtualAlloc could not commit %ld bytes", (long int)s); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; #if DEBUG_WIN32_ALLOC fprintf(stderr,"NOT OK2: %p--%p\n",b,brk); #endif @@ -867,7 +867,7 @@ ExtendWorkSpace(Int s, int fixed_allocation) #if DEBUG_WIN32_ALLOC fprintf(stderr,"OK: %p--%p " Int_FORMAT "\n",b, brk, s); #endif - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return TRUE; } @@ -1025,6 +1025,8 @@ InitWorkSpace(Int s) return (void *) a; } + +#ifndef YAPOR static MALLOC_T mmap_extension(Int s, MALLOC_T base, int fixed_allocation) { @@ -1047,13 +1049,13 @@ mmap_extension(Int s, MALLOC_T base, int fixed_allocation) char file[256]; strncpy(file,"/tmp/YAP.TMPXXXXXX",256); if (mkstemp(file) == -1) { - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_ErrorMessage = LOCAL_ErrorSay; #if HAVE_STRERROR - snprintf5(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + snprintf5(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "mkstemp could not create temporary file %s (%s)", file, strerror(errno)); #else - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "mkstemp could not create temporary file %s", file); #endif /* HAVE_STRERROR */ return (MALLOC_T)-1; @@ -1069,28 +1071,28 @@ mmap_extension(Int s, MALLOC_T base, int fixed_allocation) #endif /* HAVE_MKSTEMP */ fd = open(file, O_CREAT|O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd < 0) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "mmap could not open %s", file); return (MALLOC_T)-1; } if (lseek(fd, s, SEEK_SET) < 0) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "mmap could not lseek in mmapped file %s", file); close(fd); return (MALLOC_T)-1; } if (write(fd, "", 1) < 0) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "mmap could not write in mmapped file %s", file); close(fd); return (MALLOC_T)-1; } if (unlink(file) < 0) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "mmap could not unlink mmapped file %s", file); close(fd); return (MALLOC_T)-1; @@ -1104,12 +1106,12 @@ mmap_extension(Int s, MALLOC_T base, int fixed_allocation) #endif , fd, 0); if (close(fd) == -1) { - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_ErrorMessage = LOCAL_ErrorSay; #if HAVE_STRERROR - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "mmap could not close file (%s) ]\n", strerror(errno)); #else - snprintf3(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + snprintf3(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "mmap could not close file ]\n"); #endif return (MALLOC_T)-1; @@ -1117,6 +1119,8 @@ mmap_extension(Int s, MALLOC_T base, int fixed_allocation) #endif return a; } +#endif /* !YAPOR */ + static int ExtendWorkSpace(Int s, int fixed_allocation) @@ -1126,23 +1130,23 @@ ExtendWorkSpace(Int s, int fixed_allocation) return(FALSE); #else MALLOC_T a; - prolog_exec_mode OldPrologMode = Yap_PrologMode; + prolog_exec_mode OldPrologMode = LOCAL_PrologMode; MALLOC_T base = WorkSpaceTop; if (fixed_allocation == MAP_FIXED) base = WorkSpaceTop; else base = 0L; - Yap_PrologMode = ExtendStackMode; + LOCAL_PrologMode = ExtendStackMode; a = mmap_extension(s, base, fixed_allocation); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; if (a == (MALLOC_T) - 1) { - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_ErrorMessage = LOCAL_ErrorSay; #if HAVE_STRERROR - snprintf5(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + snprintf5(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "could not allocate %d bytes (%s)", (int)s, strerror(errno)); #else - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "could not allocate %d bytes", (int)s); #endif return FALSE; @@ -1150,10 +1154,10 @@ ExtendWorkSpace(Int s, int fixed_allocation) if (fixed_allocation) { if (a != WorkSpaceTop) { munmap((void *)a, (size_t)s); - Yap_ErrorMessage = Yap_ErrorSay; - snprintf5(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf5(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "mmap could not grow memory at %p, got %p", WorkSpaceTop, a ); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return FALSE; } } else if (a < WorkSpaceTop) { @@ -1164,7 +1168,7 @@ ExtendWorkSpace(Int s, int fixed_allocation) return res; } WorkSpaceTop = (char *) a + s; - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return TRUE; #endif /* YAPOR */ } @@ -1215,33 +1219,33 @@ ExtendWorkSpace(Int s) { MALLOC_T ptr; int shm_id; - prolog_exec_mode OldPrologMode = Yap_PrologMode; + prolog_exec_mode OldPrologMode = LOCAL_PrologMode; - Yap_PrologMode = ExtendStackMode; + LOCAL_PrologMode = ExtendStackMode; /* mapping heap area */ if((shm_id = shmget(IPC_PRIVATE, (size_t)s, SHM_R|SHM_W)) == -1) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "could not shmget %d bytes", s); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return(FALSE); } if((ptr = (MALLOC_T)shmat(shm_id, WorkSpaceTop, 0)) == (MALLOC_T) -1) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "could not shmat at %p", MMAP_ADDR); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return(FALSE); } if (shmctl(shm_id, IPC_RMID, 0) != 0) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "could not remove shm segment", shm_id); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return(FALSE); } WorkSpaceTop = (char *) ptr + s; - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return(TRUE); } @@ -1290,17 +1294,17 @@ static int ExtendWorkSpace(Int s) { MALLOC_T ptr = (MALLOC_T)sbrk(s); - prolog_exec_mode OldPrologMode = Yap_PrologMode; + prolog_exec_mode OldPrologMode = LOCAL_PrologMode; - Yap_PrologMode = ExtendStackMode; + LOCAL_PrologMode = ExtendStackMode; if (ptr == ((MALLOC_T) - 1)) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "could not expand stacks over %d bytes", s); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return(FALSE); } - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return TRUE; } @@ -1420,34 +1424,34 @@ static int ExtendWorkSpace(Int s) { MALLOC_T ptr; - prolog_exec_mode OldPrologMode = Yap_PrologMode; + prolog_exec_mode OldPrologMode = LOCAL_PrologMode; - Yap_PrologMode = ExtendStackMode; + LOCAL_PrologMode = ExtendStackMode; total_space += s; if (total_space < MAX_SPACE) return TRUE; ptr = (MALLOC_T)realloc((void *)Yap_HeapBase, total_space); if (ptr == NULL) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "could not allocate %d bytes", s); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return FALSE; } if (ptr != (MALLOC_T)Yap_HeapBase) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf4(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf4(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "could not expand contiguous stacks %d bytes", s); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return FALSE; } if ((CELL)ptr & MBIT) { - Yap_ErrorMessage = Yap_ErrorSay; - snprintf5(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, + LOCAL_ErrorMessage = LOCAL_ErrorSay; + snprintf5(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, "memory at %p conflicts with MBIT %lx", ptr, (unsigned long)MBIT); - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return FALSE; } - Yap_PrologMode = OldPrologMode; + LOCAL_PrologMode = OldPrologMode; return TRUE; } @@ -1479,10 +1483,6 @@ InitHeap(void *heap_addr) #endif FreeBlocks = NIL; - -#if defined(YAPOR) || defined(TABLING) - LOCAL = REMOTE; /* point to the first area */ -#endif /* YAPOR || TABLING */ } void @@ -1521,27 +1521,27 @@ Yap_InitMemory(UInt Trail, UInt Heap, UInt Stack) InitHeap(addr); - Yap_TrailTop = Yap_HeapBase + pm; - Yap_LocalBase = Yap_TrailTop - ta; - Yap_TrailBase = Yap_LocalBase + sizeof(CELL); + LOCAL_TrailTop = Yap_HeapBase + pm; + LOCAL_LocalBase = LOCAL_TrailTop - ta; + LOCAL_TrailBase = LOCAL_LocalBase + sizeof(CELL); - Yap_GlobalBase = Yap_LocalBase - sa; - HeapLim = Yap_GlobalBase; /* avoid confusions while + LOCAL_GlobalBase = LOCAL_LocalBase - sa; + HeapLim = LOCAL_GlobalBase; /* avoid confusions while * * restoring */ #if !USE_DL_MALLOC - AuxTop = (ADDR)(AuxSp = (CELL *)Yap_GlobalBase); + AuxTop = (ADDR)(AuxSp = (CELL *)LOCAL_GlobalBase); #endif #ifdef DEBUG #if SIZEOF_INT_P!=SIZEOF_INT - if (Yap_output_msg) { + if (GLOBAL_output_msg) { fprintf(stderr, "HeapBase = %p GlobalBase = %p\n LocalBase = %p TrailTop = %p\n", - Yap_HeapBase, Yap_GlobalBase, Yap_LocalBase, Yap_TrailTop); + Yap_HeapBase, LOCAL_GlobalBase, LOCAL_LocalBase, LOCAL_TrailTop); #else - if (Yap_output_msg) { + if (GLOBAL_output_msg) { fprintf(stderr, "HeapBase = %x GlobalBase = %x\n LocalBase = %x TrailTop = %x\n", - (UInt) Yap_HeapBase, (UInt) Yap_GlobalBase, - (UInt) Yap_LocalBase, (UInt) Yap_TrailTop); + (UInt) Yap_HeapBase, (UInt) LOCAL_GlobalBase, + (UInt) LOCAL_LocalBase, (UInt) LOCAL_TrailTop); #endif fprintf(stderr, "Heap+Aux: " UInt_FORMAT "\tLocal+Global: " UInt_FORMAT "\tTrail: " UInt_FORMAT "\n", @@ -1554,8 +1554,8 @@ void Yap_InitExStacks(int Trail, int Stack) { #if USE_DL_MALLOC - ScratchPad.ptr = NULL; - ScratchPad.sz = ScratchPad.msz = SCRATCH_START_SIZE; + LOCAL_ScratchPad.ptr = NULL; + LOCAL_ScratchPad.sz = LOCAL_ScratchPad.msz = SCRATCH_START_SIZE; AuxSp = NULL; #endif } @@ -1596,7 +1596,7 @@ Yap_ExtendWorkSpaceThroughHole(UInt s) WorkSpaceTop += 512*1024; if (ExtendWorkSpace(s, MAP_FIXED)) { Yap_add_memory_hole((ADDR)WorkSpaceTop0, (ADDR)WorkSpaceTop-s); - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; return WorkSpaceTop-WorkSpaceTop0; } #if defined(_WIN32) @@ -1614,7 +1614,7 @@ Yap_ExtendWorkSpaceThroughHole(UInt s) WorkSpaceTop += 512*1024; if (ExtendWorkSpace(s, MAP_FIXED)) { Yap_add_memory_hole((ADDR)WorkSpaceTop0, (ADDR)WorkSpaceTop-s); - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; return WorkSpaceTop-WorkSpaceTop0; } #if defined(_WIN32) diff --git a/C/amasm.c b/C/amasm.c index eb8e3afba..5807a8469 100755 --- a/C/amasm.c +++ b/C/amasm.c @@ -434,8 +434,8 @@ DumpOpCodes(void) while (i < 30) { for (j = i; j <= _std_top; j += 25) - fprintf(Yap_stderr, "%5d %6lx", j, absmadr(j)); - fputc('\n',Yap_stderr); + fprintf(GLOBAL_stderr, "%5d %6lx", j, absmadr(j)); + fputc('\n',GLOBAL_stderr); ++i; } } @@ -2196,9 +2196,9 @@ static yamop * a_gl(op_numbers opcode, yamop *code_p, int pass_no, struct PSEUDO *cpc, struct intermediates *cip USES_REGS) { #ifdef YAPOR - return a_try(opcode, cpc->rnd1, IPredArity, cpc->rnd2 >> 1, cpc->rnd2 & 1, code_p, pass_no, cip); + return a_try(opcode, cpc->rnd1, LOCAL_IPredArity, cpc->rnd2 >> 1, cpc->rnd2 & 1, code_p, pass_no, cip); #else - return a_try(opcode, cpc->rnd1, IPredArity, code_p, pass_no, cip); + return a_try(opcode, cpc->rnd1, LOCAL_IPredArity, code_p, pass_no, cip); #endif /* YAPOR */ } @@ -2429,13 +2429,13 @@ a_fetch_vv(cmp_op_info *cmp_info, int pass_no, struct intermediates *cip) PInstr *p = cip->cpc->nextInst; Ventry *ve; ve = (Ventry *) p->rnd1; - if (ve->KindOfVE != PermVar && p->op != nop_op) { + if (ve->KindOfVE != PermVar && p->op != nop_op && p->op != put_var_op) { p->rnd2 = ve->NoOfVE & MaskVarAdrs; p->op = nop_op; } p = p->nextInst; ve = (Ventry *) p->rnd1; - if (ve->KindOfVE != PermVar && p->op != nop_op) { + if (ve->KindOfVE != PermVar && p->op != nop_op && p->op != put_var_op) { p->rnd2 = ve->NoOfVE & MaskVarAdrs; p->op = nop_op; } @@ -2458,7 +2458,7 @@ a_fetch_vc(cmp_op_info *cmp_info, int pass_no, struct intermediates *cip) PInstr *p = cip->cpc->nextInst; Ventry *ve; ve = (Ventry *) p->rnd1; - if (ve->KindOfVE != PermVar && p->op != nop_op) { + if (ve->KindOfVE != PermVar && p->op != nop_op && p->op != put_var_op) { p->rnd2 = ve->NoOfVE & MaskVarAdrs; p->op = nop_op; } @@ -2479,7 +2479,7 @@ a_fetch_cv(cmp_op_info *cmp_info, int pass_no, struct intermediates *cip) PInstr *p = cip->cpc->nextInst; Ventry *ve; ve = (Ventry *) p->rnd1; - if (ve->KindOfVE != PermVar && p->op != nop_op) { + if (ve->KindOfVE != PermVar && p->op != nop_op && p->op != put_var_op) { p->rnd2 = ve->NoOfVE & MaskVarAdrs; p->op = nop_op; } @@ -2981,11 +2981,11 @@ a_special_label(yamop *code_p, int pass_no, struct intermediates *cip) #ifdef YAPOR -#define TRYCODE(G,P) a_try((G), Unsigned(cip->code_addr) + cip->label_offset[cip->cpc->rnd1], IPredArity, cip->cpc->rnd2 >> 1, cip->cpc->rnd2 & 1, code_p, pass_no, cip) -#define TABLE_TRYCODE(G) a_try((G), (CELL)emit_ilabel(cip->cpc->rnd1, cip), IPredArity, cip->cpc->rnd2 >> 1, cip->cpc->rnd2 & 1, code_p, pass_no, cip) +#define TRYCODE(G,P) a_try((G), Unsigned(cip->code_addr) + cip->label_offset[cip->cpc->rnd1], LOCAL_IPredArity, cip->cpc->rnd2 >> 1, cip->cpc->rnd2 & 1, code_p, pass_no, cip) +#define TABLE_TRYCODE(G) a_try((G), (CELL)emit_ilabel(cip->cpc->rnd1, cip), LOCAL_IPredArity, cip->cpc->rnd2 >> 1, cip->cpc->rnd2 & 1, code_p, pass_no, cip) #else -#define TRYCODE(G,P) a_try((G), Unsigned(cip->code_addr) + cip->label_offset[cip->cpc->rnd1], IPredArity, code_p, pass_no, cip) -#define TABLE_TRYCODE(G) a_try((G), (CELL)emit_ilabel(cip->cpc->rnd1, cip), IPredArity, code_p, pass_no, cip) +#define TRYCODE(G,P) a_try((G), Unsigned(cip->code_addr) + cip->label_offset[cip->cpc->rnd1], LOCAL_IPredArity, code_p, pass_no, cip) +#define TABLE_TRYCODE(G) a_try((G), (CELL)emit_ilabel(cip->cpc->rnd1, cip), LOCAL_IPredArity, code_p, pass_no, cip) #endif /* YAPOR */ static yamop * @@ -3093,22 +3093,22 @@ do_pass(int pass_no, yamop **entry_codep, int assembling, int *clause_has_blobsp } code_p = cl_u->sc.ClCode; } - IPredArity = cip->CurrentPred->ArityOfPE; /* number of args */ + LOCAL_IPredArity = cip->CurrentPred->ArityOfPE; /* number of args */ *entry_codep = code_p; if (tabled) { #if TABLING #ifdef YAPOR - code_p = a_try(_table_try_single, (CELL)NEXTOP(code_p,Otapl), IPredArity, 1, 0, code_p, pass_no, cip); + code_p = a_try(_table_try_single, (CELL)NEXTOP(code_p,Otapl), LOCAL_IPredArity, 1, 0, code_p, pass_no, cip); #else - code_p = a_try(_table_try_single, (CELL)NEXTOP(code_p,Otapl), IPredArity, code_p, pass_no, cip); + code_p = a_try(_table_try_single, (CELL)NEXTOP(code_p,Otapl), LOCAL_IPredArity, code_p, pass_no, cip); #endif #endif } if (dynamic) { #ifdef YAPOR - code_p = a_try(_try_me, 0, IPredArity, 1, 0, code_p, pass_no, cip); + code_p = a_try(_try_me, 0, LOCAL_IPredArity, 1, 0, code_p, pass_no, cip); #else - code_p = a_try(_try_me, 0, IPredArity, code_p, pass_no, cip); + code_p = a_try(_try_me, 0, LOCAL_IPredArity, code_p, pass_no, cip); #endif /* YAPOR */ } } else { @@ -3541,7 +3541,7 @@ do_pass(int pass_no, yamop **entry_codep, int assembling, int *clause_has_blobsp if (!pass_no) { #if !USE_SYSTEM_MALLOC if (CellPtr(cip->label_offset+cip->cpc->rnd1) > ASP-256) { - Yap_Error_Size = 256+((char *)(cip->label_offset+cip->cpc->rnd1) - (char *)H); + LOCAL_Error_Size = 256+((char *)(cip->label_offset+cip->cpc->rnd1) - (char *)H); save_machine_regs(); siglongjmp(cip->CompilerBotch, 3); } @@ -3787,9 +3787,9 @@ fetch_clause_space(Term* tp, UInt size, struct intermediates *cip, UInt *osizep while ((x = Yap_StoreTermInDBPlusExtraSpace(*tp, size, osizep)) == NULL) { H = h0; - switch (Yap_Error_TYPE) { + switch (LOCAL_Error_TYPE) { case OUT_OF_STACK_ERROR: - Yap_Error_Size = 256+((char *)cip->freep - (char *)H); + LOCAL_Error_Size = 256+((char *)cip->freep - (char *)H); save_machine_regs(); siglongjmp(cip->CompilerBotch,3); case OUT_OF_TRAIL_ERROR: @@ -3798,15 +3798,15 @@ fetch_clause_space(Term* tp, UInt size, struct intermediates *cip, UInt *osizep if (!Yap_growtrail(K64, FALSE)) { return NULL; } - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; *tp = ARG1; break; case OUT_OF_AUXSPACE_ERROR: ARG1 = *tp; - if (!Yap_ExpandPreAllocCodeSpace(Yap_Error_Size, (void *)cip, TRUE)) { + if (!Yap_ExpandPreAllocCodeSpace(LOCAL_Error_Size, (void *)cip, TRUE)) { return NULL; } - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; *tp = ARG1; break; case OUT_OF_HEAP_ERROR: @@ -3815,7 +3815,7 @@ fetch_clause_space(Term* tp, UInt size, struct intermediates *cip, UInt *osizep if (!Yap_growheap(TRUE, size, cip)) { return NULL; } - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; *tp = ARG1; break; default: @@ -3864,16 +3864,16 @@ Yap_assemble(int mode, Term t, PredEntry *ap, int is_fact, struct intermediates #if USE_SYSTEM_MALLOC if (!cip->label_offset) { - if (!Yap_LabelFirstArray && max_label <= DEFAULT_NLABELS) { - Yap_LabelFirstArray = (Int *)Yap_AllocCodeSpace(sizeof(Int)*DEFAULT_NLABELS); - Yap_LabelFirstArraySz = DEFAULT_NLABELS; - if (!Yap_LabelFirstArray) { + if (!LOCAL_LabelFirstArray && max_label <= DEFAULT_NLABELS) { + LOCAL_LabelFirstArray = (Int *)Yap_AllocCodeSpace(sizeof(Int)*DEFAULT_NLABELS); + LOCAL_LabelFirstArraySz = DEFAULT_NLABELS; + if (!LOCAL_LabelFirstArray) { save_machine_regs(); siglongjmp(cip->CompilerBotch, OUT_OF_HEAP_BOTCH); } } - if (Yap_LabelFirstArray && max_label <= Yap_LabelFirstArraySz) { - cip->label_offset = Yap_LabelFirstArray; + if (LOCAL_LabelFirstArray && max_label <= LOCAL_LabelFirstArraySz) { + cip->label_offset = LOCAL_LabelFirstArray; } else { cip->label_offset = (Int *)Yap_AllocCodeSpace(sizeof(Int)*max_label); if (!cip->label_offset) { @@ -3926,14 +3926,14 @@ Yap_assemble(int mode, Term t, PredEntry *ap, int is_fact, struct intermediates /* make sure we copy after second pass */ cl->usc.ClSource = x; cl->ClSize = osize; - ProfEnd=code_p; + LOCAL_ProfEnd=code_p; return entry_code; } else { while ((cip->code_addr = (yamop *) Yap_AllocCodeSpace(size)) == NULL) { if (!Yap_growheap(TRUE, size, cip)) { - Yap_Error_TYPE = OUT_OF_HEAP_ERROR; - Yap_Error_Size = size; + LOCAL_Error_TYPE = OUT_OF_HEAP_ERROR; + LOCAL_Error_Size = size; return NULL; } } @@ -3950,11 +3950,11 @@ Yap_assemble(int mode, Term t, PredEntry *ap, int is_fact, struct intermediates } } code_p = do_pass(1, &entry_code, mode, &clause_has_blobs, &clause_has_dbterm, cip, size PASS_REGS); - ProfEnd=code_p; + LOCAL_ProfEnd=code_p; #ifdef LOW_PROF if (ProfilerOn && Yap_OffLineProfiler) { - Yap_inform_profiler_of_clause(entry_code, ProfEnd, ap, mode == ASSEMBLING_INDEX); + Yap_inform_profiler_of_clause(entry_code, LOCAL_ProfEnd, ap, mode == ASSEMBLING_INDEX); } #endif /* LOW_PROF */ return entry_code; diff --git a/C/analyst.c b/C/analyst.c index 1e32eec50..ec6b95985 100644 --- a/C/analyst.c +++ b/C/analyst.c @@ -28,9 +28,7 @@ static char SccsId[] = "%W% %G%"; #include #endif -YAP_ULONG_LONG Yap_opcount[_std_top + 1]; -YAP_ULONG_LONG Yap_2opcount[_std_top + 1][_std_top + 1]; STATIC_PROTO(Int p_reset_op_counters, (void)); @@ -43,7 +41,7 @@ p_reset_op_counters() int i; for (i = 0; i <= _std_top; ++i) - Yap_opcount[i] = 0; + GLOBAL_opcount[i] = 0; return TRUE; } @@ -52,26 +50,26 @@ print_instruction(int inst) { int j; - fprintf(Yap_stderr, "%s", Yap_op_names[inst]); + fprintf(GLOBAL_stderr, "%s", Yap_op_names[inst]); for (j = strlen(Yap_op_names[inst]); j < 25; j++) - putc(' ', Yap_stderr); - j = Yap_opcount[inst]; + putc(' ', GLOBAL_stderr); + j = GLOBAL_opcount[inst]; if (j < 100000000) { - putc(' ', Yap_stderr); + putc(' ', GLOBAL_stderr); if (j < 10000000) { - putc(' ', Yap_stderr); + putc(' ', GLOBAL_stderr); if (j < 1000000) { - putc(' ', Yap_stderr); + putc(' ', GLOBAL_stderr); if (j < 100000) { - putc(' ', Yap_stderr); + putc(' ', GLOBAL_stderr); if (j < 10000) { - putc(' ', Yap_stderr); + putc(' ', GLOBAL_stderr); if (j < 1000) { - putc(' ', Yap_stderr); + putc(' ', GLOBAL_stderr); if (j < 100) { - putc(' ', Yap_stderr); + putc(' ', GLOBAL_stderr); if (j < 10) { - putc(' ', Yap_stderr); + putc(' ', GLOBAL_stderr); } } } @@ -80,7 +78,7 @@ print_instruction(int inst) } } } - fprintf(Yap_stderr, "%llu\n", Yap_opcount[inst]); + fprintf(GLOBAL_stderr, "%llu\n", GLOBAL_opcount[inst]); } static Int @@ -98,18 +96,18 @@ p_show_op_counters() wchar_t *program; program = RepAtom(at1)->WStrOfAE; - fprintf(Yap_stderr, "\n Instructions Executed in %S\n", program); + fprintf(GLOBAL_stderr, "\n Instructions Executed in %S\n", program); } else { char *program; program = RepAtom(at1)->StrOfAE; - fprintf(Yap_stderr, "\n Instructions Executed in %s\n", program); + fprintf(GLOBAL_stderr, "\n Instructions Executed in %s\n", program); } } for (i = 0; i <= _std_top; ++i) print_instruction(i); - fprintf(Yap_stderr, "\n Control Instructions \n"); + fprintf(GLOBAL_stderr, "\n Control Instructions \n"); print_instruction(_op_fail); print_instruction(_execute); print_instruction(_dexecute); @@ -121,7 +119,7 @@ p_show_op_counters() print_instruction(_allocate); print_instruction(_deallocate); - fprintf(Yap_stderr, "\n Choice Point Manipulation Instructions\n"); + fprintf(GLOBAL_stderr, "\n Choice Point Manipulation Instructions\n"); print_instruction(_try_me); print_instruction(_retry_me); print_instruction(_trust_me); @@ -130,38 +128,38 @@ p_show_op_counters() print_instruction(_retry); print_instruction(_trust); - fprintf(Yap_stderr, "\n Disjunction Instructions\n"); + fprintf(GLOBAL_stderr, "\n Disjunction Instructions\n"); print_instruction(_either); print_instruction(_or_else); print_instruction(_or_last); print_instruction(_jump); print_instruction(_move_back); - fprintf(Yap_stderr, "\n Dynamic Predicates Choicepoint Instructions\n"); + fprintf(GLOBAL_stderr, "\n Dynamic Predicates Choicepoint Instructions\n"); print_instruction(_try_and_mark); print_instruction(_retry_and_mark); - fprintf(Yap_stderr, "\n C Predicates Choicepoint Instructions\n"); + fprintf(GLOBAL_stderr, "\n C Predicates Choicepoint Instructions\n"); print_instruction(_try_c); print_instruction(_retry_c); - fprintf(Yap_stderr, "\n Indexing Instructions\n"); - fprintf(Yap_stderr, "\n Switch on Type\n"); + fprintf(GLOBAL_stderr, "\n Indexing Instructions\n"); + fprintf(GLOBAL_stderr, "\n Switch on Type\n"); print_instruction(_switch_on_type); print_instruction(_switch_list_nl); print_instruction(_switch_on_arg_type); print_instruction(_switch_on_sub_arg_type); - fprintf(Yap_stderr, "\n Switch on Value\n"); + fprintf(GLOBAL_stderr, "\n Switch on Value\n"); print_instruction(_if_cons); print_instruction(_go_on_cons); print_instruction(_switch_on_cons); print_instruction(_if_func); print_instruction(_go_on_func); print_instruction(_switch_on_func); - fprintf(Yap_stderr, "\n Other Switches\n"); + fprintf(GLOBAL_stderr, "\n Other Switches\n"); print_instruction(_if_not_then); - fprintf(Yap_stderr, "\n Get Instructions\n"); + fprintf(GLOBAL_stderr, "\n Get Instructions\n"); print_instruction(_get_x_var); print_instruction(_get_y_var); print_instruction(_get_x_val); @@ -174,7 +172,7 @@ p_show_op_counters() print_instruction(_get_6atoms); print_instruction(_get_list); print_instruction(_get_struct); - fprintf(Yap_stderr, "\n Optimised Get Instructions\n"); + fprintf(GLOBAL_stderr, "\n Optimised Get Instructions\n"); print_instruction(_glist_valx); print_instruction(_glist_valy); print_instruction(_gl_void_varx); @@ -182,7 +180,7 @@ p_show_op_counters() print_instruction(_gl_void_valx); print_instruction(_gl_void_valy); - fprintf(Yap_stderr, "\n Unify Read Instructions\n"); + fprintf(GLOBAL_stderr, "\n Unify Read Instructions\n"); print_instruction(_unify_x_var); print_instruction(_unify_x_var2); print_instruction(_unify_y_var); @@ -195,7 +193,7 @@ p_show_op_counters() print_instruction(_unify_n_voids); print_instruction(_unify_list); print_instruction(_unify_struct); - fprintf(Yap_stderr, "\n Unify Last Read Instructions\n"); + fprintf(GLOBAL_stderr, "\n Unify Last Read Instructions\n"); print_instruction(_unify_l_x_var); print_instruction(_unify_l_x_var2); print_instruction(_unify_l_y_var); @@ -208,7 +206,7 @@ p_show_op_counters() print_instruction(_unify_l_list); print_instruction(_unify_l_struc); - fprintf(Yap_stderr, "\n Unify Write Instructions\n"); + fprintf(GLOBAL_stderr, "\n Unify Write Instructions\n"); print_instruction(_unify_x_var_write); print_instruction(_unify_x_var2_write); print_instruction(_unify_y_var_write); @@ -221,7 +219,7 @@ p_show_op_counters() print_instruction(_unify_n_voids_write); print_instruction(_unify_list_write); print_instruction(_unify_struct_write); - fprintf(Yap_stderr, "\n Unify Last Read Instructions\n"); + fprintf(GLOBAL_stderr, "\n Unify Last Read Instructions\n"); print_instruction(_unify_l_x_var_write); print_instruction(_unify_l_x_var2_write); print_instruction(_unify_l_y_var_write); @@ -234,7 +232,7 @@ p_show_op_counters() print_instruction(_unify_l_list_write); print_instruction(_unify_l_struc_write); - fprintf(Yap_stderr, "\n Put Instructions\n"); + fprintf(GLOBAL_stderr, "\n Put Instructions\n"); print_instruction(_put_x_var); print_instruction(_put_y_var); print_instruction(_put_x_val); @@ -245,7 +243,7 @@ p_show_op_counters() print_instruction(_put_list); print_instruction(_put_struct); - fprintf(Yap_stderr, "\n Write Instructions\n"); + fprintf(GLOBAL_stderr, "\n Write Instructions\n"); print_instruction(_write_x_var); print_instruction(_write_y_var); print_instruction(_write_x_val); @@ -257,11 +255,11 @@ p_show_op_counters() print_instruction(_write_n_voids); print_instruction(_write_list); print_instruction(_write_struct); - fprintf(Yap_stderr, "\n Last Write Instructions\n"); + fprintf(GLOBAL_stderr, "\n Last Write Instructions\n"); print_instruction(_write_l_list); print_instruction(_write_l_struc); - fprintf(Yap_stderr, "\n Miscellaneous Instructions\n"); + fprintf(GLOBAL_stderr, "\n Miscellaneous Instructions\n"); print_instruction(_cut); print_instruction(_cut_t); print_instruction(_cut_e); @@ -292,11 +290,11 @@ p_show_op_counters() typedef struct { int nxvar, nxval, nyvar, nyval, ncons, nlist, nstru, nmisc; -} uYap_opcount; +} uGLOBAL_opcount; typedef struct { int ncalls, nexecs, nproceeds, ncallbips, ncuts, nallocs, ndeallocs; -} cYap_opcount; +} cGLOBAL_opcount; typedef struct { int ntries, nretries, ntrusts; @@ -306,8 +304,8 @@ static Int p_show_ops_by_group(void) { - uYap_opcount c_get, c_unify, c_put, c_write; - cYap_opcount c_control; + uGLOBAL_opcount c_get, c_unify, c_put, c_write; + cGLOBAL_opcount c_control; ccpcount c_cp; int gets, unifies, puts, writes, controls, choice_pts, indexes, misc, total; @@ -322,261 +320,261 @@ p_show_ops_by_group(void) wchar_t *program; program = RepAtom(at1)->WStrOfAE; - fprintf(Yap_stderr, "\n Instructions Executed in %S\n", program); + fprintf(GLOBAL_stderr, "\n Instructions Executed in %S\n", program); } else { char *program; program = RepAtom(at1)->StrOfAE; - fprintf(Yap_stderr, "\n Instructions Executed in %s\n", program); + fprintf(GLOBAL_stderr, "\n Instructions Executed in %s\n", program); } c_get.nxvar = - Yap_opcount[_get_x_var]; + GLOBAL_opcount[_get_x_var]; c_get.nyvar = - Yap_opcount[_get_y_var]; + GLOBAL_opcount[_get_y_var]; c_get.nxval = - Yap_opcount[_get_x_val]; + GLOBAL_opcount[_get_x_val]; c_get.nyval = - Yap_opcount[_get_y_val]; + GLOBAL_opcount[_get_y_val]; c_get.ncons = - Yap_opcount[_get_atom]+ - Yap_opcount[_get_2atoms]+ - Yap_opcount[_get_3atoms]+ - Yap_opcount[_get_4atoms]+ - Yap_opcount[_get_5atoms]+ - Yap_opcount[_get_6atoms]; + GLOBAL_opcount[_get_atom]+ + GLOBAL_opcount[_get_2atoms]+ + GLOBAL_opcount[_get_3atoms]+ + GLOBAL_opcount[_get_4atoms]+ + GLOBAL_opcount[_get_5atoms]+ + GLOBAL_opcount[_get_6atoms]; c_get.nlist = - Yap_opcount[_get_list] + - Yap_opcount[_glist_valx] + - Yap_opcount[_glist_valy] + - Yap_opcount[_gl_void_varx] + - Yap_opcount[_gl_void_vary] + - Yap_opcount[_gl_void_valx] + - Yap_opcount[_gl_void_valy]; + GLOBAL_opcount[_get_list] + + GLOBAL_opcount[_glist_valx] + + GLOBAL_opcount[_glist_valy] + + GLOBAL_opcount[_gl_void_varx] + + GLOBAL_opcount[_gl_void_vary] + + GLOBAL_opcount[_gl_void_valx] + + GLOBAL_opcount[_gl_void_valy]; c_get.nstru = - Yap_opcount[_get_struct]; + GLOBAL_opcount[_get_struct]; gets = c_get.nxvar + c_get.nyvar + c_get.nxval + c_get.nyval + c_get.ncons + c_get.nlist + c_get.nstru; c_unify.nxvar = - Yap_opcount[_unify_x_var] + - Yap_opcount[_unify_void] + - Yap_opcount[_unify_n_voids] + - 2 * Yap_opcount[_unify_x_var2] + - 2 * Yap_opcount[_gl_void_varx] + - Yap_opcount[_gl_void_vary] + - Yap_opcount[_gl_void_valx] + - Yap_opcount[_unify_l_x_var] + - Yap_opcount[_unify_l_void] + - Yap_opcount[_unify_l_n_voids] + - 2 * Yap_opcount[_unify_l_x_var2] + - Yap_opcount[_unify_x_var_write] + - Yap_opcount[_unify_void_write] + - Yap_opcount[_unify_n_voids_write] + - 2 * Yap_opcount[_unify_x_var2_write] + - Yap_opcount[_unify_l_x_var_write] + - Yap_opcount[_unify_l_void_write] + - Yap_opcount[_unify_l_n_voids_write] + - 2 * Yap_opcount[_unify_l_x_var2_write]; + GLOBAL_opcount[_unify_x_var] + + GLOBAL_opcount[_unify_void] + + GLOBAL_opcount[_unify_n_voids] + + 2 * GLOBAL_opcount[_unify_x_var2] + + 2 * GLOBAL_opcount[_gl_void_varx] + + GLOBAL_opcount[_gl_void_vary] + + GLOBAL_opcount[_gl_void_valx] + + GLOBAL_opcount[_unify_l_x_var] + + GLOBAL_opcount[_unify_l_void] + + GLOBAL_opcount[_unify_l_n_voids] + + 2 * GLOBAL_opcount[_unify_l_x_var2] + + GLOBAL_opcount[_unify_x_var_write] + + GLOBAL_opcount[_unify_void_write] + + GLOBAL_opcount[_unify_n_voids_write] + + 2 * GLOBAL_opcount[_unify_x_var2_write] + + GLOBAL_opcount[_unify_l_x_var_write] + + GLOBAL_opcount[_unify_l_void_write] + + GLOBAL_opcount[_unify_l_n_voids_write] + + 2 * GLOBAL_opcount[_unify_l_x_var2_write]; c_unify.nyvar = - Yap_opcount[_unify_y_var] + - Yap_opcount[_gl_void_vary] + - Yap_opcount[_unify_l_y_var] + - Yap_opcount[_unify_y_var_write] + - Yap_opcount[_unify_l_y_var_write]; + GLOBAL_opcount[_unify_y_var] + + GLOBAL_opcount[_gl_void_vary] + + GLOBAL_opcount[_unify_l_y_var] + + GLOBAL_opcount[_unify_y_var_write] + + GLOBAL_opcount[_unify_l_y_var_write]; c_unify.nxval = - Yap_opcount[_unify_x_val] + - Yap_opcount[_unify_x_loc] + - Yap_opcount[_glist_valx] + - Yap_opcount[_gl_void_valx] + - Yap_opcount[_unify_l_x_val] + - Yap_opcount[_unify_l_x_loc] + - Yap_opcount[_unify_x_val_write] + - Yap_opcount[_unify_x_loc_write] + - Yap_opcount[_unify_l_x_val_write] + - Yap_opcount[_unify_l_x_loc_write]; + GLOBAL_opcount[_unify_x_val] + + GLOBAL_opcount[_unify_x_loc] + + GLOBAL_opcount[_glist_valx] + + GLOBAL_opcount[_gl_void_valx] + + GLOBAL_opcount[_unify_l_x_val] + + GLOBAL_opcount[_unify_l_x_loc] + + GLOBAL_opcount[_unify_x_val_write] + + GLOBAL_opcount[_unify_x_loc_write] + + GLOBAL_opcount[_unify_l_x_val_write] + + GLOBAL_opcount[_unify_l_x_loc_write]; c_unify.nyval = - Yap_opcount[_unify_y_val] + - Yap_opcount[_unify_y_loc] + - Yap_opcount[_glist_valy] + - Yap_opcount[_gl_void_valy] + - Yap_opcount[_unify_l_y_val] + - Yap_opcount[_unify_l_y_loc] + - Yap_opcount[_unify_y_val_write] + - Yap_opcount[_unify_y_loc_write] + - Yap_opcount[_unify_l_y_val_write] + - Yap_opcount[_unify_l_y_loc_write]; + GLOBAL_opcount[_unify_y_val] + + GLOBAL_opcount[_unify_y_loc] + + GLOBAL_opcount[_glist_valy] + + GLOBAL_opcount[_gl_void_valy] + + GLOBAL_opcount[_unify_l_y_val] + + GLOBAL_opcount[_unify_l_y_loc] + + GLOBAL_opcount[_unify_y_val_write] + + GLOBAL_opcount[_unify_y_loc_write] + + GLOBAL_opcount[_unify_l_y_val_write] + + GLOBAL_opcount[_unify_l_y_loc_write]; c_unify.ncons = - Yap_opcount[_unify_atom] + - Yap_opcount[_unify_n_atoms] + - Yap_opcount[_unify_l_atom] + - Yap_opcount[_unify_atom_write] + - Yap_opcount[_unify_n_atoms_write] + - Yap_opcount[_unify_l_atom_write]; + GLOBAL_opcount[_unify_atom] + + GLOBAL_opcount[_unify_n_atoms] + + GLOBAL_opcount[_unify_l_atom] + + GLOBAL_opcount[_unify_atom_write] + + GLOBAL_opcount[_unify_n_atoms_write] + + GLOBAL_opcount[_unify_l_atom_write]; c_unify.nlist = - Yap_opcount[_unify_list] + - Yap_opcount[_unify_l_list] + - Yap_opcount[_unify_list_write] + - Yap_opcount[_unify_l_list_write]; + GLOBAL_opcount[_unify_list] + + GLOBAL_opcount[_unify_l_list] + + GLOBAL_opcount[_unify_list_write] + + GLOBAL_opcount[_unify_l_list_write]; c_unify.nstru = - Yap_opcount[_unify_struct] + - Yap_opcount[_unify_l_struc] + - Yap_opcount[_unify_struct_write] + - Yap_opcount[_unify_l_struc_write]; + GLOBAL_opcount[_unify_struct] + + GLOBAL_opcount[_unify_l_struc] + + GLOBAL_opcount[_unify_struct_write] + + GLOBAL_opcount[_unify_l_struc_write]; c_unify.nmisc = - Yap_opcount[_pop] + - Yap_opcount[_pop_n]; + GLOBAL_opcount[_pop] + + GLOBAL_opcount[_pop_n]; unifies = c_unify.nxvar + c_unify.nyvar + c_unify.nxval + c_unify.nyval + c_unify.ncons + c_unify.nlist + c_unify.nstru + c_unify.nmisc; c_put.nxvar = - Yap_opcount[_put_x_var]; + GLOBAL_opcount[_put_x_var]; c_put.nyvar = - Yap_opcount[_put_y_var]; + GLOBAL_opcount[_put_y_var]; c_put.nxval = - Yap_opcount[_put_x_val]+ - 2*Yap_opcount[_put_xx_val]; + GLOBAL_opcount[_put_x_val]+ + 2*GLOBAL_opcount[_put_xx_val]; c_put.nyval = - Yap_opcount[_put_y_val]; + GLOBAL_opcount[_put_y_val]; c_put.ncons = - Yap_opcount[_put_atom]; + GLOBAL_opcount[_put_atom]; c_put.nlist = - Yap_opcount[_put_list]; + GLOBAL_opcount[_put_list]; c_put.nstru = - Yap_opcount[_put_struct]; + GLOBAL_opcount[_put_struct]; puts = c_put.nxvar + c_put.nyvar + c_put.nxval + c_put.nyval + c_put.ncons + c_put.nlist + c_put.nstru; c_write.nxvar = - Yap_opcount[_write_x_var] + - Yap_opcount[_write_void] + - Yap_opcount[_write_n_voids]; + GLOBAL_opcount[_write_x_var] + + GLOBAL_opcount[_write_void] + + GLOBAL_opcount[_write_n_voids]; c_write.nyvar = - Yap_opcount[_write_y_var]; + GLOBAL_opcount[_write_y_var]; c_write.nxval = - Yap_opcount[_write_x_val]; + GLOBAL_opcount[_write_x_val]; c_write.nyval = - Yap_opcount[_write_y_val]; + GLOBAL_opcount[_write_y_val]; c_write.ncons = - Yap_opcount[_write_atom]; + GLOBAL_opcount[_write_atom]; c_write.nlist = - Yap_opcount[_write_list]; + GLOBAL_opcount[_write_list]; c_write.nstru = - Yap_opcount[_write_struct]; + GLOBAL_opcount[_write_struct]; writes = c_write.nxvar + c_write.nyvar + c_write.nxval + c_write.nyval + c_write.ncons + c_write.nlist + c_write.nstru; c_control.nexecs = - Yap_opcount[_execute] + - Yap_opcount[_dexecute]; + GLOBAL_opcount[_execute] + + GLOBAL_opcount[_dexecute]; c_control.ncalls = - Yap_opcount[_call] + - Yap_opcount[_fcall]; + GLOBAL_opcount[_call] + + GLOBAL_opcount[_fcall]; c_control.nproceeds = - Yap_opcount[_procceed]; + GLOBAL_opcount[_procceed]; c_control.ncallbips = - Yap_opcount[_call_cpred] + - Yap_opcount[_call_c_wfail] + - Yap_opcount[_try_c] + - Yap_opcount[_retry_c] + - Yap_opcount[_op_fail] + - Yap_opcount[_trust_fail] + - Yap_opcount[_p_atom_x] + - Yap_opcount[_p_atom_y] + - Yap_opcount[_p_atomic_x] + - Yap_opcount[_p_atomic_y] + - Yap_opcount[_p_compound_x] + - Yap_opcount[_p_compound_y] + - Yap_opcount[_p_float_x] + - Yap_opcount[_p_float_y] + - Yap_opcount[_p_integer_x] + - Yap_opcount[_p_integer_y] + - Yap_opcount[_p_nonvar_x] + - Yap_opcount[_p_nonvar_y] + - Yap_opcount[_p_number_x] + - Yap_opcount[_p_number_y] + - Yap_opcount[_p_var_x] + - Yap_opcount[_p_var_y] + - Yap_opcount[_p_db_ref_x] + - Yap_opcount[_p_db_ref_y] + - Yap_opcount[_p_cut_by_x] + - Yap_opcount[_p_cut_by_y] + - Yap_opcount[_p_primitive_x] + - Yap_opcount[_p_primitive_y] + - Yap_opcount[_p_equal] + - Yap_opcount[_p_plus_vv] + - Yap_opcount[_p_plus_vc] + - Yap_opcount[_p_plus_y_vv] + - Yap_opcount[_p_plus_y_vc] + - Yap_opcount[_p_minus_vv] + - Yap_opcount[_p_minus_cv] + - Yap_opcount[_p_minus_y_vv] + - Yap_opcount[_p_minus_y_cv] + - Yap_opcount[_p_times_vv] + - Yap_opcount[_p_times_vc] + - Yap_opcount[_p_times_y_vv] + - Yap_opcount[_p_times_y_vc] + - Yap_opcount[_p_div_vv] + - Yap_opcount[_p_div_vc] + - Yap_opcount[_p_div_cv] + - Yap_opcount[_p_div_y_vv] + - Yap_opcount[_p_div_y_vc] + - Yap_opcount[_p_div_y_cv] + - Yap_opcount[_p_or_vv] + - Yap_opcount[_p_or_vc] + - Yap_opcount[_p_or_y_vv] + - Yap_opcount[_p_or_y_vc] + - Yap_opcount[_p_and_vv] + - Yap_opcount[_p_and_vc] + - Yap_opcount[_p_and_y_vv] + - Yap_opcount[_p_and_y_vc] + - Yap_opcount[_p_sll_vv] + - Yap_opcount[_p_sll_vc] + - Yap_opcount[_p_sll_y_vv] + - Yap_opcount[_p_sll_y_vc] + - Yap_opcount[_p_slr_vv] + - Yap_opcount[_p_slr_vc] + - Yap_opcount[_p_slr_y_vv] + - Yap_opcount[_p_slr_y_vc] + - Yap_opcount[_p_dif] + - Yap_opcount[_p_eq] + - Yap_opcount[_p_arg_vv] + - Yap_opcount[_p_arg_cv] + - Yap_opcount[_p_arg_y_vv] + - Yap_opcount[_p_arg_y_cv] + - Yap_opcount[_p_functor] + - Yap_opcount[_p_func2s_vv] + - Yap_opcount[_p_func2s_cv] + - Yap_opcount[_p_func2s_vc] + - Yap_opcount[_p_func2s_y_vv] + - Yap_opcount[_p_func2s_y_cv] + - Yap_opcount[_p_func2s_y_vc] + - Yap_opcount[_p_func2f_xx] + - Yap_opcount[_p_func2f_xy] + - Yap_opcount[_p_func2f_yx] + - Yap_opcount[_p_func2f_yy]; + GLOBAL_opcount[_call_cpred] + + GLOBAL_opcount[_call_c_wfail] + + GLOBAL_opcount[_try_c] + + GLOBAL_opcount[_retry_c] + + GLOBAL_opcount[_op_fail] + + GLOBAL_opcount[_trust_fail] + + GLOBAL_opcount[_p_atom_x] + + GLOBAL_opcount[_p_atom_y] + + GLOBAL_opcount[_p_atomic_x] + + GLOBAL_opcount[_p_atomic_y] + + GLOBAL_opcount[_p_compound_x] + + GLOBAL_opcount[_p_compound_y] + + GLOBAL_opcount[_p_float_x] + + GLOBAL_opcount[_p_float_y] + + GLOBAL_opcount[_p_integer_x] + + GLOBAL_opcount[_p_integer_y] + + GLOBAL_opcount[_p_nonvar_x] + + GLOBAL_opcount[_p_nonvar_y] + + GLOBAL_opcount[_p_number_x] + + GLOBAL_opcount[_p_number_y] + + GLOBAL_opcount[_p_var_x] + + GLOBAL_opcount[_p_var_y] + + GLOBAL_opcount[_p_db_ref_x] + + GLOBAL_opcount[_p_db_ref_y] + + GLOBAL_opcount[_p_cut_by_x] + + GLOBAL_opcount[_p_cut_by_y] + + GLOBAL_opcount[_p_primitive_x] + + GLOBAL_opcount[_p_primitive_y] + + GLOBAL_opcount[_p_equal] + + GLOBAL_opcount[_p_plus_vv] + + GLOBAL_opcount[_p_plus_vc] + + GLOBAL_opcount[_p_plus_y_vv] + + GLOBAL_opcount[_p_plus_y_vc] + + GLOBAL_opcount[_p_minus_vv] + + GLOBAL_opcount[_p_minus_cv] + + GLOBAL_opcount[_p_minus_y_vv] + + GLOBAL_opcount[_p_minus_y_cv] + + GLOBAL_opcount[_p_times_vv] + + GLOBAL_opcount[_p_times_vc] + + GLOBAL_opcount[_p_times_y_vv] + + GLOBAL_opcount[_p_times_y_vc] + + GLOBAL_opcount[_p_div_vv] + + GLOBAL_opcount[_p_div_vc] + + GLOBAL_opcount[_p_div_cv] + + GLOBAL_opcount[_p_div_y_vv] + + GLOBAL_opcount[_p_div_y_vc] + + GLOBAL_opcount[_p_div_y_cv] + + GLOBAL_opcount[_p_or_vv] + + GLOBAL_opcount[_p_or_vc] + + GLOBAL_opcount[_p_or_y_vv] + + GLOBAL_opcount[_p_or_y_vc] + + GLOBAL_opcount[_p_and_vv] + + GLOBAL_opcount[_p_and_vc] + + GLOBAL_opcount[_p_and_y_vv] + + GLOBAL_opcount[_p_and_y_vc] + + GLOBAL_opcount[_p_sll_vv] + + GLOBAL_opcount[_p_sll_vc] + + GLOBAL_opcount[_p_sll_y_vv] + + GLOBAL_opcount[_p_sll_y_vc] + + GLOBAL_opcount[_p_slr_vv] + + GLOBAL_opcount[_p_slr_vc] + + GLOBAL_opcount[_p_slr_y_vv] + + GLOBAL_opcount[_p_slr_y_vc] + + GLOBAL_opcount[_p_dif] + + GLOBAL_opcount[_p_eq] + + GLOBAL_opcount[_p_arg_vv] + + GLOBAL_opcount[_p_arg_cv] + + GLOBAL_opcount[_p_arg_y_vv] + + GLOBAL_opcount[_p_arg_y_cv] + + GLOBAL_opcount[_p_functor] + + GLOBAL_opcount[_p_func2s_vv] + + GLOBAL_opcount[_p_func2s_cv] + + GLOBAL_opcount[_p_func2s_vc] + + GLOBAL_opcount[_p_func2s_y_vv] + + GLOBAL_opcount[_p_func2s_y_cv] + + GLOBAL_opcount[_p_func2s_y_vc] + + GLOBAL_opcount[_p_func2f_xx] + + GLOBAL_opcount[_p_func2f_xy] + + GLOBAL_opcount[_p_func2f_yx] + + GLOBAL_opcount[_p_func2f_yy]; c_control.ncuts = - Yap_opcount[_cut] + - Yap_opcount[_cut_t] + - Yap_opcount[_cut_e] + - Yap_opcount[_commit_b_x] + - Yap_opcount[_commit_b_y]; + GLOBAL_opcount[_cut] + + GLOBAL_opcount[_cut_t] + + GLOBAL_opcount[_cut_e] + + GLOBAL_opcount[_commit_b_x] + + GLOBAL_opcount[_commit_b_y]; c_control.nallocs = - Yap_opcount[_allocate] + - Yap_opcount[_fcall]; + GLOBAL_opcount[_allocate] + + GLOBAL_opcount[_fcall]; c_control.ndeallocs = - Yap_opcount[_dexecute] + - Yap_opcount[_deallocate]; + GLOBAL_opcount[_dexecute] + + GLOBAL_opcount[_deallocate]; controls = c_control.nexecs + @@ -585,30 +583,30 @@ p_show_ops_by_group(void) c_control.ncuts + c_control.nallocs + c_control.ndeallocs + - Yap_opcount[_jump] + - Yap_opcount[_move_back] + - Yap_opcount[_try_in]; + GLOBAL_opcount[_jump] + + GLOBAL_opcount[_move_back] + + GLOBAL_opcount[_try_in]; c_cp.ntries = - Yap_opcount[_try_me] + - Yap_opcount[_try_and_mark] + - Yap_opcount[_try_c] + - Yap_opcount[_try_clause] + - Yap_opcount[_either]; + GLOBAL_opcount[_try_me] + + GLOBAL_opcount[_try_and_mark] + + GLOBAL_opcount[_try_c] + + GLOBAL_opcount[_try_clause] + + GLOBAL_opcount[_either]; c_cp.nretries = - Yap_opcount[_retry_me] + - Yap_opcount[_retry_and_mark] + - Yap_opcount[_retry_c] + - Yap_opcount[_retry] + - Yap_opcount[_or_else]; + GLOBAL_opcount[_retry_me] + + GLOBAL_opcount[_retry_and_mark] + + GLOBAL_opcount[_retry_c] + + GLOBAL_opcount[_retry] + + GLOBAL_opcount[_or_else]; c_cp.ntrusts = - Yap_opcount[_trust_me] + - Yap_opcount[_trust] + - Yap_opcount[_or_last]; + GLOBAL_opcount[_trust_me] + + GLOBAL_opcount[_trust] + + GLOBAL_opcount[_or_last]; choice_pts = c_cp.ntries + @@ -616,70 +614,70 @@ p_show_ops_by_group(void) c_cp.ntrusts; indexes = - Yap_opcount[_jump_if_var] + - Yap_opcount[_switch_on_type] + - Yap_opcount[_switch_list_nl] + - Yap_opcount[_switch_on_arg_type] + - Yap_opcount[_switch_on_sub_arg_type] + - Yap_opcount[_switch_on_cons] + - Yap_opcount[_go_on_cons] + - Yap_opcount[_if_cons] + - Yap_opcount[_switch_on_func] + - Yap_opcount[_go_on_func] + - Yap_opcount[_if_func] + - Yap_opcount[_if_not_then]; + GLOBAL_opcount[_jump_if_var] + + GLOBAL_opcount[_switch_on_type] + + GLOBAL_opcount[_switch_list_nl] + + GLOBAL_opcount[_switch_on_arg_type] + + GLOBAL_opcount[_switch_on_sub_arg_type] + + GLOBAL_opcount[_switch_on_cons] + + GLOBAL_opcount[_go_on_cons] + + GLOBAL_opcount[_if_cons] + + GLOBAL_opcount[_switch_on_func] + + GLOBAL_opcount[_go_on_func] + + GLOBAL_opcount[_if_func] + + GLOBAL_opcount[_if_not_then]; misc = c_control.ncallbips + - Yap_opcount[_Ystop] + - Yap_opcount[_Nstop] + - Yap_opcount[_index_pred] + - Yap_opcount[_lock_pred] + + GLOBAL_opcount[_Ystop] + + GLOBAL_opcount[_Nstop] + + GLOBAL_opcount[_index_pred] + + GLOBAL_opcount[_lock_pred] + #if THREADS - Yap_opcount[_thread_local] + + GLOBAL_opcount[_thread_local] + #endif - Yap_opcount[_save_b_x] + - Yap_opcount[_save_b_y] + - Yap_opcount[_undef_p] + - Yap_opcount[_spy_pred] + - Yap_opcount[_spy_or_trymark] + - Yap_opcount[_save_pair_x] + - Yap_opcount[_save_pair_y] + - Yap_opcount[_save_pair_x_write] + - Yap_opcount[_save_pair_y_write] + - Yap_opcount[_save_appl_x] + - Yap_opcount[_save_appl_y] + - Yap_opcount[_save_appl_x_write] + - Yap_opcount[_save_appl_y_write]; + GLOBAL_opcount[_save_b_x] + + GLOBAL_opcount[_save_b_y] + + GLOBAL_opcount[_undef_p] + + GLOBAL_opcount[_spy_pred] + + GLOBAL_opcount[_spy_or_trymark] + + GLOBAL_opcount[_save_pair_x] + + GLOBAL_opcount[_save_pair_y] + + GLOBAL_opcount[_save_pair_x_write] + + GLOBAL_opcount[_save_pair_y_write] + + GLOBAL_opcount[_save_appl_x] + + GLOBAL_opcount[_save_appl_y] + + GLOBAL_opcount[_save_appl_x_write] + + GLOBAL_opcount[_save_appl_y_write]; total = gets + unifies + puts + writes + controls + choice_pts + indexes + misc; /* for (i = 0; i <= _std_top; ++i) * print_instruction(i); */ - fprintf(Yap_stderr, "Groups are\n\n"); - fprintf(Yap_stderr, " GET instructions: %8d (%3d%%)\n", gets, + fprintf(GLOBAL_stderr, "Groups are\n\n"); + fprintf(GLOBAL_stderr, " GET instructions: %8d (%3d%%)\n", gets, (gets * 100) / total); - fprintf(Yap_stderr, " UNIFY instructions: %8d (%3d%%)\n", unifies, + fprintf(GLOBAL_stderr, " UNIFY instructions: %8d (%3d%%)\n", unifies, (unifies * 100) / total); - fprintf(Yap_stderr, " PUT instructions: %8d (%3d%%)\n", puts, + fprintf(GLOBAL_stderr, " PUT instructions: %8d (%3d%%)\n", puts, (puts * 100) / total); - fprintf(Yap_stderr, " WRITE instructions: %8d (%3d%%)\n", writes, + fprintf(GLOBAL_stderr, " WRITE instructions: %8d (%3d%%)\n", writes, (writes * 100) / total); - fprintf(Yap_stderr, " CONTROL instructions: %8d (%3d%%)\n", controls, + fprintf(GLOBAL_stderr, " CONTROL instructions: %8d (%3d%%)\n", controls, (controls * 100) / total); - fprintf(Yap_stderr, " CHOICE POINT instructions: %8d (%3d%%)\n", choice_pts, + fprintf(GLOBAL_stderr, " CHOICE POINT instructions: %8d (%3d%%)\n", choice_pts, (choice_pts * 100) / total); - fprintf(Yap_stderr, " INDEXING instructions: %8d (%3d%%)\n", indexes, + fprintf(GLOBAL_stderr, " INDEXING instructions: %8d (%3d%%)\n", indexes, (indexes * 100) / total); - fprintf(Yap_stderr, " MISCELLANEOUS instructions: %8d (%3d%%)\n", misc, + fprintf(GLOBAL_stderr, " MISCELLANEOUS instructions: %8d (%3d%%)\n", misc, (misc * 100) / total); - fprintf(Yap_stderr, "_______________________________________________\n"); - fprintf(Yap_stderr, " TOTAL instructions: %8d (%3d%%)\n\n", total, + fprintf(GLOBAL_stderr, "_______________________________________________\n"); + fprintf(GLOBAL_stderr, " TOTAL instructions: %8d (%3d%%)\n\n", total, (total * 100) / total); - fprintf(Yap_stderr, "\n Analysis of Unification Instructions in %s \n", program); - fprintf(Yap_stderr, " XVAR, YVAR, XVAL, YVAL, CONS, LIST, STRUCT\n"); - fprintf(Yap_stderr, " GET: %8d %8d %8d %8d %8d %8d %8d\n", + fprintf(GLOBAL_stderr, "\n Analysis of Unification Instructions in %s \n", program); + fprintf(GLOBAL_stderr, " XVAR, YVAR, XVAL, YVAL, CONS, LIST, STRUCT\n"); + fprintf(GLOBAL_stderr, " GET: %8d %8d %8d %8d %8d %8d %8d\n", c_get.nxvar, c_get.nyvar, c_get.nxval, @@ -687,7 +685,7 @@ p_show_ops_by_group(void) c_get.ncons, c_get.nlist, c_get.nstru); - fprintf(Yap_stderr, "UNIFY: %8d %8d %8d %8d %8d %8d %8d\n", + fprintf(GLOBAL_stderr, "UNIFY: %8d %8d %8d %8d %8d %8d %8d\n", c_unify.nxvar, c_unify.nyvar, c_unify.nxval, @@ -695,7 +693,7 @@ p_show_ops_by_group(void) c_unify.ncons, c_unify.nlist, c_unify.nstru); - fprintf(Yap_stderr, " PUT: %8d %8d %8d %8d %8d %8d %8d\n", + fprintf(GLOBAL_stderr, " PUT: %8d %8d %8d %8d %8d %8d %8d\n", c_put.nxvar, c_put.nyvar, c_put.nxval, @@ -703,7 +701,7 @@ p_show_ops_by_group(void) c_put.ncons, c_put.nlist, c_put.nstru); - fprintf(Yap_stderr, "WRITE: %8d %8d %8d %8d %8d %8d %8d\n", + fprintf(GLOBAL_stderr, "WRITE: %8d %8d %8d %8d %8d %8d %8d\n", c_write.nxvar, c_write.nyvar, c_write.nxval, @@ -711,8 +709,8 @@ p_show_ops_by_group(void) c_write.ncons, c_write.nlist, c_write.nstru); - fprintf(Yap_stderr, " ___________________________________________________\n"); - fprintf(Yap_stderr, "TOTAL: %8d %8d %8d %8d %8d %8d %8d\n", + fprintf(GLOBAL_stderr, " ___________________________________________________\n"); + fprintf(GLOBAL_stderr, "TOTAL: %8d %8d %8d %8d %8d %8d %8d\n", c_get.nxvar + c_unify.nxvar + c_put.nxvar + c_write.nxvar, c_get.nyvar + c_unify.nyvar + c_put.nyvar + c_write.nyvar, c_get.nxval + c_unify.nxval + c_put.nxval + c_write.nxval, @@ -722,9 +720,9 @@ p_show_ops_by_group(void) c_get.nstru + c_unify.nstru + c_put.nstru + c_write.nstru ); - fprintf(Yap_stderr, "\n Analysis of Unification Instructions in %s \n", program); - fprintf(Yap_stderr, " XVAR, YVAR, XVAL, YVAL, CONS, LIST, STRUCT\n"); - fprintf(Yap_stderr, " GET: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", + fprintf(GLOBAL_stderr, "\n Analysis of Unification Instructions in %s \n", program); + fprintf(GLOBAL_stderr, " XVAR, YVAR, XVAL, YVAL, CONS, LIST, STRUCT\n"); + fprintf(GLOBAL_stderr, " GET: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", (((double) c_get.nxvar) * 100) / total, (((double) c_get.nyvar) * 100) / total, (((double) c_get.nxval) * 100) / total, @@ -732,7 +730,7 @@ p_show_ops_by_group(void) (((double) c_get.ncons) * 100) / total, (((double) c_get.nlist) * 100) / total, (((double) c_get.nstru) * 100) / total); - fprintf(Yap_stderr, "UNIFY: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", + fprintf(GLOBAL_stderr, "UNIFY: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", (((double) c_unify.nxvar) * 100) / total, (((double) c_unify.nyvar) * 100) / total, (((double) c_unify.nxval) * 100) / total, @@ -740,7 +738,7 @@ p_show_ops_by_group(void) (((double) c_unify.ncons) * 100) / total, (((double) c_unify.nlist) * 100) / total, (((double) c_unify.nstru) * 100) / total); - fprintf(Yap_stderr, " PUT: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", + fprintf(GLOBAL_stderr, " PUT: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", (((double) c_put.nxvar) * 100) / total, (((double) c_put.nyvar) * 100) / total, (((double) c_put.nxval) * 100) / total, @@ -748,7 +746,7 @@ p_show_ops_by_group(void) (((double) c_put.ncons) * 100) / total, (((double) c_put.nlist) * 100) / total, (((double) c_put.nstru) * 100) / total); - fprintf(Yap_stderr, "WRITE: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", + fprintf(GLOBAL_stderr, "WRITE: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", (((double) c_write.nxvar) * 100) / total, (((double) c_write.nyvar) * 100) / total, (((double) c_write.nxval) * 100) / total, @@ -756,8 +754,8 @@ p_show_ops_by_group(void) (((double) c_write.ncons) * 100) / total, (((double) c_write.nlist) * 100) / total, (((double) c_write.nstru) * 100) / total); - fprintf(Yap_stderr, " ___________________________________________________\n"); - fprintf(Yap_stderr, "TOTAL: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", + fprintf(GLOBAL_stderr, " ___________________________________________________\n"); + fprintf(GLOBAL_stderr, "TOTAL: %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%% %3.2f%%\n", (((double) c_get.nxvar + c_unify.nxvar + c_put.nxvar + c_write.nxvar) * 100) / total, (((double) c_get.nyvar + c_unify.nyvar + c_put.nyvar + c_write.nyvar) * 100) / total, (((double) c_get.nxval + c_unify.nxval + c_put.nxval + c_write.nxval) * 100) / total, @@ -767,36 +765,36 @@ p_show_ops_by_group(void) (((double) c_get.nstru + c_unify.nstru + c_put.nstru + c_write.nstru) * 100) / total ); - fprintf(Yap_stderr, "\n Control Instructions Executed in %s \n", program); - fprintf(Yap_stderr, "Grouped as\n\n"); - fprintf(Yap_stderr, " CALL instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, "\n Control Instructions Executed in %s \n", program); + fprintf(GLOBAL_stderr, "Grouped as\n\n"); + fprintf(GLOBAL_stderr, " CALL instructions: %8d (%3d%%)\n", c_control.ncalls, (c_control.ncalls * 100) / total); - fprintf(Yap_stderr, " PROCEED instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, " PROCEED instructions: %8d (%3d%%)\n", c_control.nproceeds, (c_control.nproceeds * 100) / total); - fprintf(Yap_stderr, " EXECUTE instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, " EXECUTE instructions: %8d (%3d%%)\n", c_control.nexecs, (c_control.nexecs * 100) / total); - fprintf(Yap_stderr, " CUT instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, " CUT instructions: %8d (%3d%%)\n", c_control.ncuts, (c_control.ncuts * 100) / total); - fprintf(Yap_stderr, " CALL_BIP instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, " CALL_BIP instructions: %8d (%3d%%)\n", c_control.ncallbips, (c_control.ncallbips * 100) / total); - fprintf(Yap_stderr, " ALLOCATE instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, " ALLOCATE instructions: %8d (%3d%%)\n", c_control.nallocs, (c_control.nallocs * 100) / total); - fprintf(Yap_stderr, " DEALLOCATE instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, " DEALLOCATE instructions: %8d (%3d%%)\n", c_control.ndeallocs, (c_control.ndeallocs * 100) / total); - fprintf(Yap_stderr, "_______________________________________________\n"); - fprintf(Yap_stderr, " TOTAL instructions: %8d (%3d%%)\n\n", total, + fprintf(GLOBAL_stderr, "_______________________________________________\n"); + fprintf(GLOBAL_stderr, " TOTAL instructions: %8d (%3d%%)\n\n", total, (total * 100) / total); - fprintf(Yap_stderr, "\n Choice Point Manipulation Instructions Executed in %s \n", program); - fprintf(Yap_stderr, "Grouped as\n\n"); - fprintf(Yap_stderr, " TRY instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, "\n Choice Point Manipulation Instructions Executed in %s \n", program); + fprintf(GLOBAL_stderr, "Grouped as\n\n"); + fprintf(GLOBAL_stderr, " TRY instructions: %8d (%3d%%)\n", c_cp.ntries, (c_cp.ntries * 100) / total); - fprintf(Yap_stderr, " RETRY instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, " RETRY instructions: %8d (%3d%%)\n", c_cp.nretries, (c_cp.nretries * 100) / total); - fprintf(Yap_stderr, " TRUST instructions: %8d (%3d%%)\n", + fprintf(GLOBAL_stderr, " TRUST instructions: %8d (%3d%%)\n", c_cp.ntrusts, (c_cp.ntrusts * 100) / total); - fprintf(Yap_stderr, "_______________________________________________\n"); - fprintf(Yap_stderr, " TOTAL instructions: %8d (%3d%%)\n\n", total, + fprintf(GLOBAL_stderr, "_______________________________________________\n"); + fprintf(GLOBAL_stderr, " TOTAL instructions: %8d (%3d%%)\n\n", total, (total * 100) / total); return TRUE; @@ -828,7 +826,7 @@ p_show_sequences(void) return FALSE; } for (i = 0; i <= _std_top; ++i) { - sum += Yap_opcount[i]; + sum += GLOBAL_opcount[i]; } for (i = 0; i <= _std_top; ++i) { for (j = 0; j <= _std_top; ++j) { diff --git a/C/arrays.c b/C/arrays.c index 43f103ed9..52af62739 100644 --- a/C/arrays.c +++ b/C/arrays.c @@ -158,12 +158,11 @@ typedef struct MMAP_ARRAY_BLOCK { struct MMAP_ARRAY_BLOCK *next; } mmap_array_block; -static mmap_array_block *mmap_arrays = NULL; static Int CloseMmappedArray(StaticArrayEntry *pp, void *area USES_REGS) { - mmap_array_block *ptr = mmap_arrays, *optr = mmap_arrays; + mmap_array_block *ptr = GLOBAL_mmap_arrays, *optr = GLOBAL_mmap_arrays; while (ptr != NULL && ptr->start != area) { ptr = ptr->next; @@ -193,7 +192,7 @@ CloseMmappedArray(StaticArrayEntry *pp, void *area USES_REGS) static void ResizeMmappedArray(StaticArrayEntry *pp, Int dim, void *area USES_REGS) { - mmap_array_block *ptr = mmap_arrays; + mmap_array_block *ptr = GLOBAL_mmap_arrays; size_t total_size; while (ptr != NULL && ptr->start != area) { ptr = ptr->next; @@ -240,16 +239,16 @@ GetTermFromArray(DBTerm *ref USES_REGS) Term TRef; while ((TRef = Yap_FetchTermFromDB(ref)) == 0L) { - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return TermNil; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 3, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 3, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return TermNil; } } @@ -573,8 +572,8 @@ CreateNamedArray(PropEntry * pp, Int dim, AtomEntry *ae USES_REGS) #if THREADS p->owner_id = worker_id; #endif - p->NextAE = DynamicArrays; - DynamicArrays = p; + p->NextAE = LOCAL_DynamicArrays; + LOCAL_DynamicArrays = p; InitNamedArray(p, dim PASS_REGS); } @@ -611,7 +610,7 @@ AllocateStaticArraySpace(StaticArrayEntry *p, static_array_types atype, Int arra while ((p->ValueOfVE.floats = (Float *) Yap_AllocAtomSpace(asize) ) == NULL) { YAPLeaveCriticalSection(); if (!Yap_growheap(FALSE, asize, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return; } YAPEnterCriticalSection(); @@ -625,15 +624,15 @@ CreateStaticArray(AtomEntry *ae, Int dim, static_array_types type, CODEADDR star if (EndOfPAEntr(p)) { while ((p = (StaticArrayEntry *) Yap_AllocAtomSpace(sizeof(*p))) == NULL) { if (!Yap_growheap(FALSE, sizeof(*p), NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return NULL; } } p->KindOfPE = ArrayProperty; p->NextOfPE = ae->PropsOfAE; INIT_RWLOCK(p->ArRWLock); - p->NextAE = StaticArrays; - StaticArrays = p; + p->NextAE = LOCAL_StaticArrays; + LOCAL_StaticArrays = p; } WRITE_LOCK(p->ArRWLock); p->ArrayEArity = -dim; @@ -900,12 +899,12 @@ p_create_array( USES_REGS1 ) farray = Yap_MkFunctor(AtomArray, size); if (H+1+size > ASP-1024) { if (!Yap_gcl((1+size)*sizeof(CELL), 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); return(FALSE); } else { if (H+1+size > ASP-1024) { if (!Yap_growstack( sizeof(CELL) * (size+1-(H-ASP-1024)))) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -938,7 +937,7 @@ p_create_array( USES_REGS1 ) if (H+1+size > ASP-1024) { WRITE_UNLOCK(ae->ARWLock); if (!Yap_gcl((1+size)*sizeof(CELL), 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); return(FALSE); } else goto restart; @@ -960,7 +959,7 @@ p_create_array( USES_REGS1 ) } else { if (H+1+size > ASP-1024) { if (!Yap_gcl((1+size)*sizeof(CELL), 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); return(FALSE); } else goto restart; @@ -1383,8 +1382,8 @@ p_create_mmapped_array( USES_REGS1 ) ptr->items = size; ptr->start = (void *)array_addr; ptr->fd = fd; - ptr->next = mmap_arrays; - mmap_arrays = ptr; + ptr->next = GLOBAL_mmap_arrays; + GLOBAL_mmap_arrays = ptr; WRITE_UNLOCK(pp->ArRWLock); WRITE_UNLOCK(ae->ARWLock); return TRUE; @@ -2244,7 +2243,7 @@ static Int p_sync_mmapped_arrays( USES_REGS1 ) { #ifdef HAVE_MMAP - mmap_array_block *ptr = mmap_arrays; + mmap_array_block *ptr = GLOBAL_mmap_arrays; while (ptr != NULL) { msync(ptr->start, ptr->size, MS_SYNC); ptr = ptr->next; @@ -2279,12 +2278,12 @@ p_static_array_to_term( USES_REGS1 ) while (H+1+dim > ASP-1024) { if (!Yap_gcl((1+dim)*sizeof(CELL), 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); return(FALSE); } else { if (H+1+dim > ASP-1024) { if (!Yap_growstack( sizeof(CELL) * (dim+1-(H-ASP-1024)))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } diff --git a/C/attvar.c b/C/attvar.c index d5646a9fa..cdd9a327d 100644 --- a/C/attvar.c +++ b/C/attvar.c @@ -41,10 +41,10 @@ AddToQueue(attvar_record *attv USES_REGS) t[0] = (CELL)&(attv->Done); t[1] = attv->Value; /* follow the chain */ - WGs = Yap_ReadTimedVar(WokenGoals); + WGs = Yap_ReadTimedVar(LOCAL_WokenGoals); ng = Yap_MkApplTerm(FunctorAttGoal, 2, t); - Yap_UpdateTimedVar(WokenGoals, MkPairTerm(ng, WGs)); + Yap_UpdateTimedVar(LOCAL_WokenGoals, MkPairTerm(ng, WGs)); if ((Term)WGs == TermNil) { /* from now on, we have to start waking up goals */ Yap_signal(YAP_WAKEUP_SIGNAL); @@ -58,9 +58,9 @@ AddFailToQueue( USES_REGS1 ) Term WGs; /* follow the chain */ - WGs = Yap_ReadTimedVar(WokenGoals); + WGs = Yap_ReadTimedVar(LOCAL_WokenGoals); - Yap_UpdateTimedVar(WokenGoals, MkPairTerm(MkAtomTerm(AtomFail), WGs)); + Yap_UpdateTimedVar(LOCAL_WokenGoals, MkPairTerm(MkAtomTerm(AtomFail), WGs)); if ((Term)WGs == TermNil) { /* from now on, we have to start waking up goals */ Yap_signal(YAP_WAKEUP_SIGNAL); @@ -205,7 +205,7 @@ BuildAttTerm(Functor mfun, UInt ar USES_REGS) UInt i; if (H+(1024+ar) > ASP) { - Yap_Error_Size=ar*sizeof(CELL); + LOCAL_Error_Size=ar*sizeof(CELL); return 0L; } H[0] = (CELL)mfun; @@ -433,9 +433,9 @@ p_put_att( USES_REGS1 ) { attv = RepAttVar(VarOfTerm(inp)); } else { while (!(attv = BuildNewAttVar( PASS_REGS1 ))) { - Yap_Error_Size = sizeof(attvar_record); - if (!Yap_gcl(Yap_Error_Size, 5, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_Size = sizeof(attvar_record); + if (!Yap_gcl(LOCAL_Error_Size, 5, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } inp = Deref(ARG1); @@ -445,8 +445,8 @@ p_put_att( USES_REGS1 ) { mfun= Yap_MkFunctor(modname,ar); if (IsVarTerm(tatts = SearchAttsForModule(attv->Atts,mfun))) { while (!(tatts = BuildAttTerm(mfun,ar PASS_REGS))) { - if (!Yap_gcl(Yap_Error_Size, 5, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + if (!Yap_gcl(LOCAL_Error_Size, 5, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -474,9 +474,9 @@ p_put_att_term( USES_REGS1 ) { MaBind(&(attv->Atts), Deref(ARG2)); } else { while (!(attv = BuildNewAttVar( PASS_REGS1 ))) { - Yap_Error_Size = sizeof(attvar_record); - if (!Yap_gcl(Yap_Error_Size, 5, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_Size = sizeof(attvar_record); + if (!Yap_gcl(LOCAL_Error_Size, 5, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } inp = Deref(ARG1); @@ -508,9 +508,9 @@ p_rm_att( USES_REGS1 ) { attv = RepAttVar(VarOfTerm(inp)); } else { while (!(attv = BuildNewAttVar( PASS_REGS1 ))) { - Yap_Error_Size = sizeof(attvar_record); - if (!Yap_gcl(Yap_Error_Size, 5, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_Size = sizeof(attvar_record); + if (!Yap_gcl(LOCAL_Error_Size, 5, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } inp = Deref(ARG1); @@ -521,8 +521,8 @@ p_rm_att( USES_REGS1 ) { mfun= Yap_MkFunctor(modname,ar); if (IsVarTerm(tatts = SearchAttsForModule(attv->Atts,mfun))) { while (!(tatts = BuildAttTerm(mfun, ar PASS_REGS))) { - if (!Yap_gcl(Yap_Error_Size, 4, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + if (!Yap_gcl(LOCAL_Error_Size, 4, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -555,9 +555,9 @@ p_put_atts( USES_REGS1 ) { attv = RepAttVar(VarOfTerm(inp)); } else { while (!(attv = BuildNewAttVar( PASS_REGS1 ))) { - Yap_Error_Size = sizeof(attvar_record); - if (!Yap_gcl(Yap_Error_Size, 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_Size = sizeof(attvar_record); + if (!Yap_gcl(LOCAL_Error_Size, 2, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } tatts = Deref(ARG2); @@ -902,7 +902,7 @@ AllAttVars( USES_REGS1 ) { case (CELL)FunctorAttVar: if (IsUnboundVar(pt+1)) { if (ASP - myH < 1024) { - Yap_Error_Size = (ASP-H)*sizeof(CELL); + LOCAL_Error_Size = (ASP-H)*sizeof(CELL); return 0L; } if (myH != H) { @@ -952,8 +952,8 @@ p_all_attvars( USES_REGS1 ) Term out; if (!(out = AllAttVars( PASS_REGS1 ))) { - if (!Yap_gcl(Yap_Error_Size, 1, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + if (!Yap_gcl(LOCAL_Error_Size, 1, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { @@ -1044,11 +1044,11 @@ void Yap_InitAttVarPreds(void) Term OldCurrentModule = CurrentModule; CurrentModule = ATTRIBUTES_MODULE; #ifdef COROUTINING - attas[attvars_ext].bind_op = WakeAttVar; - attas[attvars_ext].copy_term_op = CopyAttVar; - attas[attvars_ext].to_term_op = AttVarToTerm; - attas[attvars_ext].term_to_op = TermToAttVar; - attas[attvars_ext].mark_op = mark_attvar; + GLOBAL_attas[attvars_ext].bind_op = WakeAttVar; + GLOBAL_attas[attvars_ext].copy_term_op = CopyAttVar; + GLOBAL_attas[attvars_ext].to_term_op = AttVarToTerm; + GLOBAL_attas[attvars_ext].term_to_op = TermToAttVar; + GLOBAL_attas[attvars_ext].mark_op = mark_attvar; Yap_InitCPred("get_att", 4, p_get_att, SafePredFlag); Yap_InitCPred("get_module_atts", 2, p_get_atts, SafePredFlag); Yap_InitCPred("has_module_atts", 2, p_has_atts, SafePredFlag); diff --git a/C/bignum.c b/C/bignum.c index 5304a4faf..6aac3488f 100755 --- a/C/bignum.c +++ b/C/bignum.c @@ -233,7 +233,7 @@ p_rational( USES_REGS1 ) (mpq_numref(rat)->_mp_alloc)*(sizeof(mp_limb_t)/CellSize) + (mpq_denref(rat)->_mp_alloc)*(sizeof(mp_limb_t)/CellSize); if (!Yap_gcl(size, 3, ENV, P)) { - Yap_Error(OUT_OF_STACK_ERROR, t, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, t, LOCAL_ErrorMessage); return FALSE; } } diff --git a/C/c_interface.c b/C/c_interface.c index ff897f9f1..5ef8d66c9 100755 --- a/C/c_interface.c +++ b/C/c_interface.c @@ -334,6 +334,7 @@ #include "clause.h" #include "yapio.h" #include "attvar.h" +#include "SWI-Stream.h" #if HAVE_STDARG_H #include #endif @@ -458,6 +459,7 @@ X_API int STD_PROTO(YAP_GoalHasException,(Term *)); X_API void STD_PROTO(YAP_ClearExceptions,(void)); X_API int STD_PROTO(YAP_ContinueGoal,(void)); X_API void STD_PROTO(YAP_PruneGoal,(void)); +X_API IOSTREAM *STD_PROTO(YAP_TermToStream,(Term)); X_API IOSTREAM *STD_PROTO(YAP_InitConsult,(int, char *)); X_API void STD_PROTO(YAP_EndConsult,(IOSTREAM *)); X_API Term STD_PROTO(YAP_Read, (IOSTREAM *)); @@ -761,7 +763,7 @@ YAP_MkBlobTerm(unsigned int sz) while (H+(sz+sizeof(MP_INT)/sizeof(CELL)+2) > ASP-1024) { if (!doexpand((sz+sizeof(MP_INT)/sizeof(CELL)+2)*sizeof(CELL))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, "YAP failed to grow the stack while constructing a blob: %s", Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, "YAP failed to grow the stack while constructing a blob: %s", LOCAL_ErrorMessage); return TermNil; } } @@ -855,9 +857,9 @@ YAP_LookupAtom(char *c) while (TRUE) { a = Yap_LookupAtom(c); - if (a == NIL || (ActiveSignals & YAP_CDOVF_SIGNAL)) { + if (a == NIL || (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL)) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", LOCAL_ErrorMessage); } } else { return a; @@ -873,9 +875,9 @@ YAP_LookupWideAtom(wchar_t *c) while (TRUE) { a = Yap_LookupWideAtom(c); - if (a == NIL || (ActiveSignals & YAP_CDOVF_SIGNAL)) { + if (a == NIL || (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL)) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", LOCAL_ErrorMessage); } } else { return a; @@ -891,9 +893,9 @@ YAP_FullLookupAtom(char *c) while (TRUE) { at = Yap_FullLookupAtom(c); - if (at == NIL || (ActiveSignals & YAP_CDOVF_SIGNAL)) { + if (at == NIL || (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL)) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", LOCAL_ErrorMessage); } } else { return at; @@ -1563,7 +1565,7 @@ YAP_Execute(PredEntry *pe, CPredicate exec_code) if (!ret) { Term t; - BallTerm = EX; + LOCAL_BallTerm = EX; EX = NULL; if ((t = Yap_GetException())) { Yap_JumpToEnv(t); @@ -1586,7 +1588,7 @@ YAP_ExecuteFirst(PredEntry *pe, CPredicate exec_code) Int val; CPredicateV codev = (CPredicateV)exec_code; struct foreign_context *ctx = (struct foreign_context *)(&EXTRA_CBACK_ARG(pe->ArityOfPE,1)); - struct open_query_struct *oexec = execution; + struct open_query_struct *oexec = LOCAL_execution; extern void PL_close_foreign_frame(struct open_query_struct *); PP = pe; @@ -1599,13 +1601,13 @@ YAP_ExecuteFirst(PredEntry *pe, CPredicate exec_code) val = ((codev)(B->cp_args-LCL0,0,ctx)); } /* make sure we clean up the frames left by the user */ - while (execution != oexec) - PL_close_foreign_frame(execution); + while (LOCAL_execution != oexec) + PL_close_foreign_frame(LOCAL_execution); PP = NULL; if (val == 0) { Term t; - BallTerm = EX; + LOCAL_BallTerm = EX; EX = NULL; if ((t = Yap_GetException())) { cut_c_pop(); @@ -1628,7 +1630,7 @@ YAP_ExecuteFirst(PredEntry *pe, CPredicate exec_code) if (!ret) { Term t; - BallTerm = EX; + LOCAL_BallTerm = EX; EX = NULL; if ((t = Yap_GetException())) { Yap_JumpToEnv(t); @@ -1651,7 +1653,7 @@ YAP_ExecuteOnCut(PredEntry *pe, CPredicate exec_code, struct cut_c_str *top) Int val; CPredicateV codev = (CPredicateV)exec_code; struct foreign_context *ctx = (struct foreign_context *)(&EXTRA_CBACK_ARG(pe->ArityOfPE,1)); - struct open_query_struct *oexec = execution; + struct open_query_struct *oexec = LOCAL_execution; extern void PL_close_foreign_frame(struct open_query_struct *); CELL *args = B->cp_args; @@ -1667,15 +1669,15 @@ YAP_ExecuteOnCut(PredEntry *pe, CPredicate exec_code, struct cut_c_str *top) val = ((codev)(args-LCL0,0,ctx)); } /* make sure we clean up the frames left by the user */ - while (execution != oexec) - PL_close_foreign_frame(execution); + while (LOCAL_execution != oexec) + PL_close_foreign_frame(LOCAL_execution); PP = NULL; // B = LCL0-(CELL*)oB; if (val == 0) { Term t; - BallTerm = EX; + LOCAL_BallTerm = EX; EX = NULL; if ((t = Yap_GetException())) { cut_c_pop(); @@ -1693,7 +1695,7 @@ YAP_ExecuteOnCut(PredEntry *pe, CPredicate exec_code, struct cut_c_str *top) if (!ret) { Term t; - BallTerm = EX; + LOCAL_BallTerm = EX; EX = NULL; if ((t = Yap_GetException())) { Yap_JumpToEnv(t); @@ -1713,7 +1715,7 @@ YAP_ExecuteNext(PredEntry *pe, CPredicate exec_code) Int val; CPredicateV codev = (CPredicateV)exec_code; struct foreign_context *ctx = (struct foreign_context *)(&EXTRA_CBACK_ARG(pe->ArityOfPE,1)); - struct open_query_struct *oexec = execution; + struct open_query_struct *oexec = LOCAL_execution; extern void PL_close_foreign_frame(struct open_query_struct *); PP = pe; @@ -1724,13 +1726,13 @@ YAP_ExecuteNext(PredEntry *pe, CPredicate exec_code) val = ((codev)(B->cp_args-LCL0,0,ctx)); } /* make sure we clean up the frames left by the user */ - while (execution != oexec) - PL_close_foreign_frame(execution); + while (LOCAL_execution != oexec) + PL_close_foreign_frame(LOCAL_execution); PP = NULL; if (val == 0) { Term t; - BallTerm = EX; + LOCAL_BallTerm = EX; EX = NULL; if ((t = Yap_GetException())) { cut_c_pop(); @@ -1754,7 +1756,7 @@ YAP_ExecuteNext(PredEntry *pe, CPredicate exec_code) if (!ret) { Term t; - BallTerm = EX; + LOCAL_BallTerm = EX; EX = NULL; if ((t = Yap_GetException())) { Yap_JumpToEnv(t); @@ -1794,7 +1796,7 @@ YAP_ReallocSpaceFromYap(void *ptr,unsigned int size) { BACKUP_MACHINE_REGS(); while ((new_ptr = Yap_ReallocCodeSpace(ptr,size)) == NULL) { if (!Yap_growheap(FALSE, size, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return NULL; } } @@ -1810,7 +1812,7 @@ YAP_AllocSpaceFromYap(unsigned int size) while ((ptr = Yap_AllocCodeSpace(size)) == NULL) { if (!Yap_growheap(FALSE, size, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return NULL; } } @@ -1927,35 +1929,35 @@ YAP_ReadBuffer(char *s, Term *tp) BACKUP_H(); while ((t = Yap_StringToTerm(s,tp)) == 0L) { - if (Yap_ErrorMessage) { - if (!strcmp(Yap_ErrorMessage,"Stack Overflow")) { + if (LOCAL_ErrorMessage) { + if (!strcmp(LOCAL_ErrorMessage,"Stack Overflow")) { if (!dogc()) { - *tp = MkAtomTerm(Yap_LookupAtom(Yap_ErrorMessage)); - Yap_ErrorMessage = NULL; + *tp = MkAtomTerm(Yap_LookupAtom(LOCAL_ErrorMessage)); + LOCAL_ErrorMessage = NULL; RECOVER_H(); return 0L; } - } else if (!strcmp(Yap_ErrorMessage,"Heap Overflow")) { + } else if (!strcmp(LOCAL_ErrorMessage,"Heap Overflow")) { if (!Yap_growheap(FALSE, 0, NULL)) { - *tp = MkAtomTerm(Yap_LookupAtom(Yap_ErrorMessage)); - Yap_ErrorMessage = NULL; + *tp = MkAtomTerm(Yap_LookupAtom(LOCAL_ErrorMessage)); + LOCAL_ErrorMessage = NULL; RECOVER_H(); return 0L; } - } else if (!strcmp(Yap_ErrorMessage,"Trail Overflow")) { + } else if (!strcmp(LOCAL_ErrorMessage,"Trail Overflow")) { if (!Yap_growtrail (0, FALSE)) { - *tp = MkAtomTerm(Yap_LookupAtom(Yap_ErrorMessage)); - Yap_ErrorMessage = NULL; + *tp = MkAtomTerm(Yap_LookupAtom(LOCAL_ErrorMessage)); + LOCAL_ErrorMessage = NULL; RECOVER_H(); return 0L; } } else { - *tp = MkAtomTerm(Yap_LookupAtom(Yap_ErrorMessage)); - Yap_ErrorMessage = NULL; + *tp = MkAtomTerm(Yap_LookupAtom(LOCAL_ErrorMessage)); + LOCAL_ErrorMessage = NULL; RECOVER_H(); return 0L; } - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; continue; } else { break; @@ -2138,9 +2140,9 @@ run_emulator(YAP_dogoalinfo *dgi) int out; BACKUP_MACHINE_REGS(); - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; out = Yap_absmi(0); - Yap_PrologMode = UserCCallMode; + LOCAL_PrologMode = UserCCallMode; myB = (choiceptr)(LCL0-dgi->b); CP = myB->cp_cp; if (!out ) { @@ -2196,9 +2198,6 @@ YAP_EnterGoal(PredEntry *pe, Term *ptr, YAP_dogoalinfo *dgi) CP = YESCODE; B = myB; HB = H; -#if defined(YAPOR) || defined(THREADS) - WPP = NULL; -#endif ASP = YENV = (CELL *)B; YENV[E_CB] = Unsigned (B); out = run_emulator(dgi); @@ -2276,19 +2275,19 @@ YAP_RunGoal(Term t) yamop *old_CP = CP; BACKUP_MACHINE_REGS(); - Yap_AllowRestart = FALSE; - Yap_PrologMode = UserMode; + LOCAL_AllowRestart = FALSE; + LOCAL_PrologMode = UserMode; out = Yap_RunTopGoal(t); - Yap_PrologMode = UserCCallMode; + LOCAL_PrologMode = UserCCallMode; if (out) { P = (yamop *)ENV[E_CP]; ENV = (CELL *)ENV[E_E]; CP = old_CP; - Yap_AllowRestart = TRUE; + LOCAL_AllowRestart = TRUE; } else { ENV = B->cp_env; B = B->cp_b; - Yap_AllowRestart = FALSE; + LOCAL_AllowRestart = FALSE; } RECOVER_MACHINE_REGS(); @@ -2303,9 +2302,9 @@ YAP_RunGoalOnce(Term t) yamop *old_CP = CP; BACKUP_MACHINE_REGS(); - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; out = Yap_RunTopGoal(t); - Yap_PrologMode = UserCCallMode; + LOCAL_PrologMode = UserCCallMode; if (out) { choiceptr cut_pt; @@ -2327,7 +2326,7 @@ YAP_RunGoalOnce(Term t) #endif P = (yamop *)ASP[E_CP]; CP = old_CP; - Yap_AllowRestart = FALSE; + LOCAL_AllowRestart = FALSE; RECOVER_MACHINE_REGS(); return(out); } @@ -2338,17 +2337,17 @@ YAP_RestartGoal(void) CACHE_REGS int out; BACKUP_MACHINE_REGS(); - if (Yap_AllowRestart) { + if (LOCAL_AllowRestart) { P = (yamop *)FAILCODE; do_putcf = myputc; - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; out = Yap_exec_absmi(TRUE); - Yap_PrologMode = UserCCallMode; + LOCAL_PrologMode = UserCCallMode; if (out == FALSE) { /* cleanup */ Yap_CloseSlots( PASS_REGS1 ); Yap_trust_last(); - Yap_AllowRestart = FALSE; + LOCAL_AllowRestart = FALSE; } } else { out = FALSE; @@ -2363,7 +2362,7 @@ YAP_ShutdownGoal(int backtrack) CACHE_REGS BACKUP_MACHINE_REGS(); - if (Yap_AllowRestart) { + if (LOCAL_AllowRestart) { choiceptr cut_pt; cut_pt = B; @@ -2390,7 +2389,7 @@ YAP_ShutdownGoal(int backtrack) #ifdef DEPTH_LIMIT DEPTH = ASP[E_DEPTH]; #endif - Yap_AllowRestart = FALSE; + LOCAL_AllowRestart = FALSE; } RECOVER_MACHINE_REGS(); return TRUE; @@ -2399,12 +2398,13 @@ YAP_ShutdownGoal(int backtrack) X_API int YAP_ContinueGoal(void) { + CACHE_REGS int out; BACKUP_MACHINE_REGS(); - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; out = Yap_exec_absmi(TRUE); - Yap_PrologMode = UserCCallMode; + LOCAL_PrologMode = UserCCallMode; RECOVER_MACHINE_REGS(); return(out); @@ -2435,22 +2435,22 @@ YAP_GoalHasException(Term *t) BACKUP_MACHINE_REGS(); if (EX) { do { - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; *t = Yap_FetchTermFromDB(EX); - if (Yap_Error_TYPE == YAP_NO_ERROR) { + if (LOCAL_Error_TYPE == YAP_NO_ERROR) { RECOVER_MACHINE_REGS(); return TRUE; - } else if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + } else if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); RECOVER_MACHINE_REGS(); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growstack(EX->NOfCells*CellSize)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); RECOVER_MACHINE_REGS(); return FALSE; } @@ -2468,11 +2468,11 @@ YAP_ClearExceptions(void) CACHE_REGS Yap_ResetExceptionTerm(); if (EX) { - BallTerm = EX; + LOCAL_BallTerm = EX; } EX = NULL; Yap_ResetExceptionTerm(); - UncaughtThrow = FALSE; + LOCAL_UncaughtThrow = FALSE; } X_API IOSTREAM * @@ -2490,6 +2490,22 @@ YAP_InitConsult(int mode, char *filename) return st; } +X_API IOSTREAM * +YAP_TermToStream(Term t) +{ + CACHE_REGS + IOSTREAM *s; + int rc; + BACKUP_MACHINE_REGS(); + + if ( (rc=PL_get_stream_handle(Yap_InitSlot(t PASS_REGS), &s)) ) { + RECOVER_MACHINE_REGS(); + return s; + } + RECOVER_MACHINE_REGS(); + return NULL; +} + X_API void YAP_EndConsult(IOSTREAM *s) { @@ -2511,20 +2527,20 @@ YAP_Read(IOSTREAM *inp) BACKUP_MACHINE_REGS(); - tokstart = Yap_tokptr = Yap_toktide = Yap_tokenizer(inp, &tpos); - if (Yap_ErrorMessage) + tokstart = LOCAL_tokptr = LOCAL_toktide = Yap_tokenizer(inp, &tpos); + if (LOCAL_ErrorMessage) { - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); RECOVER_MACHINE_REGS(); return 0; } if (inp->flags & (SIO_FEOF|SIO_FEOF2)) { - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); RECOVER_MACHINE_REGS(); return MkAtomTerm (AtomEof); } t = Yap_Parse(); - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); RECOVER_MACHINE_REGS(); return t; @@ -2575,7 +2591,7 @@ YAP_CompileClause(Term t) BACKUP_MACHINE_REGS(); /* allow expansion during stack initialization */ - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; ARG1 = t; YAPEnterCriticalSection(); codeaddr = Yap_cclause (t,0, mod, t); @@ -2583,18 +2599,18 @@ YAP_CompileClause(Term t) t = Deref(ARG1); /* just in case there was an heap overflow */ if (!Yap_addclause (t, codeaddr, TRUE, mod, &tn)) { YAPLeaveCriticalSection(); - return Yap_ErrorMessage; + return LOCAL_ErrorMessage; } } YAPLeaveCriticalSection(); - if (ActiveSignals & YAP_CDOVF_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap: %s", LOCAL_ErrorMessage); } } RECOVER_MACHINE_REGS(); - return(Yap_ErrorMessage); + return(LOCAL_ErrorMessage); } static int eof_found = FALSE; @@ -2711,8 +2727,14 @@ YAP_Init(YAP_init_args *yap_init) CELL Trail = 0, Stack = 0, Heap = 0, Atts = 0; static char boot_file[256]; - Yap_argv = yap_init->Argv; - Yap_argc = yap_init->Argc; + Yap_InitPageSize(); /* init memory page size, required by later functions */ +#if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA) + Yap_init_yapor_global_local_memory(); + LOCAL = REMOTE(0); +#endif /* YAPOR_COPY || YAPOR_COW || YAPOR_SBA */ + Yap_InitSysbits(); /* init signal handling and time, required by later functions */ + GLOBAL_argv = yap_init->Argv; + GLOBAL_argc = yap_init->Argc; #if !BOOT_FROM_SAVED_STATE if (yap_init->SavedState) { fprintf(stderr,"[ WARNING: threaded YAP will ignore saved state %s ]\n",yap_init->SavedState); @@ -2721,8 +2743,8 @@ YAP_Init(YAP_init_args *yap_init) #endif if (BOOT_FROM_SAVED_STATE && !do_bootstrap) { if (Yap_SavedInfo (yap_init->SavedState, yap_init->YapLibDir, &Trail, &Stack, &Heap) != 1) { - yap_init->ErrorNo = Yap_Error_TYPE; - yap_init->ErrorCause = Yap_ErrorMessage; + yap_init->ErrorNo = LOCAL_Error_TYPE; + yap_init->ErrorCause = LOCAL_ErrorMessage; return YAP_BOOT_ERROR; } } @@ -2757,7 +2779,7 @@ YAP_Init(YAP_init_args *yap_init) } else { Heap = yap_init->HeapSize; } - Yap_PrologShouldHandleInterrupts = yap_init->PrologShouldHandleInterrupts; + GLOBAL_PrologShouldHandleInterrupts = yap_init->PrologShouldHandleInterrupts; Yap_InitWorkspace(Heap, Stack, Trail, Atts, yap_init->MaxTableSpaceSize, yap_init->NumberWorkers, @@ -2773,20 +2795,20 @@ YAP_Init(YAP_init_args *yap_init) Trail = MinTrailSpace; if (Stack < MinStackSpace) Stack = MinStackSpace; - if (!(Yap_GlobalBase = (ADDR)malloc((Trail+Stack)*1024))) { + if (!(LOCAL_GlobalBase = (ADDR)malloc((Trail+Stack)*1024))) { yap_init->ErrorNo = RESOURCE_ERROR_MEMORY; yap_init->ErrorCause = "could not allocate stack space for main thread"; return YAP_BOOT_ERROR; } #if THREADS /* don't forget this is a thread */ - MY_ThreadHandle.stack_address = Yap_GlobalBase; - MY_ThreadHandle.ssize = Trail+Stack; + LOCAL_ThreadHandle.stack_address = LOCAL_GlobalBase; + LOCAL_ThreadHandle.ssize = Trail+Stack; #endif #endif - Yap_AllowGlobalExpansion = TRUE; - Yap_AllowLocalExpansion = TRUE; - Yap_AllowTrailExpansion = TRUE; + GLOBAL_AllowGlobalExpansion = TRUE; + GLOBAL_AllowLocalExpansion = TRUE; + GLOBAL_AllowTrailExpansion = TRUE; Yap_InitExStacks (Trail, Stack); if (yap_init->QuietMode) { yap_flags[QUIET_MODE_FLAG] = TRUE; @@ -2816,8 +2838,8 @@ YAP_Init(YAP_init_args *yap_init) } else if (BOOT_FROM_SAVED_STATE) { restore_result = Yap_Restore(yap_init->SavedState, yap_init->YapLibDir); if (restore_result == FAIL_RESTORE) { - yap_init->ErrorNo = Yap_Error_TYPE; - yap_init->ErrorCause = Yap_ErrorMessage; + yap_init->ErrorNo = LOCAL_Error_TYPE; + yap_init->ErrorCause = LOCAL_ErrorMessage; /* shouldn't RECOVER_MACHINE_REGS(); be here ??? */ return YAP_BOOT_ERROR; } @@ -2826,27 +2848,21 @@ YAP_Init(YAP_init_args *yap_init) } yap_flags[FAST_BOOT_FLAG] = yap_init->FastBoot; #if defined(YAPOR) || defined(TABLING) -#ifdef TABLING - /* make sure we initialise this field */ - Yap_root_dep_fr = NULL; -#endif - make_root_frames(); -#ifdef YAPOR - init_workers(); -#endif /* YAPOR */ - Yap_init_local(); + Yap_init_root_frames(); +#endif /* YAPOR || TABLING */ #ifdef YAPOR + Yap_init_yapor_workers(); if (worker_id != 0) { -#if YAPOR_SBA||YAPOR_COPY +#if defined(YAPOR_COPY) || defined(YAPOR_SBA) /* In the SBA we cannot just happily inherit registers from the other workers */ Yap_InitYaamRegs(); -#endif /* YAPOR_SBA */ -#ifndef THREADS +#endif /* YAPOR_COPY || YAPOR_SBA */ +#ifndef YAPOR_THREADS Yap_InitPreAllocCodeSpace(); -#endif +#endif /* YAPOR_THREADS */ /* slaves, waiting for work */ CurrentModule = USER_MODULE; P = GETWORK_FIRST_TIME; @@ -2854,24 +2870,23 @@ YAP_Init(YAP_init_args *yap_init) Yap_Error(INTERNAL_ERROR, TermNil, "abstract machine unexpected exit (YAP_Init)"); } #endif /* YAPOR */ -#endif /* YAPOR || TABLING */ RECOVER_MACHINE_REGS(); } /* make sure we do this after restore */ if (yap_init->MaxStackSize) { - Yap_AllowLocalExpansion = FALSE; + GLOBAL_AllowLocalExpansion = FALSE; } else { - Yap_AllowLocalExpansion = TRUE; + GLOBAL_AllowLocalExpansion = TRUE; } if (yap_init->MaxGlobalSize) { - Yap_AllowGlobalExpansion = FALSE; + GLOBAL_AllowGlobalExpansion = FALSE; } else { - Yap_AllowGlobalExpansion = TRUE; + GLOBAL_AllowGlobalExpansion = TRUE; } if (yap_init->MaxTrailSize) { - Yap_AllowTrailExpansion = FALSE; + GLOBAL_AllowTrailExpansion = FALSE; } else { - Yap_AllowTrailExpansion = TRUE; + GLOBAL_AllowTrailExpansion = TRUE; } if (yap_init->YapPrologRCFile) { Yap_PutValue(AtomConsultOnBoot, MkAtomTerm(Yap_LookupAtom(yap_init->YapPrologRCFile))); @@ -2910,8 +2925,8 @@ YAP_Init(YAP_init_args *yap_init) } if (BOOT_FROM_SAVED_STATE && !do_bootstrap) { if (restore_result == FAIL_RESTORE) { - yap_init->ErrorNo = Yap_Error_TYPE; - yap_init->ErrorCause = Yap_ErrorMessage; + yap_init->ErrorNo = LOCAL_Error_TYPE; + yap_init->ErrorCause = LOCAL_ErrorMessage; return YAP_BOOT_ERROR; } if (Atts && Atts*1024 > 2048*sizeof(CELL)) @@ -3039,7 +3054,7 @@ YAP_Reset(void) } /* reinitialise the engine */ Yap_InitYaamRegs(); - Yap_Initialised = TRUE; + GLOBAL_Initialised = TRUE; RECOVER_MACHINE_REGS(); return(TRUE); @@ -3060,7 +3075,7 @@ X_API void YAP_SetOutputMessage(void) { #if DEBUG - Yap_output_msg = TRUE; + GLOBAL_output_msg = TRUE; #endif } @@ -3100,11 +3115,12 @@ YAP_Throw(Term t) X_API void YAP_AsyncThrow(Term t) -{ +{ + CACHE_REGS BACKUP_MACHINE_REGS(); - Yap_PrologMode |= AsyncIntMode; + LOCAL_PrologMode |= AsyncIntMode; Yap_JumpToEnv(t); - Yap_PrologMode &= ~AsyncIntMode; + LOCAL_PrologMode &= ~AsyncIntMode; RECOVER_MACHINE_REGS(); } @@ -3300,8 +3316,8 @@ YAP_AtomReleaseHold(Atom at) X_API Agc_hook YAP_AGCRegisterHook(Agc_hook hook) { - Agc_hook old = Yap_AGCHook; - Yap_AGCHook = hook; + Agc_hook old = GLOBAL_AGCHook; + GLOBAL_AGCHook = hook; return old; } @@ -3317,13 +3333,13 @@ YAP_cwd(void) CACHE_REGS char *buf; int len; - if (!Yap_getcwd(Yap_FileNameBuf, YAP_FILENAME_MAX)) + if (!Yap_getcwd(LOCAL_FileNameBuf, YAP_FILENAME_MAX)) return FALSE; - len = strlen(Yap_FileNameBuf); + len = strlen(LOCAL_FileNameBuf); buf = Yap_AllocCodeSpace(len+1); if (!buf) return NULL; - strncpy(buf, Yap_FileNameBuf, len); + strncpy(buf, LOCAL_FileNameBuf, len); return buf; } @@ -3455,22 +3471,22 @@ YAP_Recorded(void *handle) BACKUP_MACHINE_REGS(); do { - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; t = Yap_FetchTermFromDB(dbterm); - if (Yap_Error_TYPE == YAP_NO_ERROR) { + if (LOCAL_Error_TYPE == YAP_NO_ERROR) { RECOVER_MACHINE_REGS(); return t; - } else if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + } else if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); RECOVER_MACHINE_REGS(); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growstack(dbterm->NOfCells*CellSize)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); RECOVER_MACHINE_REGS(); return FALSE; } @@ -3537,9 +3553,9 @@ YAP_SetYAPFlag(yap_flag_t flag, int val) return TRUE; case YAPC_ENABLE_AGC: if (val) { - Yap_AGcThreshold = 10000; + GLOBAL_AGcThreshold = 10000; } else { - Yap_AGcThreshold = 0; + GLOBAL_AGcThreshold = 0; } return TRUE; default: diff --git a/C/cdmgr.c b/C/cdmgr.c index cef1ea4ea..a9451845b 100644 --- a/C/cdmgr.c +++ b/C/cdmgr.c @@ -483,9 +483,6 @@ STATIC_PROTO(void assertz_dynam_clause, (PredEntry *, yamop *)); STATIC_PROTO(void expand_consult, ( void )); STATIC_PROTO(int not_was_reconsulted, (PredEntry *, Term, int)); STATIC_PROTO(int RemoveIndexation, (PredEntry *)); -#if EMACS -STATIC_PROTO(int last_clause_number, (PredEntry *)); -#endif STATIC_PROTO(int static_in_use, (PredEntry *, int)); #if !defined(YAPOR) && !defined(THREADS) STATIC_PROTO(Int search_for_static_predicate_in_use, (PredEntry *, int)); @@ -635,26 +632,26 @@ static void InitConsultStack( void ) { CACHE_REGS - ConsultLow = (consult_obj *)Yap_AllocCodeSpace(sizeof(consult_obj)*InitialConsultCapacity); - if (ConsultLow == NULL) { + LOCAL_ConsultLow = (consult_obj *)Yap_AllocCodeSpace(sizeof(consult_obj)*InitialConsultCapacity); + if (LOCAL_ConsultLow == NULL) { Yap_Error(OUT_OF_HEAP_ERROR,TermNil,"No Heap Space in InitCodes"); return; } - ConsultCapacity = InitialConsultCapacity; - ConsultBase = ConsultSp = - ConsultLow + ConsultCapacity; + LOCAL_ConsultCapacity = InitialConsultCapacity; + LOCAL_ConsultBase = LOCAL_ConsultSp = + LOCAL_ConsultLow + LOCAL_ConsultCapacity; } void Yap_ResetConsultStack( void ) { CACHE_REGS - Yap_FreeCodeSpace((char *)ConsultLow); - ConsultBase = - ConsultSp = - ConsultLow = + Yap_FreeCodeSpace((char *)LOCAL_ConsultLow); + LOCAL_ConsultBase = + LOCAL_ConsultSp = + LOCAL_ConsultLow = NULL; - ConsultCapacity = InitialConsultCapacity; + LOCAL_ConsultCapacity = InitialConsultCapacity; } @@ -780,9 +777,9 @@ static Term BlobTermInCodeAdjust(Term t) { CACHE_REGS #if TAGS_FAST_OPS - return t-ClDiff; + return t-LOCAL_ClDiff; #else - return t+ClDiff; + return t+LOCAL_ClDiff; #endif } @@ -863,7 +860,7 @@ Yap_BuildMegaClause(PredEntry *ap) while (TRUE) { memcpy((void *)ptr, (void *)cl->ClCode, sz); if (has_blobs) { - ClDiff = (char *)(ptr)-(char *)cl->ClCode; + LOCAL_ClDiff = (char *)(ptr)-(char *)cl->ClCode; restore_opcodes(ptr, NULL PASS_REGS); } ptr = (yamop *)((char *)ptr + sz); @@ -961,13 +958,13 @@ IPred(PredEntry *ap, UInt NSlots, yamop *next_pc) #ifdef DEBUG CACHE_REGS - if (Yap_Option['i' - 'a' + 1]) { + if (GLOBAL_Option['i' - 'a' + 1]) { Term tmod = ap->ModuleOfPred; if (!tmod) tmod = TermProlog; - Yap_DebugPutc(Yap_c_error_stream,'\t'); + Yap_DebugPutc(LOCAL_c_error_stream,'\t'); Yap_DebugPlWrite(tmod); - Yap_DebugPutc(Yap_c_error_stream,':'); + Yap_DebugPutc(LOCAL_c_error_stream,':'); if (ap->ModuleOfPred == IDB_MODULE) { Term t = Deref(ARG1); if (IsAtomTerm(t)) { @@ -978,7 +975,7 @@ IPred(PredEntry *ap, UInt NSlots, yamop *next_pc) Functor f = FunctorOfTerm(t); Atom At = NameOfFunctor(f); Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(Yap_c_error_stream,'/'); + Yap_DebugPutc(LOCAL_c_error_stream,'/'); Yap_DebugPlWrite(MkIntTerm(ArityOfFunctor(f))); } } else { @@ -989,11 +986,11 @@ IPred(PredEntry *ap, UInt NSlots, yamop *next_pc) Functor f = ap->FunctorOfPred; Atom At = NameOfFunctor(f); Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(Yap_c_error_stream,'/'); + Yap_DebugPutc(LOCAL_c_error_stream,'/'); Yap_DebugPlWrite(MkIntTerm(ArityOfFunctor(f))); } } - Yap_DebugPutc(Yap_c_error_stream,'\n'); + Yap_DebugPutc(LOCAL_c_error_stream,'\n'); } #endif /* Do not try to index a dynamic predicate or one whithout args */ @@ -1020,8 +1017,8 @@ IPred(PredEntry *ap, UInt NSlots, yamop *next_pc) ap->OpcodeOfPred = ap->CodeOfPred->opc; } #ifdef DEBUG - if (Yap_Option['i' - 'a' + 1]) - Yap_DebugPutc(Yap_c_error_stream,'\n'); + if (GLOBAL_Option['i' - 'a' + 1]) + Yap_DebugPutc(LOCAL_c_error_stream,'\n'); #endif } @@ -1954,30 +1951,30 @@ static void expand_consult( void ) { CACHE_REGS consult_obj *new_cl, *new_cs; - UInt OldConsultCapacity = ConsultCapacity; + UInt OldConsultCapacity = LOCAL_ConsultCapacity; /* now double consult capacity */ - ConsultCapacity += InitialConsultCapacity; + LOCAL_ConsultCapacity += InitialConsultCapacity; /* I assume it always works ;-) */ - while ((new_cl = (consult_obj *)Yap_AllocCodeSpace(sizeof(consult_obj)*ConsultCapacity)) == NULL) { - if (!Yap_growheap(FALSE, sizeof(consult_obj)*ConsultCapacity, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR,TermNil,Yap_ErrorMessage); + while ((new_cl = (consult_obj *)Yap_AllocCodeSpace(sizeof(consult_obj)*LOCAL_ConsultCapacity)) == NULL) { + if (!Yap_growheap(FALSE, sizeof(consult_obj)*LOCAL_ConsultCapacity, NULL)) { + Yap_Error(OUT_OF_HEAP_ERROR,TermNil,LOCAL_ErrorMessage); return; } } new_cs = new_cl + InitialConsultCapacity; /* start copying */ - memcpy((void *)new_cs, (void *)ConsultLow, OldConsultCapacity*sizeof(consult_obj)); + memcpy((void *)new_cs, (void *)LOCAL_ConsultLow, OldConsultCapacity*sizeof(consult_obj)); /* copying done, release old space */ - Yap_FreeCodeSpace((char *)ConsultLow); + Yap_FreeCodeSpace((char *)LOCAL_ConsultLow); /* next, set up pointers correctly */ - new_cs += (ConsultSp-ConsultLow); - /* put ConsultBase at same offset as before move */ - ConsultBase = ConsultBase+(new_cs-ConsultSp); + new_cs += (LOCAL_ConsultSp-LOCAL_ConsultLow); + /* put LOCAL_ConsultBase at same offset as before move */ + LOCAL_ConsultBase = LOCAL_ConsultBase+(new_cs-LOCAL_ConsultSp); /* new consult pointer */ - ConsultSp = new_cs; + LOCAL_ConsultSp = new_cs; /* new end of memory */ - ConsultLow = new_cl; + LOCAL_ConsultLow = new_cl; } /* p was already locked */ @@ -1988,28 +1985,28 @@ not_was_reconsulted(PredEntry *p, Term t, int mode) register consult_obj *fp; Prop p0 = AbsProp((PropEntry *)p); - if (p == LastAssertedPred) + if (p == LOCAL_LastAssertedPred) return FALSE; - LastAssertedPred = p; - if (!ConsultSp) { + LOCAL_LastAssertedPred = p; + if (!LOCAL_ConsultSp) { InitConsultStack(); } if (p->cs.p_code.NOfClauses) { - for (fp = ConsultSp; fp < ConsultBase; ++fp) + for (fp = LOCAL_ConsultSp; fp < LOCAL_ConsultBase; ++fp) if (fp->p == p0) break; } else { - fp = ConsultBase; + fp = LOCAL_ConsultBase; } - if (fp != ConsultBase) + if (fp != LOCAL_ConsultBase) return FALSE; if (mode) { - if (ConsultSp == ConsultLow+1) { + if (LOCAL_ConsultSp == LOCAL_ConsultLow+1) { expand_consult(); } - --ConsultSp; - ConsultSp->p = p0; - if (ConsultBase[1].mode && + --LOCAL_ConsultSp; + LOCAL_ConsultSp->p = p0; + if (LOCAL_ConsultBase[1].mode && !(p->PredFlags & MultiFileFlag)) /* we are in reconsult mode */ { retract_all(p, static_in_use(p,TRUE)); } @@ -2027,21 +2024,21 @@ addcl_permission_error(AtomEntry *ap, Int Arity, int in_use) ti[0] = MkAtomTerm(AbsAtom(ap)); ti[1] = MkIntegerTerm(Arity); t = Yap_MkApplTerm(FunctorSlash, 2, ti); - Yap_ErrorMessage = Yap_ErrorSay; - Yap_Error_Term = t; - Yap_Error_TYPE = PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE; + LOCAL_ErrorMessage = LOCAL_ErrorSay; + LOCAL_Error_Term = t; + LOCAL_Error_TYPE = PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE; if (in_use) { if (Arity == 0) - sprintf(Yap_ErrorMessage, "static predicate %s is in use", ap->StrOfAE); + sprintf(LOCAL_ErrorMessage, "static predicate %s is in use", ap->StrOfAE); else - sprintf(Yap_ErrorMessage, + sprintf(LOCAL_ErrorMessage, "static predicate %s/" Int_FORMAT " is in use", ap->StrOfAE, Arity); } else { if (Arity == 0) - sprintf(Yap_ErrorMessage, "system predicate %s", ap->StrOfAE); + sprintf(LOCAL_ErrorMessage, "system predicate %s", ap->StrOfAE); else - sprintf(Yap_ErrorMessage, + sprintf(LOCAL_ErrorMessage, "system predicate %s/" Int_FORMAT, ap->StrOfAE, Arity); } @@ -2199,7 +2196,7 @@ addclause(Term t, yamop *cp, int mode, Term mod, Term *t4ref) if (mode == consult) not_was_reconsulted(p, t, TRUE); /* always check if we have a valid error first */ - if (Yap_ErrorMessage && Yap_Error_TYPE == PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE) { + if (LOCAL_ErrorMessage && LOCAL_Error_TYPE == PERMISSION_ERROR_MODIFY_STATIC_PROCEDURE) { UNLOCKPE(31,p); return TermNil; } @@ -2438,25 +2435,6 @@ Yap_add_logupd_clause(PredEntry *pe, LogUpdClause *cl, int mode) { } } -#if EMACS - -/* - * the place where one would add a new clause for the propriety pred_prop - */ -int -where_new_clause(pred_prop, mode) - Prop pred_prop; - int mode; -{ - PredEntry *p = RepPredProp(pred_prop); - - if (mode == consult && not_was_reconsulted(p, TermNil, FALSE)) - return (1); - else - return (p->cs.p_code.NOfClauses + 1); -} -#endif - static Int p_compile( USES_REGS1 ) { /* '$compile'(+C,+Flags, Mod) */ @@ -2475,15 +2453,15 @@ p_compile( USES_REGS1 ) codeadr = Yap_cclause(t, 4, mod, Deref(ARG3)); /* vsc: give the number of arguments to cclause in case there is overflow */ t = Deref(ARG1); /* just in case there was an heap overflow */ - if (!Yap_ErrorMessage) + if (!LOCAL_ErrorMessage) addclause(t, codeadr, (int) (IntOfTerm(t1) & 3), mod, &tn); YAPLeaveCriticalSection(); - if (Yap_ErrorMessage) { + if (LOCAL_ErrorMessage) { if (IntOfTerm(t1) & 4) { - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, - "in line %d, %s", Yap_FirstLineInParse(), Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, + "in line %d, %s", Yap_FirstLineInParse(), LOCAL_ErrorMessage); } else { - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); } return FALSE; } @@ -2507,24 +2485,26 @@ p_compile_dynamic( USES_REGS1 ) if (RepAtom(AtomOfTerm(t1))->StrOfAE[0] == 'f') mode = asserta; else mode = assertz; } else mode = IntegerOfTerm(t1); - if (mode == assertz && consult_level) - mode = consult; + /* separate assert in current file from reconsult + if (mode == assertz && LOCAL_consult_level && mod == CurrentModule) + mode = consult; + */ old_optimize = optimizer_on; optimizer_on = FALSE; YAPEnterCriticalSection(); code_adr = Yap_cclause(t, 5, mod, Deref(ARG3)); /* vsc: give the number of arguments to cclause() in case there is a overflow */ t = Deref(ARG1); /* just in case there was an heap overflow */ - if (!Yap_ErrorMessage) { + if (!LOCAL_ErrorMessage) { optimizer_on = old_optimize; addclause(t, code_adr, mode , mod, &ARG5); } - if (Yap_ErrorMessage) { - if (!Yap_Error_Term) - Yap_Error_Term = TermNil; - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + if (LOCAL_ErrorMessage) { + if (!LOCAL_Error_Term) + LOCAL_Error_Term = TermNil; + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); YAPLeaveCriticalSection(); return FALSE; } @@ -2535,10 +2515,10 @@ p_compile_dynamic( USES_REGS1 ) static Atom YapConsultingFile ( USES_REGS1 ) { - if (consult_level == 0) { + if (LOCAL_consult_level == 0) { return(AtomUser); } else { - return(Yap_LookupAtom(ConsultBase[2].filename)); + return(Yap_LookupAtom(LOCAL_ConsultBase[2].filename)); } } @@ -2554,22 +2534,22 @@ static void init_consult(int mode, char *file) { CACHE_REGS - if (!ConsultSp) { + if (!LOCAL_ConsultSp) { InitConsultStack(); } - ConsultSp--; - ConsultSp->filename = file; - ConsultSp--; - ConsultSp->mode = mode; - ConsultSp--; - ConsultSp->c = (ConsultBase-ConsultSp); - ConsultBase = ConsultSp; + LOCAL_ConsultSp--; + LOCAL_ConsultSp->filename = file; + LOCAL_ConsultSp--; + LOCAL_ConsultSp->mode = mode; + LOCAL_ConsultSp--; + LOCAL_ConsultSp->c = (LOCAL_ConsultBase-LOCAL_ConsultSp); + LOCAL_ConsultBase = LOCAL_ConsultSp; #if !defined(YAPOR) && !defined(YAPOR_SBA) - /* if (consult_level == 0) + /* if (LOCAL_consult_level == 0) do_toggle_static_predicates_in_use(TRUE); */ #endif - consult_level++; - LastAssertedPred = NULL; + LOCAL_consult_level++; + LOCAL_LastAssertedPred = NULL; } void @@ -2587,7 +2567,7 @@ p_startconsult( USES_REGS1 ) mode = strcmp("consult",smode); init_consult(mode, RepAtom(AtomOfTerm(Deref(ARG2)))->StrOfAE); - t = MkIntTerm(consult_level); + t = MkIntTerm(LOCAL_consult_level); return (Yap_unify_constant(ARG3, t)); } @@ -2596,20 +2576,20 @@ p_showconslultlev( USES_REGS1 ) { Term t; - t = MkIntTerm(consult_level); + t = MkIntTerm(LOCAL_consult_level); return (Yap_unify_constant(ARG1, t)); } static void end_consult( USES_REGS1 ) { - ConsultSp = ConsultBase; - ConsultBase = ConsultSp+ConsultSp->c; - ConsultSp += 3; - consult_level--; - LastAssertedPred = NULL; + LOCAL_ConsultSp = LOCAL_ConsultBase; + LOCAL_ConsultBase = LOCAL_ConsultSp+LOCAL_ConsultSp->c; + LOCAL_ConsultSp += 3; + LOCAL_consult_level--; + LOCAL_LastAssertedPred = NULL; #if !defined(YAPOR) && !defined(YAPOR_SBA) - /* if (consult_level == 0) + /* if (LOCAL_consult_level == 0) do_toggle_static_predicates_in_use(FALSE);*/ #endif } @@ -3406,9 +3386,9 @@ all_envs(CELL *env_ptr USES_REGS) bp[0] = MkIntegerTerm(LCL0-env_ptr); if (H >= ASP-1024) { H = start; - Yap_Error_Size = (ASP-1024)-H; + LOCAL_Error_Size = (ASP-1024)-H; while (env_ptr) { - Yap_Error_Size += 2; + LOCAL_Error_Size += 2; env_ptr = (CELL *)(env_ptr[E_E]); } return 0L; @@ -3435,9 +3415,9 @@ all_cps(choiceptr b_ptr USES_REGS) bp[0] = MkIntegerTerm((Int)(LCL0-(CELL *)b_ptr)); if (H >= ASP-1024) { H = start; - Yap_Error_Size = (ASP-1024)-H; + LOCAL_Error_Size = (ASP-1024)-H; while (b_ptr) { - Yap_Error_Size += 2; + LOCAL_Error_Size += 2; b_ptr = b_ptr->cp_b; } return 0L; @@ -3483,7 +3463,7 @@ p_all_choicepoints( USES_REGS1 ) { Term t; while ((t = all_cps(B PASS_REGS)) == 0L) { - if (!Yap_gcl(Yap_Error_Size, 1, ENV, gc_P(P,CP))) { + if (!Yap_gcl(LOCAL_Error_Size, 1, ENV, gc_P(P,CP))) { Yap_Error(OUT_OF_STACK_ERROR, TermNil, "while dumping choicepoints"); return FALSE; } @@ -3496,7 +3476,7 @@ p_all_envs( USES_REGS1 ) { Term t; while ((t = all_envs(ENV PASS_REGS)) == 0L) { - if (!Yap_gcl(Yap_Error_Size, 1, ENV, gc_P(P,CP))) { + if (!Yap_gcl(LOCAL_Error_Size, 1, ENV, gc_P(P,CP))) { Yap_Error(OUT_OF_STACK_ERROR, TermNil, "while dumping environments"); return FALSE; } @@ -3509,7 +3489,7 @@ p_current_stack( USES_REGS1 ) { Term t; while ((t = all_calls( PASS_REGS1 )) == 0L) { - if (!Yap_gcl(Yap_Error_Size, 1, ENV, gc_P(P,CP))) { + if (!Yap_gcl(LOCAL_Error_Size, 1, ENV, gc_P(P,CP))) { Yap_Error(OUT_OF_STACK_ERROR, TermNil, "while dumping stack"); return FALSE; } @@ -4141,20 +4121,20 @@ p_is_call_counted( USES_REGS1 ) static Int p_call_count_info( USES_REGS1 ) { - return(Yap_unify(MkIntegerTerm(ReductionsCounter),ARG1) && - Yap_unify(MkIntegerTerm(PredEntriesCounter),ARG2) && - Yap_unify(MkIntegerTerm(PredEntriesCounter),ARG3)); + return(Yap_unify(MkIntegerTerm(LOCAL_ReductionsCounter),ARG1) && + Yap_unify(MkIntegerTerm(LOCAL_PredEntriesCounter),ARG2) && + Yap_unify(MkIntegerTerm(LOCAL_PredEntriesCounter),ARG3)); } static Int p_call_count_reset( USES_REGS1 ) { - ReductionsCounter = 0; - ReductionsCounterOn = FALSE; - PredEntriesCounter = 0; - PredEntriesCounterOn = FALSE; - RetriesCounter = 0; - RetriesCounterOn = FALSE; + LOCAL_ReductionsCounter = 0; + LOCAL_ReductionsCounterOn = FALSE; + LOCAL_PredEntriesCounter = 0; + LOCAL_PredEntriesCounterOn = FALSE; + LOCAL_RetriesCounter = 0; + LOCAL_RetriesCounterOn = FALSE; return(TRUE); } @@ -4166,14 +4146,14 @@ p_call_count_set( USES_REGS1 ) int do_entries = IntOfTerm(ARG6); if (do_calls) - ReductionsCounter = IntegerOfTerm(Deref(ARG1)); - ReductionsCounterOn = do_calls; + LOCAL_ReductionsCounter = IntegerOfTerm(Deref(ARG1)); + LOCAL_ReductionsCounterOn = do_calls; if (do_retries) - RetriesCounter = IntegerOfTerm(Deref(ARG3)); - RetriesCounterOn = do_retries; + LOCAL_RetriesCounter = IntegerOfTerm(Deref(ARG3)); + LOCAL_RetriesCounterOn = do_retries; if (do_entries) - PredEntriesCounter = IntegerOfTerm(Deref(ARG5)); - PredEntriesCounterOn = do_entries; + LOCAL_PredEntriesCounter = IntegerOfTerm(Deref(ARG5)); + LOCAL_PredEntriesCounterOn = do_entries; return(TRUE); } @@ -4482,18 +4462,18 @@ fetch_next_lu_clause(PredEntry *pe, yamop *i_code, Term th, Term tb, Term tr, ya ARG5 = th; ARG6 = tb; ARG7 = tr; - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { UNLOCK(pe->PELock); - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 7, ENV, gc_P(P,CP))) { + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 7, ENV, gc_P(P,CP))) { UNLOCK(pe->PELock); - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -4504,9 +4484,9 @@ fetch_next_lu_clause(PredEntry *pe, yamop *i_code, Term th, Term tb, Term tr, ya ARG6 = th; ARG7 = tb; ARG8 = tr; - if (!Yap_gcl(Yap_Error_Size, 8, ENV, gc_P(P,CP))) { + if (!Yap_gcl(LOCAL_Error_Size, 8, ENV, gc_P(P,CP))) { UNLOCK(pe->PELock); - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } th = ARG6; @@ -4630,18 +4610,18 @@ fetch_next_lu_clause_erase(PredEntry *pe, yamop *i_code, Term th, Term tb, Term ARG5 = th; ARG6 = tb; ARG7 = tr; - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { UNLOCK(pe->PELock); - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 7, ENV, gc_P(P,CP))) { + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 7, ENV, gc_P(P,CP))) { UNLOCK(pe->PELock); - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -4652,9 +4632,9 @@ fetch_next_lu_clause_erase(PredEntry *pe, yamop *i_code, Term th, Term tb, Term ARG6 = th; ARG7 = tb; ARG8 = tr; - if (!Yap_gcl(Yap_Error_Size, 8, ENV, CP)) { + if (!Yap_gcl(LOCAL_Error_Size, 8, ENV, CP)) { UNLOCK(pe->PELock); - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } th = ARG6; @@ -4868,7 +4848,7 @@ Yap_UpdateTimestamps(PredEntry *ap) return; overflow: if (!Yap_growstack(64*1024)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return; } goto restart; @@ -4967,19 +4947,19 @@ fetch_next_static_clause(PredEntry *pe, yamop *i_code, Term th, Term tb, Term tr } while ((t = Yap_FetchTermFromDB(cl->usc.ClSource)) == 0L) { if (first_time) { - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; ARG5 = th; ARG6 = tb; ARG7 = tr; if (!Yap_gc(7, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } th = ARG5; @@ -4987,12 +4967,12 @@ fetch_next_static_clause(PredEntry *pe, yamop *i_code, Term th, Term tb, Term tr tr = ARG7; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; ARG6 = th; ARG7 = tb; ARG8 = tr; - if (!Yap_gcl(Yap_Error_Size, 8, ENV, CP)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + if (!Yap_gcl(LOCAL_Error_Size, 8, ENV, CP)) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } th = ARG6; diff --git a/C/cmppreds.c b/C/cmppreds.c index 8637a82c4..9402f82c7 100644 --- a/C/cmppreds.c +++ b/C/cmppreds.c @@ -481,14 +481,14 @@ flt_cmp(Float dif) static inline Int a_cmp(Term t1, Term t2 USES_REGS) { - ArithError = FALSE; + LOCAL_ArithError = FALSE; if (IsVarTerm(t1)) { - ArithError = TRUE; + LOCAL_ArithError = TRUE; Yap_Error(INSTANTIATION_ERROR, t1, "=:=/2"); return FALSE; } if (IsVarTerm(t2)) { - ArithError = TRUE; + LOCAL_ArithError = TRUE; Yap_Error(INSTANTIATION_ERROR, t2, "=:=/2"); return FALSE; } @@ -513,10 +513,10 @@ a_cmp(Term t1, Term t2 USES_REGS) Float f2 = FloatOfTerm(t2); #if HAVE_ISNAN if (isnan(f2)) { - Yap_Error_TYPE = EVALUATION_ERROR_UNDEFINED; - Yap_Error_Term = t2; - Yap_ErrorMessage = "trying to evaluate nan"; - ArithError = TRUE; + LOCAL_Error_TYPE = EVALUATION_ERROR_UNDEFINED; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = "trying to evaluate nan"; + LOCAL_ArithError = TRUE; } #endif return flt_cmp(i1-f2); @@ -531,10 +531,10 @@ a_cmp(Term t1, Term t2 USES_REGS) Float f1 = FloatOfTerm(t1); #if HAVE_ISNAN if (isnan(f1)) { - Yap_Error_TYPE = EVALUATION_ERROR_UNDEFINED; - Yap_Error_Term = t1; - Yap_ErrorMessage = "trying to evaluate nan"; - ArithError = TRUE; + LOCAL_Error_TYPE = EVALUATION_ERROR_UNDEFINED; + LOCAL_Error_Term = t1; + LOCAL_ErrorMessage = "trying to evaluate nan"; + LOCAL_ArithError = TRUE; } #endif t2 = Yap_Eval(t2); @@ -550,10 +550,10 @@ a_cmp(Term t1, Term t2 USES_REGS) Float f2 = FloatOfTerm(t2); #if HAVE_ISNAN if (isnan(f2)) { - Yap_Error_TYPE = EVALUATION_ERROR_UNDEFINED; - Yap_Error_Term = t2; - Yap_ErrorMessage = "trying to evaluate nan"; - ArithError = TRUE; + LOCAL_Error_TYPE = EVALUATION_ERROR_UNDEFINED; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = "trying to evaluate nan"; + LOCAL_ArithError = TRUE; } #endif return flt_cmp(f1-f2); @@ -575,10 +575,10 @@ a_cmp(Term t1, Term t2 USES_REGS) Float f2 = FloatOfTerm(t2); #if HAVE_ISNAN if (isnan(f2)) { - Yap_Error_TYPE = EVALUATION_ERROR_UNDEFINED; - Yap_Error_Term = t2; - Yap_ErrorMessage = "trying to evaluate nan"; - ArithError = TRUE; + LOCAL_Error_TYPE = EVALUATION_ERROR_UNDEFINED; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = "trying to evaluate nan"; + LOCAL_ArithError = TRUE; } #endif return Yap_gmp_cmp_big_float(t1, f2); @@ -603,7 +603,7 @@ p_acomp( USES_REGS1 ) Int out; out = a_cmp(t1, t2 PASS_REGS); - if (ArithError) { Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); return FALSE; } + if (LOCAL_ArithError) { Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } return out; } @@ -637,7 +637,7 @@ a_eq(Term t1, Term t2) } } out = a_cmp(t1,t2 PASS_REGS); - if (ArithError) { Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); return FALSE; } + if (LOCAL_ArithError) { Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } return out == 0; } @@ -646,7 +646,7 @@ a_dif(Term t1, Term t2) { CACHE_REGS Int out = a_cmp(Deref(t1),Deref(t2) PASS_REGS); - if (ArithError) { Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); return FALSE; } + if (LOCAL_ArithError) { Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } return out != 0; } @@ -655,7 +655,7 @@ a_gt(Term t1, Term t2) { /* A > B */ CACHE_REGS Int out = a_cmp(Deref(t1),Deref(t2) PASS_REGS); - if (ArithError) { Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); return FALSE; } + if (LOCAL_ArithError) { Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } return out > 0; } @@ -664,7 +664,7 @@ a_ge(Term t1, Term t2) { /* A >= B */ CACHE_REGS Int out = a_cmp(Deref(t1),Deref(t2) PASS_REGS); - if (ArithError) { Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); return FALSE; } + if (LOCAL_ArithError) { Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } return out >= 0; } @@ -673,7 +673,7 @@ a_lt(Term t1, Term t2) { /* A < B */ CACHE_REGS Int out = a_cmp(Deref(t1),Deref(t2) PASS_REGS); - if (ArithError) { Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); return FALSE; } + if (LOCAL_ArithError) { Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } return out < 0; } @@ -682,7 +682,7 @@ a_le(Term t1, Term t2) { /* A <= B */ CACHE_REGS Int out = a_cmp(Deref(t1),Deref(t2) PASS_REGS); - if (ArithError) { Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); return FALSE; } + if (LOCAL_ArithError) { Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } return out <= 0; } diff --git a/C/compiler.c b/C/compiler.c index 35a9e1f5c..03d759216 100755 --- a/C/compiler.c +++ b/C/compiler.c @@ -286,7 +286,7 @@ active_branch(int i, int onbranch) return(i==onbranch);*/ } -#define FAIL(M,T,E) { Yap_ErrorMessage=M; Yap_Error_TYPE = T; Yap_Error_Term = E; return; } +#define FAIL(M,T,E) { LOCAL_ErrorMessage=M; LOCAL_Error_TYPE = T; LOCAL_Error_Term = E; return; } #if USE_SYSTEM_MALLOC #define IsNewVar(v) ((CELL *)(v) >= H0 && (CELL *)(v) < LCL0) @@ -567,9 +567,9 @@ compile_sf_term(Term t, int argno, int level) if (IsAtomicTerm(t)) Yap_emit((cglobs->onhead ? unify_s_a_op : write_s_a_op), t, (CELL) argno, &cglobs->cint); else if (!IsVarTerm(t)) { - Yap_Error_TYPE = INTERNAL_COMPILER_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "illegal argument of soft functor"; + LOCAL_Error_TYPE = INTERNAL_COMPILER_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "illegal argument of soft functor"; save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch, COMPILER_ERR_BOTCH); } @@ -595,9 +595,9 @@ c_args(Term app, unsigned int level, compiler_struct *cglobs) if (level == 0) { if (Arity >= MaxTemps) { - Yap_Error_TYPE = INTERNAL_COMPILER_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "exceed maximum arity of compiled goal"; + LOCAL_Error_TYPE = INTERNAL_COMPILER_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "exceed maximum arity of compiled goal"; save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch, COMPILER_ERR_BOTCH); } @@ -619,7 +619,7 @@ try_store_as_dbterm(Term t, Int argno, unsigned int arity, int level, compiler_s while ((g=Yap_SizeGroundTerm(t,TRUE)) < 0) { /* oops, too deep a term */ save_machine_regs(); - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; siglongjmp(cglobs->cint.CompilerBotch, OUT_OF_AUX_BOTCH); } if (g < 16) @@ -628,18 +628,18 @@ try_store_as_dbterm(Term t, Int argno, unsigned int arity, int level, compiler_s H = CellPtr(cglobs->cint.freep); if ((dbt = Yap_StoreTermInDB(t, -1)) == NULL) { H = h0; - switch(Yap_Error_TYPE) { + switch(LOCAL_Error_TYPE) { case OUT_OF_STACK_ERROR: - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; siglongjmp(cglobs->cint.CompilerBotch,OUT_OF_STACK_BOTCH); case OUT_OF_TRAIL_ERROR: - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; siglongjmp(cglobs->cint.CompilerBotch,OUT_OF_TRAIL_BOTCH); case OUT_OF_HEAP_ERROR: - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; siglongjmp(cglobs->cint.CompilerBotch,OUT_OF_HEAP_BOTCH); case OUT_OF_AUXSPACE_ERROR: - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; siglongjmp(cglobs->cint.CompilerBotch,OUT_OF_AUX_BOTCH); default: siglongjmp(cglobs->cint.CompilerBotch,COMPILER_ERR_BOTCH); @@ -1010,11 +1010,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler } else { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_NUMBER; - Yap_Error_Term = t2; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_NUMBER; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/2 with output bound", s); + sprintf(LOCAL_ErrorMessage, "compiling %s/2 with output bound", s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1025,11 +1025,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler if (IsNewVar(t2)) { char s[32]; - Yap_Error_TYPE = INSTANTIATION_ERROR; - Yap_Error_Term = t2; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = INSTANTIATION_ERROR; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/3",s); + sprintf(LOCAL_ErrorMessage, "compiling %s/3",s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1041,11 +1041,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler if (!IsIntegerTerm(t2)) { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_INTEGER; - Yap_Error_Term = t2; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_INTEGER; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling functor/3"); + sprintf(LOCAL_ErrorMessage, "compiling functor/3"); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1053,11 +1053,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler if (i2 < 0) { char s[32]; - Yap_Error_TYPE = DOMAIN_ERROR_NOT_LESS_THAN_ZERO; - Yap_Error_Term = t2; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = DOMAIN_ERROR_NOT_LESS_THAN_ZERO; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling functor/3"); + sprintf(LOCAL_ErrorMessage, "compiling functor/3"); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1068,11 +1068,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler } else if (!IsAtomTerm(t1)) { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_ATOM; - Yap_Error_Term = t2; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_ATOM; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling functor/3"); + sprintf(LOCAL_ErrorMessage, "compiling functor/3"); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1126,11 +1126,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler else { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_INTEGER; - Yap_Error_Term = t2; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_INTEGER; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/2", s); + sprintf(LOCAL_ErrorMessage, "compiling %s/2", s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1138,11 +1138,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler (IsApplTerm(t2) && IsExtensionFunctor(FunctorOfTerm(t2)))) { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_COMPOUND; - Yap_Error_Term = t2; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_COMPOUND; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/2", s); + sprintf(LOCAL_ErrorMessage, "compiling %s/2", s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } else if (IsApplTerm(t2)) { @@ -1169,11 +1169,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler } else { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_INTEGER; - Yap_Error_Term = t2; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_INTEGER; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/2", s); + sprintf(LOCAL_ErrorMessage, "compiling %s/2", s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1182,11 +1182,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler if (!IsAtomicTerm(t1)) { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_ATOM; - Yap_Error_Term = t1; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_ATOM; + LOCAL_Error_Term = t1; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/2", s); + sprintf(LOCAL_ErrorMessage, "compiling %s/2", s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } else { @@ -1197,11 +1197,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler if (!IsIntegerTerm(t2)) { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_INTEGER; - Yap_Error_Term = t2; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_INTEGER; + LOCAL_Error_Term = t2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/2", s); + sprintf(LOCAL_ErrorMessage, "compiling %s/2", s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1215,11 +1215,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler if (!IsAtomTerm(t1)) { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_ATOM; - Yap_Error_Term = t1; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_ATOM; + LOCAL_Error_Term = t1; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/2", s); + sprintf(LOCAL_ErrorMessage, "compiling %s/2", s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1259,11 +1259,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler } else { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_VARIABLE; - Yap_Error_Term = t1; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_VARIABLE; + LOCAL_Error_Term = t1; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/2 with output bound", s); + sprintf(LOCAL_ErrorMessage, "compiling %s/2 with output bound", s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1282,11 +1282,11 @@ c_bifun(basic_preds Op, Term t1, Term t2, Term t3, Term Goal, Term mod, compiler } else { char s[32]; - Yap_Error_TYPE = TYPE_ERROR_VARIABLE; - Yap_Error_Term = t3; - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_Error_TYPE = TYPE_ERROR_VARIABLE; + LOCAL_Error_Term = t3; + LOCAL_ErrorMessage = LOCAL_ErrorSay; Yap_bip_name(Op, s); - sprintf(Yap_ErrorMessage, "compiling %s/2 with input unbound", s); + sprintf(LOCAL_ErrorMessage, "compiling %s/2 with input unbound", s); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -1450,12 +1450,12 @@ c_goal(Term Goal, Term mod, compiler_struct *cglobs) if (IsVarTerm(M) || !IsAtomTerm(M)) { CACHE_REGS if (IsVarTerm(M)) { - Yap_Error_TYPE = INSTANTIATION_ERROR; + LOCAL_Error_TYPE = INSTANTIATION_ERROR; } else { - Yap_Error_TYPE = TYPE_ERROR_ATOM; + LOCAL_Error_TYPE = TYPE_ERROR_ATOM; } - Yap_Error_Term = M; - Yap_ErrorMessage = "in module name"; + LOCAL_Error_Term = M; + LOCAL_ErrorMessage = "in module name"; save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch, COMPILER_ERR_BOTCH); } @@ -1469,8 +1469,8 @@ c_goal(Term Goal, Term mod, compiler_struct *cglobs) FAIL("goal can not be a number", TYPE_ERROR_CALLABLE, Goal); } else if (IsRefTerm(Goal)) { CACHE_REGS - Yap_Error_TYPE = TYPE_ERROR_DBREF; - Yap_Error_Term = Goal; + LOCAL_Error_TYPE = TYPE_ERROR_DBREF; + LOCAL_Error_Term = Goal; FAIL("goal argument in static procedure can not be a data base reference", TYPE_ERROR_CALLABLE, Goal); } else if (IsPairTerm(Goal)) { @@ -1906,10 +1906,10 @@ c_goal(Term Goal, Term mod, compiler_struct *cglobs) Term a2 = ArgOfTerm(2,Goal); if (IsVarTerm(a2) && !IsNewVar(a2)) { if (IsNewVar(a2)) { - Yap_Error_TYPE = INSTANTIATION_ERROR; - Yap_Error_Term = a2; - Yap_ErrorMessage = Yap_ErrorSay; - sprintf(Yap_ErrorMessage, "compiling %s/2 with second arg unbound", RepAtom(NameOfFunctor(p->FunctorOfPred))->StrOfAE); + LOCAL_Error_TYPE = INSTANTIATION_ERROR; + LOCAL_Error_Term = a2; + LOCAL_ErrorMessage = LOCAL_ErrorSay; + sprintf(LOCAL_ErrorMessage, "compiling %s/2 with second arg unbound", RepAtom(NameOfFunctor(p->FunctorOfPred))->StrOfAE); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch,1); } @@ -2314,9 +2314,9 @@ clear_bvarray(int var, CELL *bvarray if (*bvarray & nbit) { CACHE_REGS /* someone had already marked this variable: complain */ - Yap_Error_TYPE = INTERNAL_COMPILER_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "compiler internal error: variable initialised twice"; + LOCAL_Error_TYPE = INTERNAL_COMPILER_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "compiler internal error: variable initialised twice"; fprintf(stderr," vsc: compiling7\n"); save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch, COMPILER_ERR_BOTCH); @@ -2357,9 +2357,9 @@ push_bvmap(int label, PInstr *pcpc, compiler_struct *cglobs) { if (bvindex == MAX_DISJUNCTIONS) { CACHE_REGS - Yap_Error_TYPE = INTERNAL_COMPILER_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "Too many embedded disjunctions"; + LOCAL_Error_TYPE = INTERNAL_COMPILER_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "Too many embedded disjunctions"; save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch, COMPILER_ERR_BOTCH); } @@ -2381,9 +2381,9 @@ reset_bvmap(CELL *bvarray, int nperm, compiler_struct *cglobs) if (bvindex == 0) { CACHE_REGS - Yap_Error_TYPE = INTERNAL_COMPILER_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "No embedding in disjunctions"; + LOCAL_Error_TYPE = INTERNAL_COMPILER_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "No embedding in disjunctions"; save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch, COMPILER_ERR_BOTCH); } @@ -2402,9 +2402,9 @@ pop_bvmap(CELL *bvarray, int nperm, compiler_struct *cglobs) { if (bvindex == 0) { CACHE_REGS - Yap_Error_TYPE = INTERNAL_COMPILER_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "Too few embedded disjunctions"; + LOCAL_Error_TYPE = INTERNAL_COMPILER_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "Too few embedded disjunctions"; /* save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch, OUT_OF_HEAP_BOTCH); */ } @@ -2673,9 +2673,9 @@ checktemp(Int arg, Int rn, compiler_vm_op ic, compiler_struct *cglobs) } if (target1 == cglobs->MaxCTemps) { CACHE_REGS - Yap_Error_TYPE = INTERNAL_COMPILER_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "too many temporaries"; + LOCAL_Error_TYPE = INTERNAL_COMPILER_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "too many temporaries"; save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch, COMPILER_ERR_BOTCH); } @@ -2807,9 +2807,9 @@ c_layout(compiler_struct *cglobs) #ifdef DEBUG if (cglobs->pbvars != nperm) { CACHE_REGS - Yap_Error_TYPE = INTERNAL_COMPILER_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "wrong number of variables found in bitmap"; + LOCAL_Error_TYPE = INTERNAL_COMPILER_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "wrong number of variables found in bitmap"; save_machine_regs(); siglongjmp(cglobs->cint.CompilerBotch, OUT_OF_HEAP_BOTCH); } @@ -3357,7 +3357,7 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) compiler_struct cglobs; /* make sure we know there was no error yet */ - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; if ((botch_why = sigsetjmp(cglobs.cint.CompilerBotch, 0))) { restore_machine_regs(); reset_vars(cglobs.vtable); @@ -3371,14 +3371,14 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) ARG3 = src; YAPLeaveCriticalSection(); - if (!Yap_gcl(Yap_Error_Size, NOfArgs, ENV, gc_P(P,CP))) { - Yap_Error_TYPE = OUT_OF_STACK_ERROR; - Yap_Error_Term = inp_clause; + if (!Yap_gcl(LOCAL_Error_Size, NOfArgs, ENV, gc_P(P,CP))) { + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Term = inp_clause; } if (osize > ASP-H) { if (!Yap_growstack(2*sizeof(CELL)*(ASP-H))) { - Yap_Error_TYPE = OUT_OF_STACK_ERROR; - Yap_Error_Term = inp_clause; + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Term = inp_clause; } } YAPEnterCriticalSection(); @@ -3391,9 +3391,9 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) YAPLeaveCriticalSection(); ARG1 = inp_clause; ARG3 = src; - if (!Yap_ExpandPreAllocCodeSpace(Yap_Error_Size, NULL, TRUE)) { - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; - Yap_Error_Term = inp_clause; + if (!Yap_ExpandPreAllocCodeSpace(LOCAL_Error_Size, NULL, TRUE)) { + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_Error_Term = inp_clause; } YAPEnterCriticalSection(); src = ARG3; @@ -3412,9 +3412,9 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) ARG1 = inp_clause; ARG3 = src; YAPLeaveCriticalSection(); - if (!Yap_growheap(FALSE, Yap_Error_Size, NULL)) { - Yap_Error_TYPE = OUT_OF_HEAP_ERROR; - Yap_Error_Term = inp_clause; + if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) { + LOCAL_Error_TYPE = OUT_OF_HEAP_ERROR; + LOCAL_Error_Term = inp_clause; return NULL; } YAPEnterCriticalSection(); @@ -3426,9 +3426,9 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) ARG1 = inp_clause; ARG3 = src; YAPLeaveCriticalSection(); - if (!Yap_growtrail(Yap_TrailTop-(ADDR)TR, FALSE)) { - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; - Yap_Error_Term = inp_clause; + if (!Yap_growtrail(LOCAL_TrailTop-(ADDR)TR, FALSE)) { + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_Error_Term = inp_clause; return NULL; } YAPEnterCriticalSection(); @@ -3441,9 +3441,9 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) } my_clause = inp_clause; HB = H; - Yap_ErrorMessage = NULL; - Yap_Error_Size = 0; - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_ErrorMessage = NULL; + LOCAL_Error_Size = 0; + LOCAL_Error_TYPE = YAP_NO_ERROR; /* initialize variables for code generation */ cglobs.cint.CodeStart = cglobs.cint.cpc = NULL; @@ -3457,7 +3457,7 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) cglobs.cint.success_handler = 0L; if (ASP <= CellPtr (cglobs.cint.freep) + 256) { cglobs.vtable = NULL; - Yap_Error_Size = (256+maxvnum)*sizeof(CELL); + LOCAL_Error_Size = (256+maxvnum)*sizeof(CELL); save_machine_regs(); siglongjmp(cglobs.cint.CompilerBotch,3); } @@ -3481,9 +3481,9 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) cglobs.is_a_fact = FALSE; cglobs.hasdbrefs = FALSE; if (IsVarTerm(my_clause)) { - Yap_Error_TYPE = INSTANTIATION_ERROR; - Yap_Error_Term = my_clause; - Yap_ErrorMessage = "in compiling clause"; + LOCAL_Error_TYPE = INSTANTIATION_ERROR; + LOCAL_Error_Term = my_clause; + LOCAL_ErrorMessage = "in compiling clause"; return 0; } if (IsApplTerm(my_clause) && FunctorOfTerm(my_clause) == FunctorAssert) { @@ -3494,9 +3494,9 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) head = my_clause, body = MkAtomTerm(AtomTrue); } if (IsVarTerm(head) || IsPairTerm(head) || IsIntTerm(head) || IsFloatTerm(head) || IsRefTerm(head)) { - Yap_Error_TYPE = TYPE_ERROR_CALLABLE; - Yap_Error_Term = my_clause; - Yap_ErrorMessage = "clause should be atom or term"; + LOCAL_Error_TYPE = TYPE_ERROR_CALLABLE; + LOCAL_Error_Term = my_clause; + LOCAL_ErrorMessage = "clause should be atom or term"; return (0); } else { @@ -3544,10 +3544,10 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) cglobs.cint.cpc->nextInst = cglobs.cint.BlobsStart; cglobs.cint.BlobsStart = NULL; } - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return (0); #ifdef DEBUG - if (Yap_Option['g' - 96]) + if (GLOBAL_Option['g' - 96]) Yap_ShowCode(&cglobs.cint); #endif } else { @@ -3577,10 +3577,10 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) if (B != NULL) { HB = B->cp_h; } - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return (0); #ifdef DEBUG - if (Yap_Option['g' - 96]) + if (GLOBAL_Option['g' - 96]) Yap_ShowCode(&cglobs.cint); #endif /* phase 2: classify variables and optimize temporaries */ @@ -3596,7 +3596,7 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) /* eliminate superfluous pop's and unify_var's */ c_optimize(cglobs.cint.CodeStart); #ifdef DEBUG - if (Yap_Option['f' - 96]) + if (GLOBAL_Option['f' - 96]) Yap_ShowCode(&cglobs.cint); #endif @@ -3618,7 +3618,7 @@ Yap_cclause(volatile Term inp_clause, Int NOfArgs, Term mod, volatile Term src) #ifdef LOW_PROF if (ProfilerOn && Yap_OffLineProfiler) { - Yap_inform_profiler_of_clause(acode, ProfEnd, cglobs.cint.CurrentPred,0); + Yap_inform_profiler_of_clause(acode, LOCAL_ProfEnd, cglobs.cint.CurrentPred,0); } #endif /* LOW_PROF */ return(acode); diff --git a/C/computils.c b/C/computils.c index bfba8e5f7..71f1784eb 100755 --- a/C/computils.c +++ b/C/computils.c @@ -75,12 +75,7 @@ STATIC_PROTO (void ShowOp, (char *, struct PSEUDO *)); * afterwards */ -#ifdef DEBUG -char Yap_Option[20]; - -YP_FILE *Yap_logfile; -#endif typedef struct mem_blk { union { @@ -112,27 +107,27 @@ AllocCMem (UInt size, struct intermediates *cip) blksz = CMEM_BLK_SIZE; if (!cip->blks) { CACHE_REGS - if (Yap_CMemFirstBlock) { - p = Yap_CMemFirstBlock; - blksz = Yap_CMemFirstBlockSz; + if (LOCAL_CMemFirstBlock) { + p = LOCAL_CMemFirstBlock; + blksz = LOCAL_CMemFirstBlockSz; p->u.next = NULL; } else { if (blksz < FIRST_CMEM_BLK_SIZE) blksz = FIRST_CMEM_BLK_SIZE; p = (struct mem_blk *)Yap_AllocCodeSpace(blksz); if (!p) { - Yap_Error_Size = size; + LOCAL_Error_Size = size; save_machine_regs(); siglongjmp(cip->CompilerBotch, OUT_OF_HEAP_BOTCH); } - Yap_CMemFirstBlock = p; - Yap_CMemFirstBlockSz = blksz; + LOCAL_CMemFirstBlock = p; + LOCAL_CMemFirstBlockSz = blksz; } } else { p = (struct mem_blk *)Yap_AllocCodeSpace(blksz); if (!p) { CACHE_REGS - Yap_Error_Size = size; + LOCAL_Error_Size = size; save_machine_regs(); siglongjmp(cip->CompilerBotch, OUT_OF_HEAP_BOTCH); } @@ -153,7 +148,7 @@ AllocCMem (UInt size, struct intermediates *cip) cip->freep += size; if (ASP <= CellPtr (cip->freep) + 256) { CACHE_REGS - Yap_Error_Size = 256+((char *)cip->freep - (char *)H); + LOCAL_Error_Size = 256+((char *)cip->freep - (char *)H); save_machine_regs(); siglongjmp(cip->CompilerBotch, OUT_OF_STACK_BOTCH); } @@ -169,13 +164,13 @@ Yap_ReleaseCMem (struct intermediates *cip) struct mem_blk *p = cip->blks; while (p) { struct mem_blk *nextp = p->u.next; - if (p != Yap_CMemFirstBlock) + if (p != LOCAL_CMemFirstBlock) Yap_FreeCodeSpace((ADDR)p); p = nextp; } cip->blks = NULL; if (cip->label_offset && - cip->label_offset != Yap_LabelFirstArray) { + cip->label_offset != LOCAL_LabelFirstArray) { Yap_FreeCodeSpace((ADDR)cip->label_offset); } #endif diff --git a/C/corout.c b/C/corout.c index 88422528f..7210058d2 100644 --- a/C/corout.c +++ b/C/corout.c @@ -505,7 +505,7 @@ static Int p_coroutining( USES_REGS1 ) #if COROUTINING static Term ListOfWokenGoals( USES_REGS1 ) { - return Yap_ReadTimedVar(WokenGoals); + return Yap_ReadTimedVar(LOCAL_WokenGoals); } Term @@ -519,12 +519,12 @@ Yap_ListOfWokenGoals(void) { static Int p_awoken_goals( USES_REGS1 ) { #ifdef COROUTINING - Term WGs = Yap_ReadTimedVar(WokenGoals); + Term WGs = Yap_ReadTimedVar(LOCAL_WokenGoals); if (WGs == TermNil) { return(FALSE); } WGs = ListOfWokenGoals( PASS_REGS1 ); - Yap_UpdateTimedVar(WokenGoals, TermNil); + Yap_UpdateTimedVar(LOCAL_WokenGoals, TermNil); return(Yap_unify(ARG1,WGs)); #else return(FALSE); diff --git a/C/cut_c.c b/C/cut_c.c index 7de08c8c6..36e461cc5 100755 --- a/C/cut_c.c +++ b/C/cut_c.c @@ -6,14 +6,14 @@ void cut_c_initialize(void){ CACHE_REGS - Yap_REGS.CUT_C_TOP=(cut_c_str_ptr)Yap_LocalBase; + Yap_REGS.CUT_C_TOP=(cut_c_str_ptr)LOCAL_LocalBase; } /*Removes a choice_point from the stack*/ void cut_c_pop(void){ CACHE_REGS cut_c_str_ptr to_delete = NULL; - if (((CELL *)Yap_REGS.CUT_C_TOP) == ((CELL *)Yap_LocalBase)) + if (((CELL *)Yap_REGS.CUT_C_TOP) == ((CELL *)LOCAL_LocalBase)) { return; } diff --git a/C/dbase.c b/C/dbase.c index efa76d597..bb7895bdc 100755 --- a/C/dbase.c +++ b/C/dbase.c @@ -160,7 +160,6 @@ typedef struct db_globs { UInt sz; /* total size */ } dbglobs; -static dbglobs *s_dbg; #ifdef SUPPORT_HASH_TABLES typedef struct { @@ -249,7 +248,7 @@ STATIC_PROTO(DBProp find_int_key, (Int)); static UInt new_trail_size(void) { CACHE_REGS - UInt sz = (Yap_TrailTop-(ADDR)TR)/2; + UInt sz = (LOCAL_TrailTop-(ADDR)TR)/2; if (sz < K64) return K64; if (sz > M1) @@ -261,10 +260,10 @@ static int recover_from_record_error(int nargs) { CACHE_REGS - switch(Yap_Error_TYPE) { + switch(LOCAL_Error_TYPE) { case OUT_OF_STACK_ERROR: - if (!Yap_gcl(Yap_Error_Size, nargs, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + if (!Yap_gcl(LOCAL_Error_Size, nargs, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } goto recover_record; @@ -275,24 +274,24 @@ recover_from_record_error(int nargs) } goto recover_record; case OUT_OF_HEAP_ERROR: - if (!Yap_growheap(FALSE, Yap_Error_Size, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, Yap_Error_Term, Yap_ErrorMessage); + if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) { + Yap_Error(OUT_OF_HEAP_ERROR, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } goto recover_record; case OUT_OF_AUXSPACE_ERROR: - if (!Yap_ExpandPreAllocCodeSpace(Yap_Error_Size, NULL, TRUE)) { - Yap_Error(OUT_OF_AUXSPACE_ERROR, Yap_Error_Term, Yap_ErrorMessage); + if (!Yap_ExpandPreAllocCodeSpace(LOCAL_Error_Size, NULL, TRUE)) { + Yap_Error(OUT_OF_AUXSPACE_ERROR, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } goto recover_record; default: - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } recover_record: - Yap_Error_Size = 0; - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_Size = 0; + LOCAL_Error_TYPE = YAP_NO_ERROR; return TRUE; } @@ -368,7 +367,7 @@ static Int cmpclls(CELL *a,CELL *b,Int n) #if !THREADS int Yap_DBTrailOverflow() { - return((CELL *)s_dbg->lr > (CELL *)s_dbg->tofref - 2048); + return((CELL *)LOCAL_s_dbg->lr > (CELL *)LOCAL_s_dbg->tofref - 2048); } #endif @@ -906,7 +905,7 @@ static CELL *MkDBTerm(register CELL *pt0, register CELL *pt0_end, the variable, the constraint in some cannonical form, what type of constraint, and a list pointer */ t[0] = (CELL)ptd0; - t[1] = attas[ExtFromCell(ptd0)].to_term_op(ptd0); + t[1] = GLOBAL_attas[ExtFromCell(ptd0)].to_term_op(ptd0); t[2] = MkIntegerTerm(ExtFromCell(ptd0)); t[3] = ConstraintsTerm; ConstraintsTerm = Yap_MkApplTerm(FunctorClist, 4, t); @@ -975,8 +974,8 @@ static CELL *MkDBTerm(register CELL *pt0, register CELL *pt0_end, return CodeMax; error: - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; - Yap_Error_Size = 1024+((char *)AuxSp-(char *)CodeMaxBase); + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_Error_Size = 1024+((char *)AuxSp-(char *)CodeMaxBase); *vars_foundp = vars_found; #ifdef RATIONAL_TREES while (to_visit > to_visit_base) { @@ -994,7 +993,7 @@ static CELL *MkDBTerm(register CELL *pt0, register CELL *pt0_end, return NULL; error2: - Yap_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; *vars_foundp = vars_found; #ifdef RATIONAL_TREES while (to_visit > to_visit_base) { @@ -1012,7 +1011,7 @@ static CELL *MkDBTerm(register CELL *pt0, register CELL *pt0_end, return NULL; error_tr_overflow: - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; *vars_foundp = vars_found; #ifdef RATIONAL_TREES while (to_visit > to_visit_base) { @@ -1078,9 +1077,9 @@ sf_include(SFKeep *sfp, struct db_globs *dbg) *StoPoint++ = tvalue; j += 2; } else { - Yap_Error_TYPE = TYPE_ERROR_DBTERM; - Yap_Error_Term = d0; - Yap_ErrorMessage = "wrong term in SF"; + LOCAL_Error_TYPE = TYPE_ERROR_DBTERM; + LOCAL_Error_Term = d0; + LOCAL_ErrorMessage = "wrong term in SF"; return(NULL); } } @@ -1208,10 +1207,10 @@ static DBRef generate_dberror_msg(int errnumb, UInt sz, char *msg) { CACHE_REGS - Yap_Error_Size = sz; - Yap_Error_TYPE = errnumb; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = msg; + LOCAL_Error_Size = sz; + LOCAL_Error_TYPE = errnumb; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = msg; return NULL; } @@ -1365,11 +1364,11 @@ CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat, UInt extra_size, struc SMALLUNSGN flag; int NOfLinks = 0; /* place DBRefs in ConsultStack */ - DBRef *TmpRefBase = (DBRef *)Yap_TrailTop; + DBRef *TmpRefBase = (DBRef *)LOCAL_TrailTop; CELL *CodeAbs; /* how much code did we find */ int vars_found = FALSE; - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; if (p == NULL) { if (IsVarTerm(Tm)) { @@ -1420,15 +1419,15 @@ CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat, UInt extra_size, struc ppt0 = &(pp0->DBT); } if ((ADDR)ppt0 >= (ADDR)AuxSp-1024) { - Yap_Error_Size = (UInt)(extra_size+sizeof(ppt0)); - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_Error_Size = (UInt)(extra_size+sizeof(ppt0)); + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; Yap_ReleasePreAllocCodeSpace((ADDR)pp0); return NULL; } ntp0 = ppt0->Contents; - if ((ADDR)TR >= Yap_TrailTop-1024) { - Yap_Error_Size = 0; - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; + if ((ADDR)TR >= LOCAL_TrailTop-1024) { + LOCAL_Error_Size = 0; + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; Yap_ReleasePreAllocCodeSpace((ADDR)pp0); return NULL; } @@ -1501,7 +1500,7 @@ CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat, UInt extra_size, struc } } CodeAbs = (CELL *)((CELL)ntp-(CELL)ntp0); - if (Yap_Error_TYPE) { + if (LOCAL_Error_TYPE) { Yap_ReleasePreAllocCodeSpace((ADDR)pp0); return NULL; /* Error Situation */ } @@ -1517,8 +1516,8 @@ CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat, UInt extra_size, struc flag = DBComplex; CodeAbs += CellPtr(dbg->lr) - CellPtr(dbg->LinkAr); if ((CELL *)((char *)ntp0+(CELL)CodeAbs) > AuxSp) { - Yap_Error_Size = (UInt)DBLength(CodeAbs); - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_Error_Size = (UInt)DBLength(CodeAbs); + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; Yap_ReleasePreAllocCodeSpace((ADDR)pp0); return NULL; } @@ -1536,8 +1535,8 @@ CreateDBStruct(Term Tm, DBProp p, int InFlag, int *pstat, UInt extra_size, struc if (dbg->tofref != TmpRefBase) { CodeAbs += (TmpRefBase - dbg->tofref) + 1; if ((CELL *)((char *)ntp0+(CELL)CodeAbs) > AuxSp) { - Yap_Error_Size = (UInt)DBLength(CodeAbs); - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_Error_Size = (UInt)DBLength(CodeAbs); + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; Yap_ReleasePreAllocCodeSpace((ADDR)pp0); return NULL; } @@ -1647,7 +1646,7 @@ record(int Flag, Term key, Term t_data, Term t_code USES_REGS) int needs_vars; struct db_globs dbg; - s_dbg = &dbg; + LOCAL_s_dbg = &dbg; dbg.found_one = NULL; #ifdef SFUNC FathersPlace = NIL; @@ -1724,7 +1723,7 @@ record_at(int Flag, DBRef r0, Term t_data, Term t_code USES_REGS) int needs_vars; struct db_globs dbg; - s_dbg = &dbg; + LOCAL_s_dbg = &dbg; #ifdef SFUNC FathersPlace = NIL; #endif @@ -1799,6 +1798,7 @@ record_at(int Flag, DBRef r0, Term t_data, Term t_code USES_REGS) static LogUpdClause * new_lu_db_entry(Term t, PredEntry *pe) { + CACHE_REGS DBTerm *x; LogUpdClause *cl; yamop *ipc; @@ -1811,7 +1811,7 @@ new_lu_db_entry(Term t, PredEntry *pe) if (!(pe->PredFlags & ThreadLocalPredFlag)) d_flag |= InQueue; #endif - s_dbg = &dbg; + LOCAL_s_dbg = &dbg; ipc = NEXTOP(((LogUpdClause *)NULL)->ClCode,e); if ((x = (DBTerm *)CreateDBStruct(t, NULL, d_flag, &needs_vars, (UInt)ipc, &dbg)) == NULL) { return NULL; /* crash */ @@ -1859,9 +1859,9 @@ Yap_new_ludbe(Term t, PredEntry *pe, UInt nargs) CACHE_REGS LogUpdClause *x; - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; while ((x = new_lu_db_entry(t, pe)) == NULL) { - if (Yap_Error_TYPE == YAP_NO_ERROR) { + if (LOCAL_Error_TYPE == YAP_NO_ERROR) { break; } else { XREGS[nargs+1] = t; @@ -1951,7 +1951,7 @@ p_rcda( USES_REGS1 ) if (!IsVarTerm(Deref(ARG3))) return (FALSE); pe = find_lu_entry(t1); - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; restart_record: if (pe) { LogUpdClause *cl; @@ -1973,7 +1973,7 @@ p_rcda( USES_REGS1 ) } else { TRef = MkDBRefTerm(record(MkFirst, t1, Deref(ARG2), Unsigned(0) PASS_REGS)); } - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (recover_from_record_error(3)) { goto restart_record; } else { @@ -1993,11 +1993,11 @@ p_rcdap( USES_REGS1 ) if (!IsVarTerm(Deref(ARG3))) return FALSE; - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; restart_record: TRef = MkDBRefTerm(record(MkFirst | MkCode, t1, t2, Unsigned(0) PASS_REGS)); - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (recover_from_record_error(3)) { t1 = Deref(ARG1); t2 = Deref(ARG2); @@ -2027,7 +2027,7 @@ p_rcda_at( USES_REGS1 ) Yap_Error(TYPE_ERROR_DBREF, t1, "recorda_at/3"); return FALSE; } - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; restart_record: dbr = DBRefOfTerm(t1); if (dbr->Flags & ErasedMask) { @@ -2039,7 +2039,7 @@ p_rcda_at( USES_REGS1 ) } else { TRef = MkDBRefTerm(record_at(MkFirst, DBRefOfTerm(t1), t2, Unsigned(0) PASS_REGS)); } - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (recover_from_record_error(3)) { t1 = Deref(ARG1); t2 = Deref(ARG2); @@ -2061,7 +2061,7 @@ p_rcdz( USES_REGS1 ) if (!IsVarTerm(Deref(ARG3))) return (FALSE); pe = find_lu_entry(t1); - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; restart_record: if (pe) { LogUpdClause *cl; @@ -2083,7 +2083,7 @@ p_rcdz( USES_REGS1 ) } else { TRef = MkDBRefTerm(record(MkLast, t1, t2, Unsigned(0) PASS_REGS)); } - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (recover_from_record_error(3)) { t1 = Deref(ARG1); t2 = Deref(ARG2); @@ -2105,14 +2105,14 @@ Yap_Recordz(Atom at, Term t2) PredEntry *pe; pe = find_lu_entry(MkAtomTerm(at)); - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; restart_record: if (pe) { record_lu(pe, t2, MkLast); } else { record(MkLast, MkAtomTerm(at), t2, Unsigned(0) PASS_REGS); } - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { ARG1 = t2; if (recover_from_record_error(1)) { t2 = ARG1; @@ -2132,10 +2132,10 @@ p_rcdzp( USES_REGS1 ) if (!IsVarTerm(Deref(ARG3))) return (FALSE); - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; restart_record: TRef = MkDBRefTerm(record(MkLast | MkCode, t1, t2, Unsigned(0) PASS_REGS)); - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (recover_from_record_error(3)) { t1 = Deref(ARG1); t2 = Deref(ARG2); @@ -2165,7 +2165,7 @@ p_rcdz_at( USES_REGS1 ) Yap_Error(TYPE_ERROR_DBREF, t1, "recordz_at/3"); return FALSE; } - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; restart_record: dbr = DBRefOfTerm(t1); if (dbr->Flags & ErasedMask) { @@ -2177,7 +2177,7 @@ p_rcdz_at( USES_REGS1 ) } else { TRef = MkDBRefTerm(record_at(MkLast, dbr, t2, Unsigned(0) PASS_REGS)); } - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (recover_from_record_error(3)) { t1 = Deref(ARG1); t2 = Deref(ARG2); @@ -2202,13 +2202,13 @@ p_rcdstatp( USES_REGS1 ) if (IsVarTerm(t3) || !IsIntTerm(t3)) return (FALSE); mk_first = ((IntOfTerm(t3) % 4) == 2); - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; restart_record: if (mk_first) TRef = MkDBRefTerm(record(MkFirst | MkCode, t1, t2, MkIntTerm(0) PASS_REGS)); else TRef = MkDBRefTerm(record(MkLast | MkCode, t1, t2, MkIntTerm(0) PASS_REGS)); - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (recover_from_record_error(4)) { t1 = Deref(ARG1); t2 = Deref(ARG2); @@ -2231,11 +2231,11 @@ p_drcdap( USES_REGS1 ) return (FALSE); if (IsVarTerm(t4) || !IsIntegerTerm(t4)) return (FALSE); - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; restart_record: TRef = MkDBRefTerm(record(MkFirst | MkCode | WithRef, t1, t2, t4 PASS_REGS)); - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (recover_from_record_error(4)) { t1 = Deref(ARG1); t2 = Deref(ARG2); @@ -2259,10 +2259,10 @@ p_drcdzp( USES_REGS1 ) if (IsVarTerm(t4) || !IsIntegerTerm(t4)) return (FALSE); restart_record: - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; TRef = MkDBRefTerm(record(MkLast | MkCode | WithRef, t1, t2, t4 PASS_REGS)); - if (Yap_Error_TYPE != YAP_NO_ERROR) { + if (LOCAL_Error_TYPE != YAP_NO_ERROR) { if (recover_from_record_error(4)) { t1 = Deref(ARG1); t2 = Deref(ARG2); @@ -2358,7 +2358,7 @@ copy_attachments(CELL *ts USES_REGS) while (TRUE) { /* store away in case there is an overflow */ - if (attas[IntegerOfTerm(ts[2])].term_to_op(ts[1], ts[0] PASS_REGS) == FALSE) { + if (GLOBAL_attas[IntegerOfTerm(ts[2])].term_to_op(ts[1], ts[0] PASS_REGS) == FALSE) { /* oops, we did not have enough space to copy the elements */ /* reset queue of woken up goals */ TR = tr0; @@ -2466,13 +2466,13 @@ GetDBTerm(DBTerm *DBSP USES_REGS) } pt = CellPtr(DBSP->Contents); if (H+NOf > ASP-CalculateStackGap()/sizeof(CELL)) { - if (Yap_PrologMode & InErrorMode) { + if (LOCAL_PrologMode & InErrorMode) { if (H+NOf > ASP) - fprintf(Yap_stderr, "\n\n [ FATAL ERROR: No Stack for Error Handling ]\n"); + fprintf(GLOBAL_stderr, "\n\n [ FATAL ERROR: No Stack for Error Handling ]\n"); Yap_exit( 1); } else { - Yap_Error_TYPE = OUT_OF_STACK_ERROR; - Yap_Error_Size = NOf*sizeof(CELL); + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Size = NOf*sizeof(CELL); return (Term)0; } } @@ -2487,8 +2487,8 @@ GetDBTerm(DBTerm *DBSP USES_REGS) if (DBSP->ag.attachments != 0L) { if (!copy_attachments((CELL *)AdjustIDBPtr(DBSP->ag.attachments,(CELL)HOld-(CELL)(DBSP->Contents)) PASS_REGS)) { H = HOld; - Yap_Error_TYPE = OUT_OF_ATTVARS_ERROR; - Yap_Error_Size = 0; + LOCAL_Error_TYPE = OUT_OF_ATTVARS_ERROR; + LOCAL_Error_Size = 0; return (Term)0; } } @@ -2549,9 +2549,9 @@ resize_int_keys(UInt new_size) { new = (Prop *)Yap_AllocCodeSpace(sizeof(Prop)*new_size); if (new == NULL) { YAPLeaveCriticalSection(); - Yap_Error_TYPE = OUT_OF_HEAP_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "could not allocate space"; + LOCAL_Error_TYPE = OUT_OF_HEAP_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "could not allocate space"; return FALSE; } Yap_LUClauseSpace += sizeof(Prop)*new_size; @@ -2642,9 +2642,9 @@ new_lu_int_key(Int key) init_int_lu_keys(); if (INT_LU_KEYS == NULL) { CACHE_REGS - Yap_Error_TYPE = OUT_OF_HEAP_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "could not allocate space"; + LOCAL_Error_TYPE = OUT_OF_HEAP_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "could not allocate space"; return NULL; } } @@ -2765,9 +2765,9 @@ FetchIntDBPropFromKey(Int key, int flag, int new, char *error_mssg) init_int_keys(); if (INT_KEYS == NULL) { CACHE_REGS - Yap_Error_TYPE = OUT_OF_HEAP_ERROR; - Yap_Error_Term = TermNil; - Yap_ErrorMessage = "could not allocate space"; + LOCAL_Error_TYPE = OUT_OF_HEAP_ERROR; + LOCAL_Error_Term = TermNil; + LOCAL_ErrorMessage = "could not allocate space"; return NULL; } } @@ -3182,20 +3182,20 @@ i_recorded(DBProp AtProp, Term t3 USES_REGS) /* make sure the garbage collector sees what we want it to see! */ EXTRA_CBACK_ARG(3,1) = (CELL)ref; /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 3, ENV, CP)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 3, ENV, CP)) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; twork = Deref(ARG2); t3 = Deref(ARG3); } @@ -3254,16 +3254,16 @@ i_recorded(DBProp AtProp, Term t3 USES_REGS) EXTRA_CBACK_ARG(3,2) = MkIntegerTerm(((Int)mask)); EXTRA_CBACK_ARG(3,3) = MkIntegerTerm(((Int)key)); /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 3, ENV, CP)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 3, ENV, CP)) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -3350,20 +3350,20 @@ c_recorded(int flags USES_REGS) /* make sure the garbage collector sees what we want it to see! */ EXTRA_CBACK_ARG(3,1) = (CELL)ref; /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 3, ENV, CP)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 3, ENV, CP)) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; PreviousHeap = H; } Yap_unify(ARG2, TermDB); @@ -3393,20 +3393,20 @@ c_recorded(int flags USES_REGS) /* make sure the garbage collector sees what we want it to see! */ EXTRA_CBACK_ARG(3,1) = (CELL)ref; /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 3, ENV, CP)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 3, ENV, CP)) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; PreviousHeap = H; } if (Yap_unify(ARG2, TermDB)) @@ -3530,16 +3530,16 @@ p_recorded( USES_REGS1 ) Term TermDB; while ((TermDB = GetDBTermFromDBEntry(ref PASS_REGS)) == (CELL)0) { /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 3, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 3, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -3677,16 +3677,16 @@ p_first_instance( USES_REGS1 ) UNLOCK(ref->lock); while ((TermDB = GetDBTermFromDBEntry(ref PASS_REGS)) == (CELL)0) { /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 3, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 3, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -4197,7 +4197,7 @@ MyEraseClause(DynamicClause *clau USES_REGS) Yap_FreeCodeSpace((char *)clau); #ifdef DEBUG if (ref->NOfRefsTo) - fprintf(Yap_stderr, "Error: references to dynamic clause\n"); + fprintf(GLOBAL_stderr, "Error: references to dynamic clause\n"); #endif RemoveDBEntry(ref PASS_REGS); } @@ -4622,16 +4622,16 @@ static_instance(StaticClause *cl USES_REGS) while ((TermDB = GetDBTerm(cl->usc.ClSource PASS_REGS)) == 0L) { /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 2, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -4735,17 +4735,17 @@ p_instance( USES_REGS1 ) Term TermDB; while ((TermDB = GetDBTerm(cl->ClSource PASS_REGS)) == 0L) { /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); UNLOCK(ap->PELock); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 2, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); UNLOCK(ap->PELock); return FALSE; } @@ -4758,16 +4758,16 @@ p_instance( USES_REGS1 ) Term TermDB; while ((TermDB = GetDBTermFromDBEntry(dbr PASS_REGS)) == 0L) { /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 2, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -4790,16 +4790,16 @@ Yap_LUInstance(LogUpdClause *cl, UInt arity) CACHE_REGS while ((TermDB = GetDBTerm(cl->ClSource PASS_REGS)) == 0L) { /* oops, we are in trouble, not enough stack space */ - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, arity, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, arity, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } } @@ -5048,11 +5048,11 @@ StoreTermInDB(Term t, int nargs USES_REGS) int needs_vars; struct db_globs dbg; - s_dbg = &dbg; - Yap_Error_Size = 0; + LOCAL_s_dbg = &dbg; + LOCAL_Error_Size = 0; while ((x = (DBTerm *)CreateDBStruct(t, (DBProp)NULL, InQueue, &needs_vars, 0, &dbg)) == NULL) { - if (Yap_Error_TYPE == YAP_NO_ERROR) { + if (LOCAL_Error_TYPE == YAP_NO_ERROR) { break; } else if (nargs == -1) { return NULL; @@ -5076,11 +5076,12 @@ Yap_StoreTermInDB(Term t, int nargs) { DBTerm * Yap_StoreTermInDBPlusExtraSpace(Term t, UInt extra_size, UInt *sz) { + CACHE_REGS int needs_vars; struct db_globs dbg; DBTerm *o; - s_dbg = &dbg; + LOCAL_s_dbg = &dbg; o = (DBTerm *)CreateDBStruct(t, (DBProp)NULL, InQueue, &needs_vars, extra_size, &dbg); *sz = dbg.sz; @@ -5249,16 +5250,16 @@ p_dequeue( USES_REGS1 ) father_key->FirstInQueue = cur_instance->next; WRITE_UNLOCK(father_key->QRWLock); while ((TDB = GetDBTerm(cur_instance->DBT PASS_REGS)) == 0L) { - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 2, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -5293,16 +5294,16 @@ p_dequeue_unlocked( USES_REGS1 ) while (cur_instance) { Term TDB; while ((TDB = GetDBTerm(cur_instance->DBT PASS_REGS)) == 0L) { - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 2, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -5350,16 +5351,16 @@ p_peek_queue( USES_REGS1 ) while (cur_instance) { Term TDB; while ((TDB = GetDBTerm(cur_instance->DBT PASS_REGS)) == 0L) { - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 2, ENV, gc_P(P,CP))) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } diff --git a/C/dlmalloc.c b/C/dlmalloc.c index 78e189d8c..9ec17147b 100755 --- a/C/dlmalloc.c +++ b/C/dlmalloc.c @@ -12,7 +12,7 @@ static struct malloc_chunk * ChunkPtrAdjust (struct malloc_chunk *ptr) { - return (struct malloc_chunk *) ((char *) (ptr) + HDiff); + return (struct malloc_chunk *) ((char *) (ptr) + LOCAL_HDiff); } @@ -212,8 +212,8 @@ yapsbrk(long size) UNLOCK(HeapTopLock); Yap_signal(YAP_CDOVF_SIGNAL); } else { - if (size > Yap_SizeOfOverflow) - Yap_SizeOfOverflow = size; + if (size > GLOBAL_SizeOfOverflow) + GLOBAL_SizeOfOverflow = size; /* big allocations, the caller must handle the problem */ UNLOCK(HeapUsedLock); UNLOCK(HeapTopLock); diff --git a/C/errors.c b/C/errors.c index 4d90de960..a00607c22 100755 --- a/C/errors.c +++ b/C/errors.c @@ -38,7 +38,7 @@ STATIC_PROTO (void detect_bug_location, (yamop *,find_pred_type,char *, int)); #define ONHEAP(ptr) (CellPtr(ptr) >= CellPtr(Yap_HeapBase) && CellPtr(ptr) < CellPtr(HeapTop)) -#define ONLOCAL(ptr) (CellPtr(ptr) > CellPtr(H) && CellPtr(ptr) < CellPtr(Yap_LocalBase)) +#define ONLOCAL(ptr) (CellPtr(ptr) > CellPtr(H) && CellPtr(ptr) < CellPtr(LOCAL_LocalBase)) static int hidden (Atom at) @@ -118,15 +118,15 @@ DumpActiveGoals ( USES_REGS1 ) fprintf(stderr,"Active ancestors:\n"); if (pe->ModuleOfPred) mod = pe->ModuleOfPred; Yap_DebugPlWrite (mod); - Yap_DebugPutc (Yap_c_error_stream,':'); + Yap_DebugPutc (LOCAL_c_error_stream,':'); if (pe->ArityOfPE == 0) { Yap_DebugPlWrite (MkAtomTerm ((Atom)f)); } else { Yap_DebugPlWrite (MkAtomTerm (NameOfFunctor (f))); - Yap_DebugPutc (Yap_c_error_stream,'/'); + Yap_DebugPutc (LOCAL_c_error_stream,'/'); Yap_DebugPlWrite (MkIntTerm (ArityOfFunctor (f))); } - Yap_DebugPutc (Yap_c_error_stream,'\n'); + Yap_DebugPutc (LOCAL_c_error_stream,'\n'); } else { UNLOCK(pe->PELock); } @@ -152,21 +152,21 @@ DumpActiveGoals ( USES_REGS1 ) mod = pe->ModuleOfPred; else mod = TermProlog; Yap_DebugPlWrite (mod); - Yap_DebugPutc (Yap_c_error_stream,':'); + Yap_DebugPutc (LOCAL_c_error_stream,':'); if (pe->ArityOfPE == 0) { Yap_DebugPlWrite (MkAtomTerm (NameOfFunctor(f))); } else { Int i = 0, arity = pe->ArityOfPE; Term *args = &(b_ptr->cp_a1); Yap_DebugPlWrite (MkAtomTerm (NameOfFunctor (f))); - Yap_DebugPutc (Yap_c_error_stream,'('); + Yap_DebugPutc (LOCAL_c_error_stream,'('); for (i= 0; i < arity; i++) { - if (i > 0) Yap_DebugPutc (Yap_c_error_stream,','); + if (i > 0) Yap_DebugPutc (LOCAL_c_error_stream,','); Yap_DebugPlWrite(args[i]); } - Yap_DebugPutc (Yap_c_error_stream,')'); + Yap_DebugPutc (LOCAL_c_error_stream,')'); } - Yap_DebugPutc (Yap_c_error_stream,'\n'); + Yap_DebugPutc (LOCAL_c_error_stream,'\n'); } UNLOCK(pe->PELock); b_ptr = b_ptr->cp_b; @@ -264,14 +264,14 @@ dump_stack( USES_REGS1 ) return; #if DEBUG fprintf(stderr,"%% YAP regs: P=%p, CP=%p, ASP=%p, H=%p, TR=%p, HeapTop=%p\n",P,CP,ASP,H,TR,HeapTop); - fprintf(stderr,"%% YAP mode: %ux\n",(unsigned int)Yap_PrologMode); - if (Yap_ErrorMessage) - fprintf(stderr,"%% YAP_ErrorMessage: %s\n",Yap_ErrorMessage); + fprintf(stderr,"%% YAP mode: %ux\n",(unsigned int)LOCAL_PrologMode); + if (LOCAL_ErrorMessage) + fprintf(stderr,"%% LOCAL_ErrorMessage: %s\n",LOCAL_ErrorMessage); #endif if (H > ASP || H > LCL0) { fprintf(stderr,"%% YAP ERROR: Global Collided against Local (%p--%p)\n",H,ASP); - } else if (HeapTop > (ADDR)Yap_GlobalBase) { - fprintf(stderr,"%% YAP ERROR: Code Space Collided against Global (%p--%p)\n", HeapTop, Yap_GlobalBase); + } else if (HeapTop > (ADDR)LOCAL_GlobalBase) { + fprintf(stderr,"%% YAP ERROR: Code Space Collided against Global (%p--%p)\n", HeapTop, LOCAL_GlobalBase); } else { #if !USE_SYSTEM_MALLOC fprintf (stderr,"%ldKB of Code Space (%p--%p)\n",(long int)((CELL)HeapTop-(CELL)Yap_HeapBase)/1024,Yap_HeapBase,HeapTop); @@ -292,8 +292,8 @@ dump_stack( USES_REGS1 ) fprintf (stderr,"%% Continuation: %s\n",(char *)H); fprintf (stderr,"%% %luKB of Global Stack (%p--%p)\n",(unsigned long int)(sizeof(CELL)*(H-H0))/1024,H0,H); fprintf (stderr,"%% %luKB of Local Stack (%p--%p)\n",(unsigned long int)(sizeof(CELL)*(LCL0-ASP))/1024,ASP,LCL0); - fprintf (stderr,"%% %luKB of Trail (%p--%p)\n",(unsigned long int)((ADDR)TR-Yap_TrailBase)/1024,Yap_TrailBase,TR); - fprintf (stderr,"%% Performed %ld garbage collections\n", (unsigned long int)GcCalls); + fprintf (stderr,"%% %luKB of Trail (%p--%p)\n",(unsigned long int)((ADDR)TR-LOCAL_TrailBase)/1024,LOCAL_TrailBase,TR); + fprintf (stderr,"%% Performed %ld garbage collections\n", (unsigned long int)LOCAL_GcCalls); #if LOW_LEVEL_TRACER { extern long long vsc_count; @@ -352,7 +352,7 @@ static void error_exit_yap (int value) { CACHE_REGS - if (!(Yap_PrologMode & BootMode)) { + if (!(LOCAL_PrologMode & BootMode)) { dump_stack( PASS_REGS1 ); #if DEBUG #endif @@ -391,14 +391,14 @@ Yap_Error(yap_error_number type, Term where, char *format,...) char *tp = tmpbuf; int psize = YAP_BUF_SIZE; - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; if (where == 0L) where = TermNil; #if DEBUG_STRICT - if (Yap_heap_regs && !(Yap_PrologMode & BootMode)) - fprintf(stderr,"***** Processing Error %d (%lx,%x) %s***\n", type, (unsigned long int)ActiveSignals,Yap_PrologMode,format); + if (Yap_heap_regs && !(LOCAL_PrologMode & BootMode)) + fprintf(stderr,"***** Processing Error %d (%lx,%x) %s***\n", type, (unsigned long int)LOCAL_ActiveSignals,LOCAL_PrologMode,format); else - fprintf(stderr,"***** Processing Error %d (%x) %s***\n", type,Yap_PrologMode,format); + fprintf(stderr,"***** Processing Error %d (%x) %s***\n", type,LOCAL_PrologMode,format); #endif if (type == INTERRUPT_ERROR) { fprintf(stderr,"%% YAP exiting: cannot handle signal %d\n", @@ -406,7 +406,7 @@ Yap_Error(yap_error_number type, Term where, char *format,...) Yap_exit(1); } /* disallow recursive error handling */ - if (Yap_PrologMode & InErrorMode) { + if (LOCAL_PrologMode & InErrorMode) { /* error within error */ va_start (ap, format); /* now build the error string */ @@ -444,7 +444,7 @@ Yap_Error(yap_error_number type, Term where, char *format,...) } else { tmpbuf[0] = '\0'; } - if (Yap_PrologMode == UserCCallMode) { + if (LOCAL_PrologMode == UserCCallMode) { fprintf(stderr,"%%\n%%\n"); fprintf(stderr,"%% YAP OOOPS in USER C-CODE: %s.\n",tmpbuf); fprintf(stderr,"%%\n%%\n"); @@ -458,12 +458,12 @@ Yap_Error(yap_error_number type, Term where, char *format,...) if (P == (yamop *)(FAILCODE)) return P; /* PURE_ABORT may not have set where correctly, BootMode may not have the data terms ready */ - if (type == PURE_ABORT || Yap_PrologMode & BootMode) { + if (type == PURE_ABORT || LOCAL_PrologMode & BootMode) { where = TermNil; - Yap_PrologMode &= ~AbortMode; - Yap_PrologMode |= InErrorMode; + LOCAL_PrologMode &= ~AbortMode; + LOCAL_PrologMode |= InErrorMode; /* make sure failure will be seen at next port */ - if (Yap_PrologMode & AsyncIntMode) + if (LOCAL_PrologMode & AsyncIntMode) Yap_signal(YAP_FAIL_SIGNAL); P = FAILCODE; } else { @@ -474,8 +474,8 @@ Yap_Error(yap_error_number type, Term where, char *format,...) where = Deref(where); } /* Exit Abort Mode, if we were there */ - Yap_PrologMode &= ~AbortMode; - Yap_PrologMode |= InErrorMode; + LOCAL_PrologMode &= ~AbortMode; + LOCAL_PrologMode |= InErrorMode; if (!(where = Yap_CopyTerm(where))) { where = TermNil; } @@ -493,7 +493,7 @@ Yap_Error(yap_error_number type, Term where, char *format,...) else tmpbuf[0] = '\0'; va_end (ap); - if (Yap_PrologMode & BootMode) { + if (LOCAL_PrologMode & BootMode) { /* crash in flames! */ fprintf(stderr,"%% YAP Fatal Error: %s exiting....\n",tmpbuf); error_exit_yap (1); @@ -506,7 +506,7 @@ Yap_Error(yap_error_number type, Term where, char *format,...) { fprintf(stderr,"%% Internal YAP Error: %s exiting....\n",tmpbuf); serious = TRUE; - if (Yap_PrologMode & BootMode) { + if (LOCAL_PrologMode & BootMode) { fprintf(stderr,"%% YAP crashed while booting %s\n",tmpbuf); } else { detect_bug_location(P, FIND_PRED_FROM_ANYWHERE, tmpbuf, YAP_BUF_SIZE); @@ -530,30 +530,30 @@ Yap_Error(yap_error_number type, Term where, char *format,...) break; case CALL_COUNTER_UNDERFLOW: /* Do a long jump */ - ReductionsCounterOn = FALSE; - PredEntriesCounterOn = FALSE; - RetriesCounterOn = FALSE; + LOCAL_ReductionsCounterOn = FALSE; + LOCAL_PredEntriesCounterOn = FALSE; + LOCAL_RetriesCounterOn = FALSE; Yap_JumpToEnv(MkAtomTerm(AtomCallCounter)); P = (yamop *)FAILCODE; - Yap_PrologMode &= ~InErrorMode; + LOCAL_PrologMode &= ~InErrorMode; return(P); case PRED_ENTRY_COUNTER_UNDERFLOW: /* Do a long jump */ - ReductionsCounterOn = FALSE; - PredEntriesCounterOn = FALSE; - RetriesCounterOn = FALSE; + LOCAL_ReductionsCounterOn = FALSE; + LOCAL_PredEntriesCounterOn = FALSE; + LOCAL_RetriesCounterOn = FALSE; Yap_JumpToEnv(MkAtomTerm(AtomCallAndRetryCounter)); P = (yamop *)FAILCODE; - Yap_PrologMode &= ~InErrorMode; + LOCAL_PrologMode &= ~InErrorMode; return(P); case RETRY_COUNTER_UNDERFLOW: /* Do a long jump */ - ReductionsCounterOn = FALSE; - PredEntriesCounterOn = FALSE; - RetriesCounterOn = FALSE; + LOCAL_ReductionsCounterOn = FALSE; + LOCAL_PredEntriesCounterOn = FALSE; + LOCAL_RetriesCounterOn = FALSE; Yap_JumpToEnv(MkAtomTerm(AtomRetryCounter)); P = (yamop *)FAILCODE; - Yap_PrologMode &= ~InErrorMode; + LOCAL_PrologMode &= ~InErrorMode; return(P); case CONSISTENCY_ERROR: { @@ -1831,13 +1831,13 @@ Yap_Error(yap_error_number type, Term where, char *format,...) if (type != PURE_ABORT) { /* This is used by some complex procedures to detect there was an error */ if (IsAtomTerm(nt[0])) { - strncpy(Yap_ErrorSay, RepAtom(AtomOfTerm(nt[0]))->StrOfAE, MAX_ERROR_MSG_SIZ\ + strncpy(LOCAL_ErrorSay, RepAtom(AtomOfTerm(nt[0]))->StrOfAE, MAX_ERROR_MSG_SIZ\ E); - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_ErrorMessage = LOCAL_ErrorSay; } else { - strncpy(Yap_ErrorSay, RepAtom(NameOfFunctor(FunctorOfTerm(nt[0])))->StrOfAE,\ + strncpy(LOCAL_ErrorSay, RepAtom(NameOfFunctor(FunctorOfTerm(nt[0])))->StrOfAE,\ MAX_ERROR_MSG_SIZE); - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_ErrorMessage = LOCAL_ErrorSay; } } switch (type) { @@ -1852,35 +1852,35 @@ E); if ((stack_dump = Yap_all_calls()) == 0L) { stack_dump = TermNil; - Yap_Error_Size = 0L; + LOCAL_Error_Size = 0L; } nt[1] = MkPairTerm(MkAtomTerm(Yap_LookupAtom(tmpbuf)), stack_dump); } } if (serious) { /* disable active signals at this point */ - ActiveSignals = 0; + LOCAL_ActiveSignals = 0; CreepFlag = CalculateStackGap(); - Yap_PrologMode &= ~InErrorMode; - LOCK(SignalLock); + LOCAL_PrologMode &= ~InErrorMode; + LOCK(LOCAL_SignalLock); /* we might be in the middle of a critical region */ - if (Yap_InterruptsDisabled) { - Yap_InterruptsDisabled = 0; - UncaughtThrow = TRUE; - UNLOCK(SignalLock); + if (LOCAL_InterruptsDisabled) { + LOCAL_InterruptsDisabled = 0; + LOCAL_UncaughtThrow = TRUE; + UNLOCK(LOCAL_SignalLock); #if PUSH_REGS restore_absmi_regs(&Yap_standard_regs); #endif - siglongjmp(Yap_RestartEnv,1); + siglongjmp(LOCAL_RestartEnv,1); } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); /* wait if we we are in user code, it's up to her to decide */ - if (Yap_PrologMode & UserCCallMode) { + if (LOCAL_PrologMode & UserCCallMode) { if (!(EX = Yap_StoreTermInDB(Yap_MkApplTerm(fun, 2, nt), 0))) { /* fat chance */ - siglongjmp(Yap_RestartEnv,1); + siglongjmp(LOCAL_RestartEnv,1); } } else { if (type == PURE_ABORT) { @@ -1890,7 +1890,7 @@ E); P = (yamop *)FAILCODE; } } else { - Yap_PrologMode &= ~InErrorMode; + LOCAL_PrologMode &= ~InErrorMode; } return P; } diff --git a/C/eval.c b/C/eval.c index 3d7d52750..311c96e06 100644 --- a/C/eval.c +++ b/C/eval.c @@ -34,13 +34,13 @@ static char SccsId[] = "%W% %G%"; #include #endif -yap_error_number Yap_matherror = YAP_NO_ERROR; + static Term Eval(Term t USES_REGS) { if (IsVarTerm(t)) { - ArithError = TRUE; + LOCAL_ArithError = TRUE; return Yap_ArithError(INSTANTIATION_ERROR,t,"in arithmetic"); } else if (IsNumTerm(t)) { return t; @@ -131,14 +131,14 @@ p_is( USES_REGS1 ) Term out = 0L; while (!(out = Eval(Deref(ARG2) PASS_REGS))) { - if (Yap_Error_TYPE == RESOURCE_ERROR_STACK) { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, 2, ENV, CP)) { - Yap_Error(RESOURCE_ERROR_STACK, ARG2, Yap_ErrorMessage); + if (LOCAL_Error_TYPE == RESOURCE_ERROR_STACK) { + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, 2, ENV, CP)) { + Yap_Error(RESOURCE_ERROR_STACK, ARG2, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error(Yap_Error_TYPE, Yap_Error_Term, Yap_ErrorMessage); + Yap_Error(LOCAL_Error_TYPE, LOCAL_Error_Term, LOCAL_ErrorMessage); return FALSE; } } @@ -151,20 +151,20 @@ Yap_ArithError(yap_error_number type, Term where, char *format,...) CACHE_REGS va_list ap; - ArithError = TRUE; - Yap_Error_TYPE = type; - Yap_Error_Term = where; - if (!Yap_ErrorMessage) - Yap_ErrorMessage = Yap_ErrorSay; + LOCAL_ArithError = TRUE; + LOCAL_Error_TYPE = type; + LOCAL_Error_Term = where; + if (!LOCAL_ErrorMessage) + LOCAL_ErrorMessage = LOCAL_ErrorSay; va_start (ap, format); if (format != NULL) { #if HAVE_VSNPRINTF - (void) vsnprintf(Yap_ErrorMessage, MAX_ERROR_MSG_SIZE, format, ap); + (void) vsnprintf(LOCAL_ErrorMessage, MAX_ERROR_MSG_SIZE, format, ap); #else - (void) vsprintf(Yap_ErrorMessage, format, ap); + (void) vsprintf(LOCAL_ErrorMessage, format, ap); #endif } else { - Yap_ErrorMessage[0] = '\0'; + LOCAL_ErrorMessage[0] = '\0'; } va_end (ap); return 0L; diff --git a/C/evalis.c b/C/evalis.c deleted file mode 100644 index e69de29bb..000000000 diff --git a/C/evaltwo.c b/C/evaltwo.c deleted file mode 100644 index e69de29bb..000000000 diff --git a/C/exec.c b/C/exec.c index 8024fb95f..20d12d683 100644 --- a/C/exec.c +++ b/C/exec.c @@ -160,15 +160,15 @@ do_execute(Term t, Term mod USES_REGS) /* first do predicate expansion, even before you process signals. This way you don't get to spy goal_expansion(). */ if (PRED_GOAL_EXPANSION_ALL) { - LOCK(SignalLock); + LOCK(LOCAL_SignalLock); /* disable creeping when we do goal expansion */ - if (ActiveSignals & YAP_CREEP_SIGNAL && !Yap_InterruptsDisabled) { - ActiveSignals &= ~YAP_CREEP_SIGNAL; + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL && !LOCAL_InterruptsDisabled) { + LOCAL_ActiveSignals &= ~YAP_CREEP_SIGNAL; CreepFlag = CalculateStackGap(); } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return CallMetaCall(mod PASS_REGS); - } else if (ActiveSignals && !Yap_InterruptsDisabled) { + } else if (LOCAL_ActiveSignals && !LOCAL_InterruptsDisabled) { return EnterCreepMode(t, mod PASS_REGS); } restart_exec: @@ -331,16 +331,16 @@ do_execute_n(Term t, Term mod, unsigned int n USES_REGS) return CallError(TYPE_ERROR_CALLABLE, mod PASS_REGS); } if (PRED_GOAL_EXPANSION_ALL) { - LOCK(SignalLock); + LOCK(LOCAL_SignalLock); /* disable creeping when we do goal expansion */ - if (ActiveSignals & YAP_CREEP_SIGNAL && !Yap_InterruptsDisabled) { - ActiveSignals &= ~YAP_CREEP_SIGNAL; + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL && !LOCAL_InterruptsDisabled) { + LOCAL_ActiveSignals &= ~YAP_CREEP_SIGNAL; CreepFlag = CalculateStackGap(); } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); ARG1 = copy_execn_to_heap(f, pt, n, arity, mod PASS_REGS); return CallMetaCall(mod PASS_REGS); - } else if (ActiveSignals && !Yap_InterruptsDisabled) { + } else if (LOCAL_ActiveSignals && !LOCAL_InterruptsDisabled) { return EnterCreepMode(copy_execn_to_heap(f, pt, n, arity, CurrentModule PASS_REGS), mod PASS_REGS); } if (arity > MaxTemps) { @@ -378,12 +378,12 @@ static Int EnterCreepMode(Term t, Term mod USES_REGS) { PredEntry *PredCreep; - if (ActiveSignals & YAP_CDOVF_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CDOVF_SIGNAL) { ARG1 = t; if (!Yap_growheap(FALSE, 0, NULL)) { Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "YAP failed to grow heap at meta-call"); } - if (!ActiveSignals) { + if (!LOCAL_ActiveSignals) { return do_execute(ARG1, mod PASS_REGS); } } @@ -394,9 +394,9 @@ EnterCreepMode(Term t, Term mod USES_REGS) { } else { ARG1 = MkPairTerm(TermProlog,t); } - LOCK(SignalLock); + LOCK(LOCAL_SignalLock); CreepFlag = CalculateStackGap(); - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); P_before_spy = P; return CallPredicate(PredCreep, B, PredCreep->CodeOfPred PASS_REGS); } @@ -631,7 +631,7 @@ p_execute_clause( USES_REGS1 ) } else { code = Yap_ClauseFromTerm(clt)->ClCode; } - if (ActiveSignals & YAP_CREEP_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL) { Yap_signal(YAP_CREEP_SIGNAL); } return CallPredicate(RepPredProp(pe), cut_cp, code PASS_REGS); @@ -651,7 +651,7 @@ p_execute0( USES_REGS1 ) unsigned int arity; Prop pe; - if (ActiveSignals && !Yap_InterruptsDisabled) { + if (LOCAL_ActiveSignals && !LOCAL_InterruptsDisabled) { return EnterCreepMode(t, mod PASS_REGS); } restart_exec: @@ -781,7 +781,7 @@ p_execute_nonstop( USES_REGS1 ) /* N = arity; */ /* call may not define new system predicates!! */ if (RepPredProp(pe)->PredFlags & SpiedPredFlag) { - if (ActiveSignals & YAP_CREEP_SIGNAL && !Yap_InterruptsDisabled) { + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL && !LOCAL_InterruptsDisabled) { Yap_signal(YAP_CREEP_SIGNAL); } #if defined(YAPOR) || defined(THREADS) @@ -791,8 +791,8 @@ p_execute_nonstop( USES_REGS1 ) } #endif return CallPredicate(RepPredProp(pe), B, RepPredProp(pe)->cs.p_code.TrueCodeOfPred PASS_REGS); - } else { if (ActiveSignals & YAP_CREEP_SIGNAL && - !Yap_InterruptsDisabled && + } else { if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL && + !LOCAL_InterruptsDisabled && (!(RepPredProp(pe)->PredFlags & (AsmPredFlag|CPredFlag)) || RepPredProp(pe)->OpcodeOfPred == Yap_opcode(_call_bfunc_xx))) { Yap_signal(YAP_CREEP_SIGNAL); @@ -946,12 +946,12 @@ exec_absmi(int top USES_REGS) { int lval, out; - if (top && (lval = sigsetjmp (Yap_RestartEnv, 1)) != 0) { + if (top && (lval = sigsetjmp (LOCAL_RestartEnv, 1)) != 0) { switch(lval) { case 1: { /* restart */ /* otherwise, SetDBForThrow will fail entering critical mode */ - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; /* find out where to cut to */ /* siglongjmp resets the TR hardware register */ /* TR and B are crucial, they might have been changed, or not */ @@ -962,12 +962,12 @@ exec_absmi(int top USES_REGS) /* set stack */ ASP = (CELL *)PROTECT_FROZEN_B(B); Yap_StartSlots( PASS_REGS1 ); - LOCK(SignalLock); + LOCK(LOCAL_SignalLock); /* forget any signals active, we're reborne */ - ActiveSignals = 0; + LOCAL_ActiveSignals = 0; CreepFlag = CalculateStackGap(); - Yap_PrologMode = UserMode; - UNLOCK(SignalLock); + LOCAL_PrologMode = UserMode; + UNLOCK(LOCAL_SignalLock); P = (yamop *)FAILCODE; } break; @@ -975,11 +975,11 @@ exec_absmi(int top USES_REGS) { /* arithmetic exception */ /* must be done here, otherwise siglongjmp will clobber all the registers */ - Yap_Error(Yap_matherror,TermNil,NULL); + Yap_Error(LOCAL_matherror ,TermNil,NULL); /* reset the registers so that we don't have trash in abstract machine */ Yap_set_fpu_exceptions(yap_flags[LANGUAGE_MODE_FLAG] == 1); P = (yamop *)FAILCODE; - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; } break; case 3: @@ -988,10 +988,10 @@ exec_absmi(int top USES_REGS) } default: /* do nothing */ - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; } } else { - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; } Yap_CloseSlots( PASS_REGS1 ); YENV = ASP; @@ -999,8 +999,8 @@ exec_absmi(int top USES_REGS) out = Yap_absmi(0); Yap_StartSlots( PASS_REGS1 ); /* make sure we don't leave a FAIL signal hanging around */ - ActiveSignals &= ~YAP_FAIL_SIGNAL; - if (!ActiveSignals) + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); return out; } @@ -1048,9 +1048,6 @@ init_stack(int arity, CELL *pt, int top, choiceptr saved_b USES_REGS) #endif /* DEPTH_LIMIT */ YENV = ASP = (CELL *)B; HB = H; -#if defined(YAPOR) || defined(THREADS) - WPP = NULL; -#endif /* start with some slots so that we can use them */ Yap_StartSlots( PASS_REGS1 ); CP = YESCODE; @@ -1282,8 +1279,8 @@ Yap_RunTopGoal(Term t) CodeAdr = ppe->CodeOfPred; UNLOCK(ppe->PELock); #if !USE_SYSTEM_MALLOC - if (Yap_TrailTop - HeapTop < 2048) { - Yap_PrologMode = BootMode; + if (LOCAL_TrailTop - HeapTop < 2048) { + LOCAL_PrologMode = BootMode; Yap_Error(OUT_OF_TRAIL_ERROR,TermNil, "unable to boot because of too little Trail space"); } @@ -1475,9 +1472,9 @@ JumpToEnv(Term t USES_REGS) { if (EX) return FALSE; /* just keep the throwed object away, we don't need to care about it */ - if (!(BallTerm = Yap_StoreTermInDB(t, 0))) { + if (!(LOCAL_BallTerm = Yap_StoreTermInDB(t, 0))) { /* fat chance */ - siglongjmp(Yap_RestartEnv,1); + siglongjmp(LOCAL_RestartEnv,1); } /* careful, previous step may have caused a stack shift, so get pointers here */ @@ -1509,16 +1506,16 @@ JumpToEnv(Term t USES_REGS) { /* we reached C-Code */ if (handler->cp_ap == NOCODE) { /* up to the C-code to deal with this! */ - UncaughtThrow = TRUE; + LOCAL_UncaughtThrow = TRUE; if (previous == NULL) B = handler; else previous->cp_b = handler; - EX = BallTerm; - BallTerm = NULL; + EX = LOCAL_BallTerm; + LOCAL_BallTerm = NULL; P = (yamop *)FAILCODE; /* make sure failure will be seen at next port */ - if (Yap_PrologMode & AsyncIntMode) { + if (LOCAL_PrologMode & AsyncIntMode) { Yap_signal(YAP_FAIL_SIGNAL); } HB = B->cp_h; @@ -1528,11 +1525,11 @@ JumpToEnv(Term t USES_REGS) { } /* uncaught throw */ if (handler == NULL) { - UncaughtThrow = TRUE; + LOCAL_UncaughtThrow = TRUE; #if PUSH_REGS restore_absmi_regs(&Yap_standard_regs); #endif - siglongjmp(Yap_RestartEnv,1); + siglongjmp(LOCAL_RestartEnv,1); } /* is it a continuation? */ env = handler->cp_env; @@ -1563,7 +1560,7 @@ JumpToEnv(Term t USES_REGS) { /* B->cp_h = H; */ /* I could backtrack here, but it is easier to leave the unwinding to the emulator */ - if (Yap_PrologMode & AsyncIntMode) { + if (LOCAL_PrologMode & AsyncIntMode) { Yap_signal(YAP_FAIL_SIGNAL); } P = (yamop *)FAILCODE; @@ -1578,7 +1575,7 @@ JumpToEnv(Term t USES_REGS) { Int Yap_JumpToEnv(Term t) { CACHE_REGS - if (Yap_PrologMode & BootMode) { + if (LOCAL_PrologMode & BootMode) { return FALSE; } return JumpToEnv(t PASS_REGS); @@ -1605,27 +1602,26 @@ Yap_InitYaamRegs(void) { CACHE_REGS Term h0var; - #if PUSH_REGS /* Guarantee that after a longjmp we go back to the original abstract machine registers */ #ifdef THREADS int myworker_id = worker_id; - pthread_setspecific(Yap_yaamregs_key, (const void *)FOREIGN_ThreadHandle(myworker_id).default_yaam_regs); - FOREIGN_ThreadHandle(myworker_id).current_yaam_regs = FOREIGN_ThreadHandle(myworker_id).default_yaam_regs; - worker_id = myworker_id; + pthread_setspecific(Yap_yaamregs_key, (const void *)REMOTE_ThreadHandle(myworker_id).default_yaam_regs); + REMOTE_ThreadHandle(myworker_id).current_yaam_regs = REMOTE_ThreadHandle(myworker_id).default_yaam_regs; + worker_id = myworker_id; /* ricroc: for what I understand, this shouldn't be necessary */ #else Yap_regp = &Yap_standard_regs; #endif #endif /* PUSH_REGS */ Yap_ResetExceptionTerm (); Yap_PutValue (AtomBreak, MkIntTerm (0)); - TR = (tr_fr_ptr)Yap_TrailBase; - if (Yap_AttsSize > (Yap_LocalBase-Yap_GlobalBase)/8) - Yap_AttsSize = (Yap_LocalBase-Yap_GlobalBase)/8; - H = H0 = ((CELL *) Yap_GlobalBase)+ Yap_AttsSize/sizeof(CELL); + TR = (tr_fr_ptr)LOCAL_TrailBase; + if (Yap_AttsSize > (LOCAL_LocalBase-LOCAL_GlobalBase)/8) + Yap_AttsSize = (LOCAL_LocalBase-LOCAL_GlobalBase)/8; + H = H0 = ((CELL *) LOCAL_GlobalBase)+ Yap_AttsSize/sizeof(CELL); RESET_VARIABLE(H0-1); - LCL0 = ASP = (CELL *) Yap_LocalBase; + LCL0 = ASP = (CELL *) LOCAL_LocalBase; /* notice that an initial choice-point and environment *must* be created since for the garbage collector to work */ B = NULL; @@ -1640,29 +1636,28 @@ Yap_InitYaamRegs(void) #ifdef YAPOR_SBA BSEG = #endif /* YAPOR_SBA */ - BBREG = B_FZ = (choiceptr) Yap_LocalBase; - TR = TR_FZ = (tr_fr_ptr) Yap_TrailBase; + BBREG = B_FZ = (choiceptr) LOCAL_LocalBase; + TR = TR_FZ = (tr_fr_ptr) LOCAL_TrailBase; #endif /* FROZEN_STACKS */ - LOCK(SignalLock); + LOCK(LOCAL_SignalLock); CreepFlag = CalculateStackGap(); - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); EX = NULL; init_stack(0, NULL, TRUE, NULL PASS_REGS); /* the first real choice-point will also have AP=FAIL */ /* always have an empty slots for people to use */ CurSlot = 0; - GlobalArena = TermNil; + LOCAL_GlobalArena = TermNil; h0var = MkVarTerm(); #if COROUTINING - WokenGoals = Yap_NewTimedVar(TermNil); - AttsMutableList = Yap_NewTimedVar(h0var); + LOCAL_WokenGoals = Yap_NewTimedVar(TermNil); + LOCAL_AttsMutableList = Yap_NewTimedVar(h0var); #endif - GcGeneration = Yap_NewTimedVar(h0var); - GcCurrentPhase = 0L; - GcPhase = Yap_NewTimedVar(MkIntTerm(GcCurrentPhase)); + LOCAL_GcGeneration = Yap_NewTimedVar(h0var); + LOCAL_GcCurrentPhase = 0L; + LOCAL_GcPhase = Yap_NewTimedVar(MkIntTerm(LOCAL_GcCurrentPhase)); #if defined(YAPOR) || defined(THREADS) PP = NULL; - WPP = NULL; PREG_ADDR = NULL; #endif Yap_AllocateDefaultArena(128*1024, 2); @@ -1678,8 +1673,8 @@ Yap_InitYaamRegs(void) static Int p_uncaught_throw( USES_REGS1 ) { - Int out = UncaughtThrow; - UncaughtThrow = FALSE; /* just caught it */ + Int out = LOCAL_UncaughtThrow; + LOCAL_UncaughtThrow = FALSE; /* just caught it */ return out; } @@ -1687,14 +1682,14 @@ static Int p_creep_allowed( USES_REGS1 ) { if (PP != NULL) { - LOCK(SignalLock); - if (ActiveSignals & YAP_CREEP_SIGNAL && !Yap_InterruptsDisabled) { - ActiveSignals &= ~YAP_CREEP_SIGNAL; - if (!ActiveSignals) + LOCK(LOCAL_SignalLock); + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL && !LOCAL_InterruptsDisabled) { + LOCAL_ActiveSignals &= ~YAP_CREEP_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); } else { - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); } return TRUE; } @@ -1706,15 +1701,15 @@ p_debug_on( USES_REGS1 ) { Term t = Deref(ARG1); if (IsVarTerm(t)) { - if (DebugOn) + if (LOCAL_DebugOn) return Yap_unify(MkAtomTerm(AtomTrue),ARG1); else return Yap_unify(MkAtomTerm(AtomFalse),ARG1); } if (t == MkAtomTerm(AtomTrue)) - DebugOn = TRUE; + LOCAL_DebugOn = TRUE; else - DebugOn = FALSE; + LOCAL_DebugOn = FALSE; return TRUE; } @@ -1723,26 +1718,26 @@ Yap_GetException(void) { CACHE_REGS Term t = 0L; - if (BallTerm) { + if (LOCAL_BallTerm) { do { - t = Yap_PopTermFromDB(BallTerm); + t = Yap_PopTermFromDB(LOCAL_BallTerm); if (t == 0) { - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_growstack(BallTerm->NOfCells*CellSize)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_growstack(LOCAL_BallTerm->NOfCells*CellSize)) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } } } while (t == 0); - BallTerm = NULL; + LOCAL_BallTerm = NULL; } return t; } @@ -1762,8 +1757,8 @@ void Yap_ResetExceptionTerm(void) { CACHE_REGS - Yap_ReleaseTermFromDB(BallTerm); - BallTerm = NULL; + Yap_ReleaseTermFromDB(LOCAL_BallTerm); + LOCAL_BallTerm = NULL; } static Int diff --git a/C/globals.c b/C/globals.c index f55fba220..5c2851796 100644 --- a/C/globals.c +++ b/C/globals.c @@ -111,7 +111,7 @@ NewArena(UInt size, UInt arity, CELL *where USES_REGS) if (where == NULL || where == H) { while (H+size > ASP-1024) { if (!Yap_gcl(size*sizeof(CELL), arity, ENV, P)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return TermNil; } } @@ -146,7 +146,7 @@ p_allocate_arena( USES_REGS1 ) static Int p_default_arena_size( USES_REGS1 ) { - return Yap_unify(ARG1,MkIntegerTerm(ArenaSz(GlobalArena))); + return Yap_unify(ARG1,MkIntegerTerm(ArenaSz(LOCAL_GlobalArena))); } @@ -154,7 +154,7 @@ void Yap_AllocateDefaultArena(Int gsize, Int attsize) { CACHE_REGS - GlobalArena = NewArena(gsize, 2, NULL PASS_REGS); + LOCAL_GlobalArena = NewArena(gsize, 2, NULL PASS_REGS); } static void @@ -172,7 +172,7 @@ adjust_cps(UInt size USES_REGS) static int GrowArena(Term arena, CELL *pt, UInt old_size, UInt size, UInt arity USES_REGS) { - ArenaOverflows++; + LOCAL_ArenaOverflows++; if (size == 0) { if (old_size < 128*1024) { size = old_size; @@ -188,7 +188,7 @@ GrowArena(Term arena, CELL *pt, UInt old_size, UInt size, UInt arity USES_REGS) XREGS[arity+1] = arena; if (!Yap_gcl(size*sizeof(CELL), arity+1, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } arena = XREGS[arity+1]; @@ -201,9 +201,9 @@ GrowArena(Term arena, CELL *pt, UInt old_size, UInt size, UInt arity USES_REGS) } else { XREGS[arity+1] = arena; /* try to recover some room */ - if (arena == GlobalArena && 10*(pt-H0) > 8*(H-H0)) { + if (arena == LOCAL_GlobalArena && 10*(pt-H0) > 8*(H-H0)) { if (!Yap_gcl(size*sizeof(CELL), arity+1, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR,TermNil,Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR,TermNil,LOCAL_ErrorMessage); return FALSE; } } @@ -474,12 +474,12 @@ copy_complex_term(register CELL *pt0, register CELL *pt0_end, int share, int cop CELL new; bp = to_visit; - if (!attas[ExtFromCell(ptd0)].copy_term_op(ptd0, &bp, ptf PASS_REGS)) { + if (!GLOBAL_attas[ExtFromCell(ptd0)].copy_term_op(ptd0, &bp, ptf PASS_REGS)) { goto overflow; } to_visit = bp; new = *ptf; - if (TR > (tr_fr_ptr)Yap_TrailTop - 256) { + if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) { /* Trail overflow */ if (!Yap_growtrail((TR-TR0)*sizeof(tr_fr_ptr *), TRUE)) { goto trail_overflow; @@ -491,7 +491,7 @@ copy_complex_term(register CELL *pt0, register CELL *pt0_end, int share, int cop #endif /* first time we met this term */ RESET_VARIABLE(ptf); - if ((ADDR)TR > Yap_TrailTop-MIN_ARENA_SIZE) + if ((ADDR)TR > LOCAL_TrailTop-MIN_ARENA_SIZE) goto trail_overflow; Bind_and_Trail(ptd0, (CELL)ptf); ptf++; @@ -720,16 +720,16 @@ CopyTermToArena(Term t, Term arena, int share, int copy_att_vars, UInt arity, Te HB = oldHB; switch (res) { case -1: - if (arena == GlobalArena) - GlobalArenaOverflows++; + if (arena == LOCAL_GlobalArena) + LOCAL_GlobalArenaOverflows++; if (!GrowArena(arena, old_top, old_size, min_grow, arity+3 PASS_REGS)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } break; default: /* temporary space overflow */ if (!Yap_ExpandPreAllocCodeSpace(0,NULL,TRUE)) { - Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } } @@ -774,8 +774,8 @@ CreateTermInArena(Term arena, Atom Na, UInt Nar, UInt arity, Term *newarena, Ter ASP = oldASP; H = oldH; HB = oldHB; - if (arena == GlobalArena) - GlobalArenaOverflows++; + if (arena == LOCAL_GlobalArena) + LOCAL_GlobalArenaOverflows++; if (!GrowArena(arena, old_top, old_size, Nar*sizeof(CELL), arity+2 PASS_REGS)) { Yap_Error(OUT_OF_STACK_ERROR, TermNil, "while creating large global term"); return 0L; @@ -855,8 +855,8 @@ GetGlobalEntry(Atom at USES_REGS) #if THREADS new->owner_id = worker_id; #endif - new->NextGE = GlobalVariables; - GlobalVariables = new; + new->NextGE = LOCAL_GlobalVariables; + LOCAL_GlobalVariables = new; new->AtomOfGE = ae; new->NextOfPE = ae->PropsOfAE; ae->PropsOfAE = AbsGlobalProp(new); @@ -869,8 +869,8 @@ static UInt garena_overflow_size(CELL *arena USES_REGS) { UInt dup = (((CELL *)arena-H0)*sizeof(CELL))>>3; - if (dup < 64*1024*GlobalArenaOverflows) - dup = 64*1024*GlobalArenaOverflows; + if (dup < 64*1024*LOCAL_GlobalArenaOverflows) + dup = 64*1024*LOCAL_GlobalArenaOverflows; if (dup > 1024*1024) return 1024*1024; return dup; @@ -911,7 +911,7 @@ p_nb_setarg( USES_REGS1 ) return FALSE; to = Deref(ARG3); - to = CopyTermToArena(ARG3, GlobalArena, FALSE, TRUE, 2, &GlobalArena, garena_overflow_size(ArenaPt(GlobalArena) PASS_REGS) PASS_REGS); + to = CopyTermToArena(ARG3, LOCAL_GlobalArena, FALSE, TRUE, 2, &LOCAL_GlobalArena, garena_overflow_size(ArenaPt(LOCAL_GlobalArena) PASS_REGS) PASS_REGS); if (to == 0L) return FALSE; @@ -958,7 +958,7 @@ p_nb_set_shared_arg( USES_REGS1 ) } if (pos < 1 || pos > arity) return FALSE; - to = CopyTermToArena(ARG3, GlobalArena, TRUE, TRUE, 3, &GlobalArena, garena_overflow_size(ArenaPt(GlobalArena) PASS_REGS) PASS_REGS); + to = CopyTermToArena(ARG3, LOCAL_GlobalArena, TRUE, TRUE, 3, &LOCAL_GlobalArena, garena_overflow_size(ArenaPt(LOCAL_GlobalArena) PASS_REGS) PASS_REGS); if (to == 0L) return FALSE; destp[pos] = to; @@ -1041,7 +1041,7 @@ p_nb_create_accumulator( USES_REGS1 ) if (!Yap_unify(ARG2, acct)) { return FALSE; } - to = CopyTermToArena(t, GlobalArena, TRUE, TRUE, 2, &GlobalArena, garena_overflow_size(ArenaPt(GlobalArena) PASS_REGS) PASS_REGS); + to = CopyTermToArena(t, LOCAL_GlobalArena, TRUE, TRUE, 2, &LOCAL_GlobalArena, garena_overflow_size(ArenaPt(LOCAL_GlobalArena) PASS_REGS) PASS_REGS); if (to == 0L) return FALSE; destp = RepAppl(Deref(ARG2)); @@ -1091,7 +1091,7 @@ p_nb_add_to_accumulator( USES_REGS1 ) target[1] = source[1]; } else { /* we need to create a new long int */ - new = CopyTermToArena(new, GlobalArena, TRUE, TRUE, 2, &GlobalArena, garena_overflow_size(ArenaPt(GlobalArena) PASS_REGS) PASS_REGS); + new = CopyTermToArena(new, LOCAL_GlobalArena, TRUE, TRUE, 2, &LOCAL_GlobalArena, garena_overflow_size(ArenaPt(LOCAL_GlobalArena) PASS_REGS) PASS_REGS); destp = RepAppl(Deref(ARG1)); destp[1] = new; } @@ -1118,7 +1118,7 @@ p_nb_add_to_accumulator( USES_REGS1 ) new = Yap_MkApplTerm(FunctorPlus, 2, t2); new = Yap_Eval(new); - new = CopyTermToArena(new, GlobalArena, TRUE, TRUE, 2, &GlobalArena, garena_overflow_size(ArenaPt(GlobalArena) PASS_REGS) PASS_REGS); + new = CopyTermToArena(new, LOCAL_GlobalArena, TRUE, TRUE, 2, &LOCAL_GlobalArena, garena_overflow_size(ArenaPt(LOCAL_GlobalArena) PASS_REGS) PASS_REGS); destp = RepAppl(Deref(ARG1)); destp[1] = new; @@ -1158,7 +1158,7 @@ Yap_SetGlobalVal(Atom at, Term t0) Term to; GlobalEntry *ge; ge = GetGlobalEntry(at PASS_REGS); - to = CopyTermToArena(t0, GlobalArena, FALSE, TRUE, 2, &GlobalArena, garena_overflow_size(ArenaPt(GlobalArena) PASS_REGS) PASS_REGS); + to = CopyTermToArena(t0, LOCAL_GlobalArena, FALSE, TRUE, 2, &LOCAL_GlobalArena, garena_overflow_size(ArenaPt(LOCAL_GlobalArena) PASS_REGS) PASS_REGS); if (to == 0L) return to; WRITE_LOCK(ge->GRWLock); @@ -1172,7 +1172,7 @@ Yap_SaveTerm(Term t0) { CACHE_REGS Term to; - to = CopyTermToArena(t0, GlobalArena, FALSE, TRUE, 2, &GlobalArena, garena_overflow_size(ArenaPt(GlobalArena) PASS_REGS) PASS_REGS); + to = CopyTermToArena(t0, LOCAL_GlobalArena, FALSE, TRUE, 2, &LOCAL_GlobalArena, garena_overflow_size(ArenaPt(LOCAL_GlobalArena) PASS_REGS) PASS_REGS); if (to == 0L) return to; return to; @@ -1205,7 +1205,7 @@ p_nb_set_shared_val( USES_REGS1 ) return (FALSE); } ge = GetGlobalEntry(AtomOfTerm(t) PASS_REGS); - to = CopyTermToArena(ARG2, GlobalArena, TRUE, TRUE, 2, &GlobalArena, garena_overflow_size(ArenaPt(GlobalArena) PASS_REGS) PASS_REGS); + to = CopyTermToArena(ARG2, LOCAL_GlobalArena, TRUE, TRUE, 2, &LOCAL_GlobalArena, garena_overflow_size(ArenaPt(LOCAL_GlobalArena) PASS_REGS) PASS_REGS); if (to == 0L) return FALSE; WRITE_LOCK(ge->GRWLock); @@ -1295,10 +1295,10 @@ nbdelete(Atom at USES_REGS) } WRITE_LOCK(ge->GRWLock); ae = ge->AtomOfGE; - if (GlobalVariables == ge) { - GlobalVariables = ge->NextGE; + if (LOCAL_GlobalVariables == ge) { + LOCAL_GlobalVariables = ge->NextGE; } else { - g = GlobalVariables; + g = LOCAL_GlobalVariables; while (g->NextGE != ge) g = g->NextGE; g->NextGE = ge->NextGE; @@ -1376,7 +1376,7 @@ p_nb_create( USES_REGS1 ) Yap_Error(TYPE_ERROR_ATOM,tname,"nb_create"); return FALSE; } - to = CreateTermInArena(GlobalArena, AtomOfTerm(tname), IntegerOfTerm(tarity), 3, &GlobalArena, 0L PASS_REGS); + to = CreateTermInArena(LOCAL_GlobalArena, AtomOfTerm(tname), IntegerOfTerm(tarity), 3, &LOCAL_GlobalArena, 0L PASS_REGS); if (!to) return FALSE; WRITE_LOCK(ge->GRWLock); @@ -1428,7 +1428,7 @@ p_nb_create2( USES_REGS1 ) Yap_Error(TYPE_ERROR_ATOM,tname,"nb_create"); return FALSE; } - to = CreateTermInArena(GlobalArena, AtomOfTerm(tname), IntegerOfTerm(tarity), 4, &GlobalArena, tinit PASS_REGS); + to = CreateTermInArena(LOCAL_GlobalArena, AtomOfTerm(tname), IntegerOfTerm(tarity), 4, &LOCAL_GlobalArena, tinit PASS_REGS); if (!to) return FALSE; WRITE_LOCK(ge->GRWLock); @@ -1445,7 +1445,7 @@ nb_queue(UInt arena_sz USES_REGS) Term queue_arena, queue, ar[QUEUE_FUNCTOR_ARITY], *nar; Term t = Deref(ARG1); - DepthArenas++; + LOCAL_DepthArenas++; if (!IsVarTerm(t)) { if (!IsApplTerm(t)) { return FALSE; @@ -1475,8 +1475,8 @@ static Int p_nb_queue( USES_REGS1 ) { UInt arena_sz = (ASP-H)/16; - if (DepthArenas > 1) - arena_sz /= DepthArenas; + if (LOCAL_DepthArenas > 1) + arena_sz /= LOCAL_DepthArenas; if (arena_sz < MIN_ARENA_SIZE) arena_sz = MIN_ARENA_SIZE; if (arena_sz > MAX_ARENA_SIZE) @@ -1556,7 +1556,7 @@ p_nb_queue_close( USES_REGS1 ) Term t = Deref(ARG1); Int out; - DepthArenas--; + LOCAL_DepthArenas--; if (!IsVarTerm(t)) { CELL *qp; @@ -1625,7 +1625,7 @@ p_nb_queue_enqueue( USES_REGS1 ) ARG3 = to; /* fprintf(stderr,"growing %ld cells\n",(unsigned long int)gsiz);*/ if (!GrowArena(arena, ArenaLimit(arena), old_sz, gsiz, 3 PASS_REGS)) { - Yap_Error(OUT_OF_STACK_ERROR, arena, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, arena, LOCAL_ErrorMessage); return 0L; } to = ARG3; @@ -1677,6 +1677,31 @@ p_nb_queue_dequeue( USES_REGS1 ) return Yap_unify(out, ARG2); } +/* purge an entry from the queue, replacing it by [] */ +static Int +p_nb_queue_replace( USES_REGS1 ) +{ + CELL *qd = GetQueue(ARG1,"dequeue"); + UInt qsz; + Term queue, t = Deref(ARG2); + + if (!qd) + return FALSE; + qsz = IntegerOfTerm(qd[QUEUE_SIZE]); + if (qsz == 0) + return FALSE; + + queue = qd[QUEUE_HEAD]; + for (; qsz > 0; qsz--) { + if (Yap_eq(HeadOfTerm(queue), t)) { + *RepPair(Deref(queue)) = Deref(ARG3); + return TRUE; + } + queue = TailOfTerm(queue); + } + return FALSE; +} + static Int p_nb_queue_peek( USES_REGS1 ) { @@ -1711,6 +1736,16 @@ p_nb_queue_size( USES_REGS1 ) return Yap_unify(ARG2,qd[QUEUE_SIZE]); } +static Int +p_nb_queue_show( USES_REGS1 ) +{ + CELL *qd = GetQueue(ARG1,"queue_size"); + + if (!qd) + return FALSE; + return Yap_unify(ARG2,qd[QUEUE_HEAD]); +} + static CELL * GetHeap(Term t, char* caller) @@ -1768,7 +1803,7 @@ p_nb_heap( USES_REGS1 ) while ((heap = MkZeroApplTerm(Yap_MkFunctor(AtomHeap,2*hsize+HEAP_START+1),2*hsize+HEAP_START+1 PASS_REGS)) == TermNil) { if (!Yap_gcl((2*hsize+HEAP_START+1)*sizeof(CELL), 2, ENV, P)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1942,7 +1977,7 @@ p_nb_heap_add_to_heap( USES_REGS1 ) } ARG3 = to; if (!GrowArena(arena, ArenaLimit(arena), old_sz, gsiz, 3 PASS_REGS)) { - Yap_Error(OUT_OF_STACK_ERROR, arena, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, arena, LOCAL_ErrorMessage); return 0L; } to = ARG3; @@ -2050,7 +2085,7 @@ p_nb_beam( USES_REGS1 ) } while ((beam = MkZeroApplTerm(Yap_MkFunctor(AtomHeap,5*hsize+HEAP_START+1),5*hsize+HEAP_START+1 PASS_REGS)) == TermNil) { if (!Yap_gcl((4*hsize+HEAP_START+1)*sizeof(CELL), 2, ENV, P)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -2328,7 +2363,7 @@ p_nb_beam_add_to_beam( USES_REGS1 ) } ARG3 = to; if (!GrowArena(arena, ArenaLimit(arena), old_sz, gsiz, 3 PASS_REGS)) { - Yap_Error(OUT_OF_STACK_ERROR, arena, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, arena, LOCAL_ErrorMessage); return 0L; } to = ARG3; @@ -2440,7 +2475,7 @@ p_nb_beam_keys( USES_REGS1 ) if (H > ASP-1024) { H = ho; if (!Yap_gcl(((ASP-H)-1024)*sizeof(CELL), 2, ENV, P)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return TermNil; } goto restart; @@ -2531,7 +2566,7 @@ init_current_nb( USES_REGS1 ) } } READ_LOCK(HashChain[0].AERWLock); - EXTRA_CBACK_ARG(1,1) = MkIntegerTerm((Int)GlobalVariables); + EXTRA_CBACK_ARG(1,1) = MkIntegerTerm((Int)LOCAL_GlobalVariables); return cont_current_nb( PASS_REGS1 ); } @@ -2562,7 +2597,9 @@ void Yap_InitGlobals(void) Yap_InitCPred("nb_queue_dequeue", 2, p_nb_queue_dequeue, SafePredFlag); Yap_InitCPred("nb_queue_peek", 2, p_nb_queue_peek, SafePredFlag); Yap_InitCPred("nb_queue_empty", 1, p_nb_queue_empty, SafePredFlag); + Yap_InitCPred("nb_queue_replace", 3, p_nb_queue_replace, SafePredFlag); Yap_InitCPred("nb_queue_size", 2, p_nb_queue_size, SafePredFlag); + Yap_InitCPred("nb_queue_show", 2, p_nb_queue_show, SafePredFlag); Yap_InitCPred("nb_heap", 2, p_nb_heap, 0L); Yap_InitCPred("nb_heap_close", 1, p_nb_heap_close, SafePredFlag); Yap_InitCPred("nb_heap_add", 3, p_nb_heap_add_to_heap, 0L); diff --git a/C/gprof.c b/C/gprof.c index 1ebebd8bb..3d475456f 100755 --- a/C/gprof.c +++ b/C/gprof.c @@ -123,13 +123,13 @@ typedef greg_t context_reg; #include #endif -static Int ProfCalls, ProfGCs, ProfHGrows, ProfSGrows, ProfMallocs, ProfOn, ProfOns; + #define TIMER_DEFAULT 100 #define PROFILING_FILE 1 #define PROFPREDS_FILE 2 -static char *DIRNAME=NULL; + typedef struct RB_red_blk_node { yamop *key; /* first address */ @@ -142,7 +142,7 @@ typedef struct RB_red_blk_node { struct RB_red_blk_node* parent; } rb_red_blk_node; -static rb_red_blk_node *ProfilerRoot, *ProfilerNil; + static rb_red_blk_node * RBMalloc(UInt size) @@ -162,14 +162,14 @@ RBTreeCreate(void) { /* see the comment in the rb_red_blk_tree structure in red_black_tree.h */ /* for information on nil and root */ - temp=ProfilerNil= RBMalloc(sizeof(rb_red_blk_node)); + temp=GLOBAL_ProfilerNil= RBMalloc(sizeof(rb_red_blk_node)); temp->parent=temp->left=temp->right=temp; temp->pcs=0; temp->red=0; temp->key=temp->lim=NULL; temp->pe=NULL; temp = RBMalloc(sizeof(rb_red_blk_node)); - temp->parent=temp->left=temp->right=ProfilerNil; + temp->parent=temp->left=temp->right=GLOBAL_ProfilerNil; temp->key=temp->lim=NULL; temp->pe=NULL; temp->pcs=0; @@ -199,7 +199,7 @@ RBTreeCreate(void) { static void LeftRotate(rb_red_blk_node* x) { rb_red_blk_node* y; - rb_red_blk_node* nil=ProfilerNil; + rb_red_blk_node* nil=GLOBAL_ProfilerNil; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ @@ -230,7 +230,7 @@ LeftRotate(rb_red_blk_node* x) { x->parent=y; #ifdef DEBUG_ASSERT - Assert(!ProfilerNil->red,"nil not red in LeftRotate"); + Assert(!GLOBAL_ProfilerNil->red,"nil not red in LeftRotate"); #endif } @@ -255,7 +255,7 @@ LeftRotate(rb_red_blk_node* x) { static void RightRotate(rb_red_blk_node* y) { rb_red_blk_node* x; - rb_red_blk_node* nil=ProfilerNil; + rb_red_blk_node* nil=GLOBAL_ProfilerNil; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ @@ -285,7 +285,7 @@ RightRotate(rb_red_blk_node* y) { y->parent=x; #ifdef DEBUG_ASSERT - Assert(!ProfilerNil->red,"nil not red in RightRotate"); + Assert(!GLOBAL_ProfilerNil->red,"nil not red in RightRotate"); #endif } @@ -309,11 +309,11 @@ TreeInsertHelp(rb_red_blk_node* z) { /* This function should only be called by InsertRBTree (see above) */ rb_red_blk_node* x; rb_red_blk_node* y; - rb_red_blk_node* nil=ProfilerNil; + rb_red_blk_node* nil=GLOBAL_ProfilerNil; z->left=z->right=nil; - y=ProfilerRoot; - x=ProfilerRoot->left; + y=GLOBAL_ProfilerRoot; + x=GLOBAL_ProfilerRoot->left; while( x != nil) { y=x; if (x->key > z->key) { /* x.key > z.key */ @@ -323,7 +323,7 @@ TreeInsertHelp(rb_red_blk_node* z) { } } z->parent=y; - if ( (y == ProfilerRoot) || + if ( (y == GLOBAL_ProfilerRoot) || (y->key > z->key)) { /* y.key > z.key */ y->left=z; } else { @@ -331,7 +331,7 @@ TreeInsertHelp(rb_red_blk_node* z) { } #ifdef DEBUG_ASSERT - Assert(!ProfilerNil->red,"nil not red in TreeInsertHelp"); + Assert(!GLOBAL_ProfilerNil->red,"nil not red in TreeInsertHelp"); #endif } @@ -403,12 +403,12 @@ RBTreeInsert(yamop *key, yamop *lim) { } } } - ProfilerRoot->left->red=0; + GLOBAL_ProfilerRoot->left->red=0; return newNode; #ifdef DEBUG_ASSERT - Assert(!ProfilerNil->red,"nil not red in RBTreeInsert"); - Assert(!ProfilerRoot->red,"root not red in RBTreeInsert"); + Assert(!GLOBAL_ProfilerNil->red,"nil not red in RBTreeInsert"); + Assert(!GLOBAL_ProfilerRoot->red,"root not red in RBTreeInsert"); #endif } @@ -429,10 +429,10 @@ RBTreeInsert(yamop *key, yamop *lim) { static rb_red_blk_node* RBExactQuery(yamop* q) { rb_red_blk_node* x; - rb_red_blk_node* nil=ProfilerNil; + rb_red_blk_node* nil=GLOBAL_ProfilerNil; - if (!ProfilerRoot) return NULL; - x=ProfilerRoot->left; + if (!GLOBAL_ProfilerRoot) return NULL; + x=GLOBAL_ProfilerRoot->left; if (x == nil) return NULL; while(x->key != q) {/*assignemnt*/ if (x->key > q) { /* x->key > q */ @@ -450,10 +450,10 @@ static rb_red_blk_node* RBLookup(yamop *entry) { rb_red_blk_node *current; - if (!ProfilerRoot) + if (!GLOBAL_ProfilerRoot) return NULL; - current = ProfilerRoot->left; - while (current != ProfilerNil) { + current = GLOBAL_ProfilerRoot->left; + while (current != GLOBAL_ProfilerNil) { if (current->key <= entry && current->lim >= entry) { return current; } @@ -483,7 +483,7 @@ RBLookup(yamop *entry) { /***********************************************************************/ static void RBDeleteFixUp(rb_red_blk_node* x) { - rb_red_blk_node* root=ProfilerRoot->left; + rb_red_blk_node* root=GLOBAL_ProfilerRoot->left; rb_red_blk_node *w; while( (!x->red) && (root != x)) { @@ -563,8 +563,8 @@ static void RBDeleteFixUp(rb_red_blk_node* x) { static rb_red_blk_node* TreeSuccessor(rb_red_blk_node* x) { rb_red_blk_node* y; - rb_red_blk_node* nil=ProfilerNil; - rb_red_blk_node* root=ProfilerRoot; + rb_red_blk_node* nil=GLOBAL_ProfilerNil; + rb_red_blk_node* root=GLOBAL_ProfilerRoot; if (nil != (y = x->right)) { /* assignment to y is intentional */ while(y->left != nil) { /* returns the minium of the right subtree of x */ @@ -602,8 +602,8 @@ static void RBDelete(rb_red_blk_node* z){ rb_red_blk_node* y; rb_red_blk_node* x; - rb_red_blk_node* nil=ProfilerNil; - rb_red_blk_node* root=ProfilerRoot; + rb_red_blk_node* nil=GLOBAL_ProfilerNil; + rb_red_blk_node* root=GLOBAL_ProfilerRoot; y= ((z->left == nil) || (z->right == nil)) ? z : TreeSuccessor(z); x= (y->left == nil) ? y->right : y->left; @@ -656,21 +656,21 @@ int size=0; if (name!=NULL) { size=strlen(name)+1; - if (DIRNAME!=NULL) free(DIRNAME); - DIRNAME=malloc(size); - if (DIRNAME==NULL) { printf("Profiler Out of Mem\n"); exit(1); } - strcpy(DIRNAME,name); + if (GLOBAL_DIRNAME!=NULL) free(GLOBAL_DIRNAME); + GLOBAL_DIRNAME=malloc(size); + if (GLOBAL_DIRNAME==NULL) { printf("Profiler Out of Mem\n"); exit(1); } + strcpy(GLOBAL_DIRNAME,name); } - if (DIRNAME==NULL) { + if (GLOBAL_DIRNAME==NULL) { do { - if (DIRNAME!=NULL) free(DIRNAME); + if (GLOBAL_DIRNAME!=NULL) free(GLOBAL_DIRNAME); size+=20; - DIRNAME=malloc(size); - if (DIRNAME==NULL) { printf("Profiler Out of Mem\n"); exit(1); } - } while (getcwd(DIRNAME, size-15)==NULL); + GLOBAL_DIRNAME=malloc(size); + if (GLOBAL_DIRNAME==NULL) { printf("Profiler Out of Mem\n"); exit(1); } + } while (getcwd(GLOBAL_DIRNAME, size-15)==NULL); } -return DIRNAME; +return GLOBAL_DIRNAME; } char *profile_names(int); @@ -678,12 +678,12 @@ char *profile_names(int k) { static char *FNAME=NULL; int size=200; - if (DIRNAME==NULL) set_profile_dir(NULL); - size=strlen(DIRNAME)+40; + if (GLOBAL_DIRNAME==NULL) set_profile_dir(NULL); + size=strlen(GLOBAL_DIRNAME)+40; if (FNAME!=NULL) free(FNAME); FNAME=malloc(size); if (FNAME==NULL) { printf("Profiler Out of Mem\n"); exit(1); } - strcpy(FNAME,DIRNAME); + strcpy(FNAME,GLOBAL_DIRNAME); if (k==PROFILING_FILE) { sprintf(FNAME,"%s/PROFILING_%d",FNAME,getpid()); @@ -697,7 +697,7 @@ int size=200; void del_profile_files(void); void del_profile_files() { - if (DIRNAME!=NULL) { + if (GLOBAL_DIRNAME!=NULL) { remove(profile_names(PROFPREDS_FILE)); remove(profile_names(PROFILING_FILE)); } @@ -708,7 +708,7 @@ Yap_inform_profiler_of_clause(yamop *code_start, yamop *code_end, PredEntry *pe, static Int order=0; ProfPreds++; - ProfOn = TRUE; + GLOBAL_ProfOn = TRUE; if (FPreds != NULL) { Int temp; @@ -716,7 +716,7 @@ static Int order=0; if (index_code) temp=-order; else temp=order; fprintf(FPreds,"+%p %p %p %ld\n",code_start,code_end, pe, (long int)temp); } - ProfOn = FALSE; + GLOBAL_ProfOn = FALSE; } typedef struct clause_entry { @@ -731,7 +731,7 @@ static Int profend( USES_REGS1 ); static void clean_tree(rb_red_blk_node* node) { - if (node == ProfilerNil) + if (node == GLOBAL_ProfilerNil) return; clean_tree(node->left); clean_tree(node->right); @@ -740,18 +740,18 @@ clean_tree(rb_red_blk_node* node) { static void reset_tree(void) { - clean_tree(ProfilerRoot); - Yap_FreeCodeSpace((char *)ProfilerNil); - ProfilerNil = ProfilerRoot = NULL; - ProfCalls = ProfGCs = ProfHGrows = ProfSGrows = ProfMallocs = ProfOns = 0L; + clean_tree(GLOBAL_ProfilerRoot); + Yap_FreeCodeSpace((char *)GLOBAL_ProfilerNil); + GLOBAL_ProfilerNil = GLOBAL_ProfilerRoot = NULL; + GLOBAL_ProfCalls = GLOBAL_ProfGCs = GLOBAL_ProfHGrows = GLOBAL_ProfSGrows = GLOBAL_ProfMallocs = GLOBAL_ProfOns = 0L; } static int InitProfTree(void) { - if (ProfilerRoot) + if (GLOBAL_ProfilerRoot) reset_tree(); - while (!(ProfilerRoot = RBTreeCreate())) { + while (!(GLOBAL_ProfilerRoot = RBTreeCreate())) { if (!Yap_growheap(FALSE, 0, NULL)) { Yap_Error(OUT_OF_HEAP_ERROR, TermNil, "while initialisating profiler"); return FALSE; @@ -807,10 +807,10 @@ static void RemoveCode(CODEADDR clau) PredEntry *pp; UInt count; - if (!ProfilerRoot) return; + if (!GLOBAL_ProfilerRoot) return; if (!(x = RBExactQuery((yamop *)clau))) { /* send message */ - ProfOn = FALSE; + GLOBAL_ProfOn = FALSE; return; } pp = x->pe; @@ -823,7 +823,7 @@ static void RemoveCode(CODEADDR clau) node->pe = pp; node->pcs = count; /* send message */ - ProfOn = FALSE; + GLOBAL_ProfOn = FALSE; return; } else { node->pcs += count; @@ -872,7 +872,7 @@ showprofres( USES_REGS1 ) { } } fclose(FProf); - if (ProfCalls==0) + if (GLOBAL_ProfCalls==0) return TRUE; return TRUE; } @@ -909,7 +909,7 @@ p_test( USES_REGS1 ) { } } fclose(FProf); - if (ProfCalls==0) + if (GLOBAL_ProfCalls==0) return TRUE; return TRUE; } @@ -920,39 +920,40 @@ p_test( USES_REGS1 ) { static void prof_alrm(int signo, siginfo_t *si, void *scv) -{ +{ + CACHE_REGS void * oldpc=(void *) CONTEXT_PC(scv); yamop *current_p; - ProfCalls++; + GLOBAL_ProfCalls++; /* skip an interrupt */ - if (ProfOn) { - ProfOns++; + if (GLOBAL_ProfOn) { + GLOBAL_ProfOns++; return; } - ProfOn = TRUE; - if (Yap_PrologMode & TestMode) { - if (Yap_PrologMode & GCMode) { - ProfGCs++; - ProfOn = FALSE; + GLOBAL_ProfOn = TRUE; + if (LOCAL_PrologMode & TestMode) { + if (LOCAL_PrologMode & GCMode) { + GLOBAL_ProfGCs++; + GLOBAL_ProfOn = FALSE; return; } - if (Yap_PrologMode & MallocMode) { - ProfMallocs++; - ProfOn = FALSE; + if (LOCAL_PrologMode & MallocMode) { + GLOBAL_ProfMallocs++; + GLOBAL_ProfOn = FALSE; return; } - if (Yap_PrologMode & GrowHeapMode) { - ProfHGrows++; - ProfOn = FALSE; + if (LOCAL_PrologMode & GrowHeapMode) { + GLOBAL_ProfHGrows++; + GLOBAL_ProfOn = FALSE; return; } - if (Yap_PrologMode & GrowStackMode) { - ProfSGrows++; - ProfOn = FALSE; + if (LOCAL_PrologMode & GrowStackMode) { + GLOBAL_ProfSGrows++; + GLOBAL_ProfOn = FALSE; return; } @@ -987,34 +988,34 @@ prof_alrm(int signo, siginfo_t *si, void *scv) #if DEBUG fprintf(stderr,"Oops: %p, %p\n", oldpc, current_p); #endif - ProfOn = FALSE; + GLOBAL_ProfOn = FALSE; return; } #endif if (Yap_OffLineProfiler) { fprintf(FProf,"%p\n", current_p); - ProfOn = FALSE; + GLOBAL_ProfOn = FALSE; return; } LookupNode(current_p); - ProfOn = FALSE; + GLOBAL_ProfOn = FALSE; } void Yap_InformOfRemoval(CODEADDR clau) { - ProfOn = TRUE; + GLOBAL_ProfOn = TRUE; if (FPreds != NULL) { /* just store info about what is going on */ fprintf(FPreds,"-%p\n",clau); - ProfOn = FALSE; + GLOBAL_ProfOn = FALSE; return; } RemoveCode(clau); - ProfOn = FALSE; + GLOBAL_ProfOn = FALSE; } static Int profend( USES_REGS1 ); @@ -1024,25 +1025,25 @@ profnode( USES_REGS1 ) { Term t1 = Deref(ARG1), tleft, tright; rb_red_blk_node *node; - if (!ProfilerRoot) + if (!GLOBAL_ProfilerRoot) return FALSE; if (!(node = (rb_red_blk_node *)IntegerOfTerm(t1))) - node = ProfilerRoot; + node = GLOBAL_ProfilerRoot; /* if (node->key) fprintf(stderr,"%p: %p,%p,%d,%p(%d),%p,%p\n",node,node->key,node->lim,node->pcs,node->pe,node->pe->ArityOfPE,node->right,node->left); */ - if (node->left == ProfilerNil) { + if (node->left == GLOBAL_ProfilerNil) { tleft = TermNil; } else { tleft = MkIntegerTerm((Int)node->left); } - if (node->left == ProfilerNil) { + if (node->left == GLOBAL_ProfilerNil) { tleft = TermNil; } else { tleft = MkIntegerTerm((Int)node->left); } - if (node->right == ProfilerNil) { + if (node->right == GLOBAL_ProfilerNil) { tright = TermNil; } else { tright = MkIntegerTerm((Int)node->right); @@ -1058,12 +1059,12 @@ profnode( USES_REGS1 ) { static Int profglobs( USES_REGS1 ) { return - Yap_unify(ARG1,MkIntegerTerm(ProfCalls)) && - Yap_unify(ARG2,MkIntegerTerm(ProfGCs)) && - Yap_unify(ARG3,MkIntegerTerm(ProfHGrows)) && - Yap_unify(ARG4,MkIntegerTerm(ProfSGrows)) && - Yap_unify(ARG5,MkIntegerTerm(ProfMallocs)) && - Yap_unify(ARG6,MkIntegerTerm(ProfOns)) ; + Yap_unify(ARG1,MkIntegerTerm(GLOBAL_ProfCalls)) && + Yap_unify(ARG2,MkIntegerTerm(GLOBAL_ProfGCs)) && + Yap_unify(ARG3,MkIntegerTerm(GLOBAL_ProfHGrows)) && + Yap_unify(ARG4,MkIntegerTerm(GLOBAL_ProfSGrows)) && + Yap_unify(ARG5,MkIntegerTerm(GLOBAL_ProfMallocs)) && + Yap_unify(ARG6,MkIntegerTerm(GLOBAL_ProfOns)) ; } static Int @@ -1169,14 +1170,14 @@ static Int profoff( USES_REGS1 ) { return FALSE; } -static Int profon( USES_REGS1 ) { +static Int ProfOn( USES_REGS1 ) { Term p; profoff( PASS_REGS1 ); p=Deref(ARG1); return(start_profilers(IntOfTerm(p))); } -static Int profon0( USES_REGS1 ) { +static Int ProfOn0( USES_REGS1 ) { profoff( PASS_REGS1 ); return(start_profilers(TIMER_DEFAULT)); } @@ -1187,7 +1188,7 @@ static Int profison( USES_REGS1 ) { static Int profalt( USES_REGS1 ) { if (ProfilerOn==0) return(FALSE); - if (ProfilerOn==-1) return profon( PASS_REGS1 ); + if (ProfilerOn==-1) return ProfOn( PASS_REGS1 ); return profoff( PASS_REGS1 ); } @@ -1248,15 +1249,15 @@ void Yap_InitLowProf(void) { #if LOW_PROF - ProfCalls = 0; + GLOBAL_ProfCalls = 0; ProfilerOn = FALSE; Yap_OffLineProfiler = FALSE; Yap_InitCPred("profinit",0, profinit, SafePredFlag); Yap_InitCPred("profinit",1, profinit1, SafePredFlag); Yap_InitCPred("$proftype",1, proftype, SafePredFlag); Yap_InitCPred("profend" ,0, profend, SafePredFlag); - Yap_InitCPred("profon" , 0, profon0, SafePredFlag); - Yap_InitCPred("profon" , 1, profon, SafePredFlag); + Yap_InitCPred("ProfOn" , 0, ProfOn0, SafePredFlag); + Yap_InitCPred("ProfOn" , 1, ProfOn, SafePredFlag); Yap_InitCPred("profoff", 0, profoff, SafePredFlag); Yap_InitCPred("profalt", 0, profalt, SafePredFlag); Yap_InitCPred("$offline_showprofres", 0, profres0, SafePredFlag); diff --git a/C/grow.c b/C/grow.c index 2f146a0c6..72a34cb89 100755 --- a/C/grow.c +++ b/C/grow.c @@ -42,20 +42,7 @@ typedef enum { STACK_INCREMENTAL_COPYING = 2 } what_stack_copying; -static int heap_overflows = 0; -static Int total_heap_overflow_time = 0; -int stack_overflows = 0; -static Int total_stack_overflow_time = 0; - -int delay_overflows = 0; -static Int total_delay_overflow_time = 0; - -static int trail_overflows = 0; -static Int total_trail_overflow_time = 0; - -static int atom_table_overflows = 0; -static Int total_atom_table_overflow_time = 0; STATIC_PROTO(Int p_growheap, ( USES_REGS1 )); STATIC_PROTO(Int p_growstack, ( USES_REGS1 )); @@ -85,10 +72,11 @@ STATIC_PROTO(Term AdjustGlobTerm, (Term CACHE_TYPE)); static void LeaveGrowMode(prolog_exec_mode grow_mode) { - Yap_PrologMode &= ~grow_mode; - if (Yap_PrologMode & AbortMode) { + CACHE_REGS + LOCAL_PrologMode &= ~grow_mode; + if (LOCAL_PrologMode & AbortMode) { CACHE_REGS - Yap_PrologMode &= ~AbortMode; + LOCAL_PrologMode &= ~AbortMode; Yap_Error(PURE_ABORT, TermNil, ""); /* in case someone mangles the P register */ save_machine_regs(); @@ -98,7 +86,7 @@ LeaveGrowMode(prolog_exec_mode grow_mode) #if PUSH_REGS restore_absmi_regs(&Yap_standard_regs); #endif - siglongjmp (Yap_RestartEnv, 1); + siglongjmp (LOCAL_RestartEnv, 1); #endif } } @@ -121,27 +109,27 @@ static void SetHeapRegs(int copying_threads USES_REGS) { #ifdef undf7 - fprintf(Yap_stderr,"HeapBase = %x\tHeapTop=%x\nGlobalBase=%x\tGlobalTop=%x\nLocalBase=%x\tLocatTop=%x\n", Yap_HeapBase, HeapTop, Yap_GlobalBase, H, LCL0, ASP); + fprintf(GLOBAL_stderr,"HeapBase = %x\tHeapTop=%x\nGlobalBase=%x\tGlobalTop=%x\nLocalBase=%x\tLocatTop=%x\n", Yap_HeapBase, HeapTop, LOCAL_GlobalBase, H, LCL0, ASP); #endif /* The old stack pointers */ - OldLCL0 = LCL0; - OldASP = ASP; - OldGlobalBase = (CELL *)Yap_GlobalBase; - OldH = H; - OldH0 = H0; - OldTrailBase = Yap_TrailBase; - OldTrailTop = Yap_TrailTop; - OldTR = TR; - OldHeapBase = Yap_HeapBase; - OldHeapTop = HeapTop; + LOCAL_OldLCL0 = LCL0; + LOCAL_OldASP = ASP; + LOCAL_OldGlobalBase = (CELL *)LOCAL_GlobalBase; + LOCAL_OldH = H; + LOCAL_OldH0 = H0; + LOCAL_OldTrailBase = LOCAL_TrailBase; + LOCAL_OldTrailTop = LOCAL_TrailTop; + LOCAL_OldTR = TR; + LOCAL_OldHeapBase = Yap_HeapBase; + LOCAL_OldHeapTop = HeapTop; /* Adjust stack addresses */ - Yap_TrailBase = TrailAddrAdjust(Yap_TrailBase); - Yap_TrailTop = TrailAddrAdjust(Yap_TrailTop); - if (GDiff) { + LOCAL_TrailBase = TrailAddrAdjust(LOCAL_TrailBase); + LOCAL_TrailTop = TrailAddrAdjust(LOCAL_TrailTop); + if (LOCAL_GDiff) { /* make sure we are not just expanding the delay stack */ - Yap_GlobalBase = BaseAddrAdjust(Yap_GlobalBase); + LOCAL_GlobalBase = BaseAddrAdjust(LOCAL_GlobalBase); } - Yap_LocalBase = LocalAddrAdjust(Yap_LocalBase); + LOCAL_LocalBase = LocalAddrAdjust(LOCAL_LocalBase); #if !USE_SYSTEM_MALLOC && !USE_DL_MALLOC AuxSp = PtoBaseAdjust(AuxSp); AuxTop = (ADDR)PtoBaseAdjust((CELL *)AuxTop); @@ -157,10 +145,10 @@ SetHeapRegs(int copying_threads USES_REGS) ASP = PtoLocAdjust(ASP); if (H0) H0 = PtoGloAdjust(H0); - LOCK(SignalLock); + LOCK(LOCAL_SignalLock); if (LCL0) LCL0 = PtoLocAdjust(LCL0); - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); if (H) H = PtoGloAdjust(H); #ifdef CUT_C @@ -190,17 +178,17 @@ SetHeapRegs(int copying_threads USES_REGS) else if (IsOldLocalPtr(S)) S = PtoLocAdjust(S); if (!copying_threads) { - if (GlobalArena) - GlobalArena = AbsAppl(PtoGloAdjust(RepAppl(GlobalArena))); + if (LOCAL_GlobalArena) + LOCAL_GlobalArena = AbsAppl(PtoGloAdjust(RepAppl(LOCAL_GlobalArena))); } #ifdef COROUTINING - if (AttsMutableList) - AttsMutableList = AbsAppl(PtoGloAdjust(RepAppl(AttsMutableList))); - if (WokenGoals) - WokenGoals = AbsAppl(PtoGloAdjust(RepAppl(WokenGoals))); + if (LOCAL_AttsMutableList) + LOCAL_AttsMutableList = AbsAppl(PtoGloAdjust(RepAppl(LOCAL_AttsMutableList))); + if (LOCAL_WokenGoals) + LOCAL_WokenGoals = AbsAppl(PtoGloAdjust(RepAppl(LOCAL_WokenGoals))); #endif - GcGeneration = AbsAppl(PtoGloAdjust(RepAppl(GcGeneration))); - GcPhase = AbsAppl(PtoGloAdjust(RepAppl(GcPhase))); + LOCAL_GcGeneration = AbsAppl(PtoGloAdjust(RepAppl(LOCAL_GcGeneration))); + LOCAL_GcPhase = AbsAppl(PtoGloAdjust(RepAppl(LOCAL_GcPhase))); } static void @@ -208,9 +196,9 @@ MoveLocalAndTrail( USES_REGS1 ) { /* cpcellsd(To,From,NOfCells) - copy the cells downwards */ #if USE_SYSTEM_MALLOC - cpcellsd(ASP, (CELL *)((char *)OldASP+BaseDiff), (CELL *)OldTR - OldASP); + cpcellsd(ASP, (CELL *)((char *)LOCAL_OldASP+LOCAL_BaseDiff), (CELL *)LOCAL_OldTR - LOCAL_OldASP); #else - cpcellsd(ASP, OldASP, (CELL *)OldTR - OldASP); + cpcellsd(ASP, LOCAL_OldASP, (CELL *)LOCAL_OldTR - LOCAL_OldASP); #endif } @@ -221,7 +209,7 @@ CopyLocalAndTrail( USES_REGS1 ) { /* cpcellsd(To,From,NOfCells) - copy the cells downwards */ #if USE_SYSTEM_MALLOC - cpcellsd((void *)ASP, (void *)OldASP, (CELL *)OldTR - OldASP); + cpcellsd((void *)ASP, (void *)LOCAL_OldASP, (CELL *)LOCAL_OldTR - LOCAL_OldASP); #endif } @@ -245,11 +233,11 @@ worker_p_binding(int worker_p, CELL *aux_ptr) { CACHE_REGS if (aux_ptr > H) { - CELL reg = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->LCL0_[aux_ptr-LCL0]; + CELL reg = REMOTE_ThreadHandle(worker_p).current_yaam_regs->LCL0_[aux_ptr-LCL0]; reg = AdjustGlobTerm(reg PASS_REGS); return reg; } else { - CELL reg = FOREIGN_ThreadHandle(worker_p).current_yaam_regs-> H0_[aux_ptr-H0]; + CELL reg = REMOTE_ThreadHandle(worker_p).current_yaam_regs-> H0_[aux_ptr-H0]; reg = AdjustGlobTerm(reg PASS_REGS); return reg; } @@ -275,7 +263,7 @@ RestoreTrail(int worker_p USES_REGS) if (IsVarTerm(aux_cell)) { if (aux_cell < LOCAL_start_global_copy || EQUAL_OR_YOUNGER_CP((choiceptr)LOCAL_end_local_copy, (choiceptr)aux_cell)) { YAPOR_ERROR_CHECKING((CELL *)aux_cell < H0, "RestoreTrail: aux_cell < H0"); - YAPOR_ERROR_CHECKING((ADDR)aux_cell > Yap_LocalBase, "RestoreTrail: aux_cell > LocalBase"); + YAPOR_ERROR_CHECKING((ADDR)aux_cell > LOCAL_LocalBase, "RestoreTrail: aux_cell > LocalBase"); #ifdef TABLING *((CELL *) aux_cell) = TrailVal(aux_tr); #else @@ -286,7 +274,7 @@ RestoreTrail(int worker_p USES_REGS) } else if (IsPairTerm(aux_cell)) { /* avoid frozen segments */ aux_cell = (CELL) RepPair(aux_cell); - if (IN_BETWEEN(Yap_TrailBase, aux_cell, Yap_TrailTop)) { + if (IN_BETWEEN(LOCAL_TrailBase, aux_cell, LOCAL_TrailTop)) { aux_tr = (tr_fr_ptr) aux_cell; } #endif /* TABLING */ @@ -319,7 +307,7 @@ MoveGlobal( USES_REGS1 ) * cpcellsd(To,From,NOfCells) - copy the cells downwards - in * absmi.asm */ - cpcellsd((CELL *)Yap_GlobalBase, (CELL *)OldGlobalBase, OldH - (CELL *)OldGlobalBase); + cpcellsd((CELL *)LOCAL_GlobalBase, (CELL *)LOCAL_OldGlobalBase, LOCAL_OldH - (CELL *)LOCAL_OldGlobalBase); } static void @@ -329,7 +317,7 @@ MoveExpandedGlobal( USES_REGS1 ) * cpcellsd(To,From,NOfCells) - copy the cells downwards - in * absmi.asm */ - cpcellsd((CELL *)(Yap_GlobalBase+(GDiff-BaseDiff)), (CELL *)Yap_GlobalBase, OldH - (CELL *)OldGlobalBase); + cpcellsd((CELL *)(LOCAL_GlobalBase+(LOCAL_GDiff-LOCAL_BaseDiff)), (CELL *)LOCAL_GlobalBase, LOCAL_OldH - (CELL *)LOCAL_OldGlobalBase); } static void @@ -340,9 +328,9 @@ MoveGlobalWithHole( USES_REGS1 ) * absmi.asm */ #if USE_SYSTEM_MALLOC - cpcellsd((CELL *)((char *)Yap_GlobalBase+(GDiff0-BaseDiff)), (CELL *)Yap_GlobalBase, OldH - (CELL *)OldGlobalBase); + cpcellsd((CELL *)((char *)LOCAL_GlobalBase+(LOCAL_GDiff0-LOCAL_BaseDiff)), (CELL *)LOCAL_GlobalBase, LOCAL_OldH - (CELL *)LOCAL_OldGlobalBase); #else - cpcellsd((CELL *)((char *)OldGlobalBase+GDiff0), (CELL *)OldGlobalBase, OldH - (CELL *)OldGlobalBase); + cpcellsd((CELL *)((char *)LOCAL_OldGlobalBase+LOCAL_GDiff0), (CELL *)LOCAL_OldGlobalBase, LOCAL_OldH - (CELL *)LOCAL_OldGlobalBase); #endif } @@ -353,9 +341,9 @@ MoveHalfGlobal(CELL *OldPt USES_REGS) * cpcellsd(To,From,NOfCells) - copy the cells downwards - in * absmi.asm */ - UInt diff = OldH-OldPt; - CELL *NewPt = (CELL *)((char*)OldPt+GDiff); - CELL *IntPt = (CELL *)((char*)OldPt+GDiff0); + UInt diff = LOCAL_OldH-OldPt; + CELL *NewPt = (CELL *)((char*)OldPt+LOCAL_GDiff); + CELL *IntPt = (CELL *)((char*)OldPt+LOCAL_GDiff0); cpcellsd(NewPt, IntPt, diff); } @@ -373,7 +361,7 @@ AdjustAppl(register CELL t0 USES_REGS) #ifdef DEBUG else { /* strange cell */ - /* fprintf(Yap_stderr,"% garbage appl %lx found in stacks by stack shifter\n", t0);*/ + /* fprintf(GLOBAL_stderr,"% garbage appl %lx found in stacks by stack shifter\n", t0);*/ } #endif return(t0); @@ -391,7 +379,7 @@ AdjustPair(register CELL t0 USES_REGS) else if (IsHeapP(t)) return (AbsPair(CellPtoHeapAdjust(t))); #ifdef DEBUG - /* fprintf(Yap_stderr,"% garbage pair %lx found in stacks by stack shifter\n", t0);*/ + /* fprintf(GLOBAL_stderr,"% garbage pair %lx found in stacks by stack shifter\n", t0);*/ #endif return(t0); } @@ -399,7 +387,7 @@ AdjustPair(register CELL t0 USES_REGS) static void AdjustTrail(int adjusting_heap, int thread_copying USES_REGS) { - volatile tr_fr_ptr ptt, tr_base = (tr_fr_ptr)Yap_TrailBase; + volatile tr_fr_ptr ptt, tr_base = (tr_fr_ptr)LOCAL_TrailBase; #if defined(YAPOR_THREADS) if (thread_copying == STACK_INCREMENTAL_COPYING) { @@ -518,9 +506,9 @@ static void AdjustGlobal(long sz, int thread_copying USES_REGS) { CELL *pt, *pt_max; - ArrayEntry *al = DynamicArrays; - StaticArrayEntry *sal = StaticArrays; - GlobalEntry *gl = GlobalVariables; + ArrayEntry *al = LOCAL_DynamicArrays; + StaticArrayEntry *sal = LOCAL_StaticArrays; + GlobalEntry *gl = LOCAL_GlobalVariables; while (al) { al->ValueOfVE = AdjustGlobTerm(al->ValueOfVE PASS_REGS); @@ -736,10 +724,10 @@ AdjustScannerStacks(TokEntry **tksp, VarEntry **vep USES_REGS) ves = *vep = (VarEntry *)TrailAddrAdjust((ADDR)ves); AdjustVarTable(ves PASS_REGS); } - ves = Yap_AnonVarTable; + ves = LOCAL_AnonVarTable; if (ves != NULL) { if (IsOldVarTableTrailPtr(ves)) - ves = Yap_AnonVarTable = VarEntryAdjust(ves); + ves = LOCAL_AnonVarTable = VarEntryAdjust(ves); } while (ves != NULL) { VarEntry *vetmp = ves->VarLeft; @@ -773,47 +761,47 @@ static_growheap(long size, int fix_code, struct intermediates *cip, tr_fr_ptr *o if (size < YAP_ALLOC_SIZE) size = YAP_ALLOC_SIZE; size = AdjustPageSize(size); - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; if (!Yap_ExtendWorkSpace(size)) { - Int min_size = AdjustPageSize(((CELL)Yap_TrailTop-(CELL)Yap_GlobalBase)+MinHeapGap); + Int min_size = AdjustPageSize(((CELL)LOCAL_TrailTop-(CELL)LOCAL_GlobalBase)+MinHeapGap); - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; if (size < min_size) size = min_size; minimal_request = size; size = Yap_ExtendWorkSpaceThroughHole(size); if (size < 0) { - Yap_ErrorMessage = "Database crashed against Stacks"; + LOCAL_ErrorMessage = "Database crashed against Stacks"; return FALSE; } } start_growth_time = Yap_cputime(); gc_verbose = Yap_is_gc_verbose(); - heap_overflows++; + LOCAL_heap_overflows++; if (gc_verbose) { #if defined(YAPOR_THREADS) - fprintf(Yap_stderr, "%% Worker Id %d:\n", worker_id); + fprintf(GLOBAL_stderr, "%% Worker Id %d:\n", worker_id); #endif - fprintf(Yap_stderr, "%% Database Overflow %d\n", heap_overflows); - fprintf(Yap_stderr, "%% growing the heap %ld bytes\n", size); + fprintf(GLOBAL_stderr, "%% Database Overflow %d\n", LOCAL_heap_overflows); + fprintf(GLOBAL_stderr, "%% growing the heap %ld bytes\n", size); } /* CreepFlag is set to force heap expansion */ - if (ActiveSignals == YAP_CDOVF_SIGNAL) { - LOCK(SignalLock); + if (LOCAL_ActiveSignals == YAP_CDOVF_SIGNAL) { + LOCK(LOCAL_SignalLock); CreepFlag = CalculateStackGap(); - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); } ASP -= 256; YAPEnterCriticalSection(); - TrDiff = LDiff = GDiff = GDiff0 = DelayDiff = BaseDiff = size; - XDiff = HDiff = 0; - GSplit = NULL; + LOCAL_TrDiff = LOCAL_LDiff = LOCAL_GDiff = LOCAL_GDiff0 = LOCAL_DelayDiff = LOCAL_BaseDiff = size; + LOCAL_XDiff = LOCAL_HDiff = 0; + LOCAL_GSplit = NULL; SetHeapRegs(FALSE PASS_REGS); MoveLocalAndTrail( PASS_REGS1 ); if (fix_code) { - CELL *SaveOldH = OldH; - OldH = (CELL *)cip->freep; + CELL *SaveOldH = LOCAL_OldH; + LOCAL_OldH = (CELL *)cip->freep; MoveGlobal( PASS_REGS1 ); - OldH = SaveOldH; + LOCAL_OldH = SaveOldH; } else { MoveGlobal( PASS_REGS1 ); } @@ -835,10 +823,10 @@ static_growheap(long size, int fix_code, struct intermediates *cip, tr_fr_ptr *o if (minimal_request) Yap_AllocHole(minimal_request, size); growth_time = Yap_cputime()-start_growth_time; - total_heap_overflow_time += growth_time; + LOCAL_total_heap_overflow_time += growth_time; if (gc_verbose) { - fprintf(Yap_stderr, "%% took %g sec\n", (double)growth_time/1000); - fprintf(Yap_stderr, "%% Total of %g sec expanding Database\n", (double)total_heap_overflow_time/1000); + fprintf(GLOBAL_stderr, "%% took %g sec\n", (double)growth_time/1000); + fprintf(GLOBAL_stderr, "%% Total of %g sec expanding Database\n", (double)LOCAL_total_heap_overflow_time/1000); } return(TRUE); } @@ -851,7 +839,7 @@ static_growglobal(long request, CELL **ptr, CELL *hsplit USES_REGS) UInt start_growth_time, growth_time; int gc_verbose; char *omax = (char *)H0; - ADDR old_GlobalBase = Yap_GlobalBase; + ADDR old_GlobalBase = LOCAL_GlobalBase; UInt minimal_request = 0L; long size = request; char vb_msg1 = '\0', *vb_msg2; @@ -867,10 +855,10 @@ static_growglobal(long request, CELL **ptr, CELL *hsplit USES_REGS) if (hsplit) { /* just a little bit of sanity checking */ - if (hsplit < H0 && hsplit > (CELL *)Yap_GlobalBase) { + if (hsplit < H0 && hsplit > (CELL *)LOCAL_GlobalBase) { insert_in_delays = TRUE; /* expanding attributed variables */ - if (omax - size > Yap_GlobalBase+4096*sizeof(CELL)) { + if (omax - size > LOCAL_GlobalBase+4096*sizeof(CELL)) { /* we can just ask for more room */ size = 0; do_grow = FALSE; @@ -899,30 +887,30 @@ static_growglobal(long request, CELL **ptr, CELL *hsplit USES_REGS) size = AdjustPageSize(size); } /* adjust to a multiple of 256) */ - Yap_ErrorMessage = NULL; - Yap_PrologMode |= GrowStackMode; + LOCAL_ErrorMessage = NULL; + LOCAL_PrologMode |= GrowStackMode; start_growth_time = Yap_cputime(); if (do_grow) { - if (!Yap_AllowGlobalExpansion) { - Yap_ErrorMessage = "Global Stack crashed against Local Stack"; + if (!GLOBAL_AllowGlobalExpansion) { + LOCAL_ErrorMessage = "Global Stack crashed against Local Stack"; LeaveGrowMode(GrowStackMode); return 0; } - if (!Yap_AllowGlobalExpansion || !Yap_ExtendWorkSpace(size)) { + if (!GLOBAL_AllowGlobalExpansion || !Yap_ExtendWorkSpace(size)) { /* always fails when using malloc */ - Yap_ErrorMessage = NULL; - size += AdjustPageSize(((CELL)Yap_TrailTop-(CELL)Yap_GlobalBase)+MinHeapGap); + LOCAL_ErrorMessage = NULL; + size += AdjustPageSize(((CELL)LOCAL_TrailTop-(CELL)LOCAL_GlobalBase)+MinHeapGap); minimal_request = size; size = Yap_ExtendWorkSpaceThroughHole(size); if (size < 0) { - Yap_ErrorMessage = "Global Stack crashed against Local Stack"; + LOCAL_ErrorMessage = "Global Stack crashed against Local Stack"; LeaveGrowMode(GrowStackMode); return 0; } } } gc_verbose = Yap_is_gc_verbose(); - delay_overflows++; + LOCAL_delay_overflows++; if (gc_verbose) { if (hsplit) { if (hsplit > H0) { @@ -937,10 +925,10 @@ static_growglobal(long request, CELL **ptr, CELL *hsplit USES_REGS) vb_msg2 = "Delay"; } #if defined(YAPOR_THREADS) - fprintf(Yap_stderr, "%% Worker Id %d:\n", worker_id); + fprintf(GLOBAL_stderr, "%% Worker Id %d:\n", worker_id); #endif - fprintf(Yap_stderr, "%% %cO %s Overflow %d\n", vb_msg1, vb_msg2, delay_overflows); - fprintf(Yap_stderr, "%% %cO growing the stacks %ld bytes\n", vb_msg1, size); + fprintf(GLOBAL_stderr, "%% %cO %s Overflow %d\n", vb_msg1, vb_msg2, LOCAL_delay_overflows); + fprintf(GLOBAL_stderr, "%% %cO growing the stacks %ld bytes\n", vb_msg1, size); } ASP -= 256; YAPEnterCriticalSection(); @@ -949,41 +937,41 @@ static_growglobal(long request, CELL **ptr, CELL *hsplit USES_REGS) /* we got over a hole */ if (minimal_request) { /* we went over a hole */ - BaseDiff = size+((CELL)Yap_TrailTop-(CELL)Yap_GlobalBase)-minimal_request; - LDiff = TrDiff = size; + LOCAL_BaseDiff = size+((CELL)LOCAL_TrailTop-(CELL)LOCAL_GlobalBase)-minimal_request; + LOCAL_LDiff = LOCAL_TrDiff = size; } else { /* we may still have an overflow */ - BaseDiff = Yap_GlobalBase - old_GlobalBase; + LOCAL_BaseDiff = LOCAL_GlobalBase - old_GlobalBase; /* if we grow, we need to move the stacks */ - LDiff = TrDiff = BaseDiff+size; + LOCAL_LDiff = LOCAL_TrDiff = LOCAL_BaseDiff+size; } } else { /* stay still */ - LDiff = TrDiff = 0; - BaseDiff = 0; + LOCAL_LDiff = LOCAL_TrDiff = 0; + LOCAL_BaseDiff = 0; } /* now, remember we have delay -- global with a hole in delay or a hole in global */ if (!hsplit) { if (!do_grow) { - DelayDiff = GDiff = GDiff0 = size; + LOCAL_DelayDiff = LOCAL_GDiff = LOCAL_GDiff0 = size; request = 0L; } else { /* expand delay stack */ - DelayDiff = GDiff = GDiff0 = LDiff; + LOCAL_DelayDiff = LOCAL_GDiff = LOCAL_GDiff0 = LOCAL_LDiff; } } else if (insert_in_delays) { /* we want to expand a hole for the delay stack */ - DelayDiff = size-request; - GDiff = GDiff0 = size; + LOCAL_DelayDiff = size-request; + LOCAL_GDiff = LOCAL_GDiff0 = size; } else { /* we want to expand a hole for the delay stack */ - GDiff0 = DelayDiff = BaseDiff; - GDiff = BaseDiff+request; + LOCAL_GDiff0 = LOCAL_DelayDiff = LOCAL_BaseDiff; + LOCAL_GDiff = LOCAL_BaseDiff+request; } - GSplit = hsplit; - XDiff = HDiff = 0; - Yap_GlobalBase = old_GlobalBase; + LOCAL_GSplit = hsplit; + LOCAL_XDiff = LOCAL_HDiff = 0; + LOCAL_GlobalBase = old_GlobalBase; SetHeapRegs(FALSE PASS_REGS); if (do_grow) { MoveLocalAndTrail( PASS_REGS1 ); @@ -996,7 +984,7 @@ static_growglobal(long request, CELL **ptr, CELL *hsplit USES_REGS) MoveExpandedGlobal( PASS_REGS1 ); } /* don't run through garbage */ - if (hsplit && (OldH != hsplit)) { + if (hsplit && (LOCAL_OldH != hsplit)) { AdjustStacksAndTrail(request, FALSE PASS_REGS); } else { AdjustStacksAndTrail(0, FALSE PASS_REGS); @@ -1008,7 +996,7 @@ static_growglobal(long request, CELL **ptr, CELL *hsplit USES_REGS) if (hsplit) { if (insert_in_delays) { /* we have things not quite where we want to have them */ - cpcellsd((CELL *)(omax+DelayDiff), (CELL *)(omax+GDiff0), (ADDR)hsplit-omax); + cpcellsd((CELL *)(omax+LOCAL_DelayDiff), (CELL *)(omax+LOCAL_GDiff0), (ADDR)hsplit-omax); } else { MoveHalfGlobal(hsplit PASS_REGS); } @@ -1019,16 +1007,16 @@ static_growglobal(long request, CELL **ptr, CELL *hsplit USES_REGS) Yap_AllocHole(minimal_request, size); } growth_time = Yap_cputime()-start_growth_time; - total_delay_overflow_time += growth_time; + LOCAL_total_delay_overflow_time += growth_time; if (gc_verbose) { - fprintf(Yap_stderr, "%% %cO took %g sec\n", vb_msg1, (double)growth_time/1000); - fprintf(Yap_stderr, "%% %cO Total of %g sec expanding stacks \n", vb_msg1, (double)total_delay_overflow_time/1000); + fprintf(GLOBAL_stderr, "%% %cO took %g sec\n", vb_msg1, (double)growth_time/1000); + fprintf(GLOBAL_stderr, "%% %cO Total of %g sec expanding stacks \n", vb_msg1, (double)LOCAL_total_delay_overflow_time/1000); } LeaveGrowMode(GrowStackMode); if (hsplit) { return request; } else - return GDiff-BaseDiff; + return LOCAL_GDiff-LOCAL_BaseDiff; } static void @@ -1246,7 +1234,7 @@ static int do_growheap(int fix_code, UInt in_size, struct intermediates *cip, tr_fr_ptr *old_trp, TokEntry **tksp, VarEntry **vep USES_REGS) { unsigned long size = sizeof(CELL) * K16; - int shift_factor = (heap_overflows > 8 ? 8 : heap_overflows); + int shift_factor = (LOCAL_heap_overflows > 8 ? 8 : LOCAL_heap_overflows); unsigned long sz = size << shift_factor; if (sz < in_size) { @@ -1256,10 +1244,10 @@ do_growheap(int fix_code, UInt in_size, struct intermediates *cip, tr_fr_ptr *ol Yap_Error(OUT_OF_HEAP_ERROR,TermNil,"cannot grow Heap: more than a worker/thread running"); return FALSE; #endif - if (Yap_SizeOfOverflow > sz) { + if (GLOBAL_SizeOfOverflow > sz) { if (size < YAP_ALLOC_SIZE) size = YAP_ALLOC_SIZE; - sz = AdjustPageSize(Yap_SizeOfOverflow); + sz = AdjustPageSize(GLOBAL_SizeOfOverflow); } while(sz >= sizeof(CELL) * K16 && !static_growheap(sz, fix_code, cip, old_trp, tksp, vep PASS_REGS)) { size = size/2; @@ -1287,11 +1275,11 @@ do_growheap(int fix_code, UInt in_size, struct intermediates *cip, tr_fr_ptr *ol fix_tabling_info( PASS_REGS1 ); #endif /* TABLING */ if (sz >= sizeof(CELL) * K16) { - LOCK(SignalLock); - ActiveSignals &= ~YAP_CDOVF_SIGNAL; - if (!ActiveSignals) + LOCK(LOCAL_SignalLock); + LOCAL_ActiveSignals &= ~YAP_CDOVF_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return TRUE; } /* failed */ @@ -1342,12 +1330,12 @@ growatomtable( USES_REGS1 ) UInt start_growth_time = Yap_cputime(), growth_time; int gc_verbose = Yap_is_gc_verbose(); - LOCK(SignalLock); - if (ActiveSignals == YAP_CDOVF_SIGNAL) { + LOCK(LOCAL_SignalLock); + if (LOCAL_ActiveSignals == YAP_CDOVF_SIGNAL) { CreepFlag = CalculateStackGap(); } - ActiveSignals &= ~YAP_CDOVF_SIGNAL; - UNLOCK(SignalLock); + LOCAL_ActiveSignals &= ~YAP_CDOVF_SIGNAL; + UNLOCK(LOCAL_SignalLock); while ((ntb = (AtomHashEntry *)Yap_AllocCodeSpace(nsize*sizeof(AtomHashEntry))) == NULL) { /* leave for next time */ #if !USE_SYSTEM_MALLOC @@ -1355,13 +1343,13 @@ growatomtable( USES_REGS1 ) #endif return FALSE; } - atom_table_overflows++; + LOCAL_atom_table_overflows ++; if (gc_verbose) { #if defined(YAPOR_THREADS) - fprintf(Yap_stderr, "%% Worker Id %d:\n", worker_id); + fprintf(GLOBAL_stderr, "%% Worker Id %d:\n", worker_id); #endif - fprintf(Yap_stderr, "%% Atom Table Overflow %d\n", atom_table_overflows); - fprintf(Yap_stderr, "%% growing the atom table to %ld entries\n", (long int)(nsize)); + fprintf(GLOBAL_stderr, "%% Atom Table Overflow %d\n", LOCAL_atom_table_overflows ); + fprintf(GLOBAL_stderr, "%% growing the atom table to %ld entries\n", (long int)(nsize)); } YAPEnterCriticalSection(); init_new_table(ntb, nsize); @@ -1371,10 +1359,10 @@ growatomtable( USES_REGS1 ) AtomHashTableSize = nsize; YAPLeaveCriticalSection(); growth_time = Yap_cputime()-start_growth_time; - total_atom_table_overflow_time += growth_time; + LOCAL_total_atom_table_overflow_time += growth_time; if (gc_verbose) { - fprintf(Yap_stderr, "%% took %g sec\n", (double)growth_time/1000); - fprintf(Yap_stderr, "%% Total of %g sec expanding atom table \n", (double)total_atom_table_overflow_time/1000); + fprintf(GLOBAL_stderr, "%% took %g sec\n", (double)growth_time/1000); + fprintf(GLOBAL_stderr, "%% Total of %g sec expanding atom table \n", (double)LOCAL_total_atom_table_overflow_time/1000); } #if USE_SYSTEM_MALLOC return TRUE; @@ -1401,19 +1389,19 @@ Yap_growheap(int fix_code, UInt in_size, void *cip) if (NOfAtoms > 2*AtomHashTableSize) { UInt n = NOfAtoms; - if (Yap_AGcThreshold) + if (GLOBAL_AGcThreshold) Yap_atom_gc( PASS_REGS1 ); /* check if we have a significant improvement from agc */ if (n > NOfAtoms+ NOfAtoms/10 || NOfAtoms > 2*AtomHashTableSize) { res = growatomtable( PASS_REGS1 ); } else { - LOCK(SignalLock); - if (ActiveSignals == YAP_CDOVF_SIGNAL) { + LOCK(LOCAL_SignalLock); + if (LOCAL_ActiveSignals == YAP_CDOVF_SIGNAL) { CreepFlag = CalculateStackGap(); } - ActiveSignals &= ~YAP_CDOVF_SIGNAL; - UNLOCK(SignalLock); + LOCAL_ActiveSignals &= ~YAP_CDOVF_SIGNAL; + UNLOCK(LOCAL_SignalLock); return TRUE; } LeaveGrowMode(GrowHeapMode); @@ -1442,12 +1430,12 @@ Yap_growglobal(CELL **ptr) unsigned long sz = sizeof(CELL) * K16; #if defined(YAPOR_THREADS) - if (Yap_number_workers != 1) { + if (GLOBAL_number_workers != 1) { Yap_Error(OUT_OF_STACK_ERROR,TermNil,"cannot grow Global: more than a worker/thread running"); return(FALSE); } #elif defined(THREADS) - if (Yap_NOfThreads != 1) { + if (GLOBAL_NOfThreads != 1) { Yap_Error(OUT_OF_STACK_ERROR,TermNil,"cannot grow Global: more than a worker/thread running"); return(FALSE); } @@ -1480,7 +1468,7 @@ Yap_growstack(long size) CACHE_REGS int res; - Yap_PrologMode |= GrowStackMode; + LOCAL_PrologMode |= GrowStackMode; res=growstack(size PASS_REGS); LeaveGrowMode(GrowStackMode); return res; @@ -1491,58 +1479,58 @@ execute_growstack(long size0, int from_trail, int in_parser, tr_fr_ptr *old_trp, { UInt minimal_request = 0L; long size = size0; - ADDR old_Yap_GlobalBase = Yap_GlobalBase; + ADDR old_LOCAL_GlobalBase = LOCAL_GlobalBase; - if (!Yap_AllowGlobalExpansion) { - Yap_ErrorMessage = "Database crashed against stacks"; + if (!GLOBAL_AllowGlobalExpansion) { + LOCAL_ErrorMessage = "Database crashed against stacks"; return FALSE; } if (!Yap_ExtendWorkSpace(size)) { /* make sure stacks and trail are contiguous */ - Yap_ErrorMessage = NULL; - minimal_request = AdjustPageSize(((CELL)Yap_TrailTop-(CELL)Yap_GlobalBase)+4*MinHeapGap+size0); + LOCAL_ErrorMessage = NULL; + minimal_request = AdjustPageSize(((CELL)LOCAL_TrailTop-(CELL)LOCAL_GlobalBase)+4*MinHeapGap+size0); size = Yap_ExtendWorkSpaceThroughHole(minimal_request); if (size < 0) { - Yap_ErrorMessage = "Database crashed against stacks"; + LOCAL_ErrorMessage = "Database crashed against stacks"; return FALSE; } YAPEnterCriticalSection(); - GDiff = DelayDiff = BaseDiff = size-size0; + LOCAL_GDiff = LOCAL_DelayDiff = LOCAL_BaseDiff = size-size0; } else { YAPEnterCriticalSection(); - if (Yap_GlobalBase != old_Yap_GlobalBase) { - GDiff = BaseDiff = DelayDiff = Yap_GlobalBase-old_Yap_GlobalBase; - Yap_GlobalBase=old_Yap_GlobalBase; + if (LOCAL_GlobalBase != old_LOCAL_GlobalBase) { + LOCAL_GDiff = LOCAL_BaseDiff = LOCAL_DelayDiff = LOCAL_GlobalBase-old_LOCAL_GlobalBase; + LOCAL_GlobalBase=old_LOCAL_GlobalBase; } else { - GDiff = BaseDiff = DelayDiff = 0; + LOCAL_GDiff = LOCAL_BaseDiff = LOCAL_DelayDiff = 0; } } - XDiff = HDiff = 0; - GDiff0=GDiff; + LOCAL_XDiff = LOCAL_HDiff = 0; + LOCAL_GDiff0=LOCAL_GDiff; #if USE_SYSTEM_MALLOC if (from_trail) { - TrDiff = LDiff = GDiff; + LOCAL_TrDiff = LOCAL_LDiff = LOCAL_GDiff; } else { - TrDiff = LDiff = size+GDiff; + LOCAL_TrDiff = LOCAL_LDiff = size+LOCAL_GDiff; } #else if (from_trail) { - TrDiff = LDiff = size-size0; + LOCAL_TrDiff = LOCAL_LDiff = size-size0; } else { - TrDiff = LDiff = size; + LOCAL_TrDiff = LOCAL_LDiff = size; } #endif ASP -= 256; SetHeapRegs(FALSE PASS_REGS); if (from_trail) { - Yap_TrailTop += size0; + LOCAL_TrailTop += size0; } - if (LDiff) { + if (LOCAL_LDiff) { MoveLocalAndTrail( PASS_REGS1 ); } - if (GDiff) { + if (LOCAL_GDiff) { #if !USE_SYSTEM_MALLOC /* That is done by realloc */ MoveGlobal( PASS_REGS1 ); @@ -1563,7 +1551,7 @@ execute_growstack(long size0, int from_trail, int in_parser, tr_fr_ptr *old_trp, #ifdef TABLING fix_tabling_info( PASS_REGS1 ); #endif /* TABLING */ - } else if (LDiff) { + } else if (LOCAL_LDiff) { if (in_parser) { tr_fr_ptr nTR; @@ -1599,28 +1587,28 @@ growstack(long size USES_REGS) if (size < YAP_ALLOC_SIZE) size = YAP_ALLOC_SIZE; size = AdjustPageSize(size); - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; start_growth_time = Yap_cputime(); gc_verbose = Yap_is_gc_verbose(); - stack_overflows++; + LOCAL_stack_overflows++; if (gc_verbose) { #if defined(YAPOR) || defined(THREADS) - fprintf(Yap_stderr, "%% Worker Id %d:\n", worker_id); + fprintf(GLOBAL_stderr, "%% Worker Id %d:\n", worker_id); #endif - fprintf(Yap_stderr, "%% Stack Overflow %d\n", stack_overflows); - fprintf(Yap_stderr, "%% Global: %8ld cells (%p-%p)\n", (unsigned long int)(H-(CELL *)Yap_GlobalBase),Yap_GlobalBase,H); - fprintf(Yap_stderr, "%% Local:%8ld cells (%p-%p)\n", (unsigned long int)(LCL0-ASP),LCL0,ASP); - fprintf(Yap_stderr, "%% Trail:%8ld cells (%p-%p)\n", - (unsigned long int)(TR-(tr_fr_ptr)Yap_TrailBase),Yap_TrailBase,TR); - fprintf(Yap_stderr, "%% Growing the stacks %ld bytes\n", size); + fprintf(GLOBAL_stderr, "%% Stack Overflow %d\n", LOCAL_stack_overflows); + fprintf(GLOBAL_stderr, "%% Global: %8ld cells (%p-%p)\n", (unsigned long int)(H-(CELL *)LOCAL_GlobalBase),LOCAL_GlobalBase,H); + fprintf(GLOBAL_stderr, "%% Local:%8ld cells (%p-%p)\n", (unsigned long int)(LCL0-ASP),LCL0,ASP); + fprintf(GLOBAL_stderr, "%% Trail:%8ld cells (%p-%p)\n", + (unsigned long int)(TR-(tr_fr_ptr)LOCAL_TrailBase),LOCAL_TrailBase,TR); + fprintf(GLOBAL_stderr, "%% Growing the stacks %ld bytes\n", size); } if (!execute_growstack(size, FALSE, FALSE, NULL, NULL, NULL PASS_REGS)) return FALSE; growth_time = Yap_cputime()-start_growth_time; - total_stack_overflow_time += growth_time; + LOCAL_total_stack_overflow_time += growth_time; if (gc_verbose) { - fprintf(Yap_stderr, "%% took %g sec\n", (double)growth_time/1000); - fprintf(Yap_stderr, "%% Total of %g sec expanding stacks \n", (double)total_stack_overflow_time/1000); + fprintf(GLOBAL_stderr, "%% took %g sec\n", (double)growth_time/1000); + fprintf(GLOBAL_stderr, "%% Total of %g sec expanding stacks \n", (double)LOCAL_total_stack_overflow_time/1000); } return TRUE; } @@ -1634,33 +1622,33 @@ Yap_growstack_in_parser(tr_fr_ptr *old_trp, TokEntry **tksp, VarEntry **vep) UInt start_growth_time, growth_time; int gc_verbose; - Yap_PrologMode |= GrowStackMode; + LOCAL_PrologMode |= GrowStackMode; /* adjust to a multiple of 256) */ - size = AdjustPageSize((ADDR)LCL0-Yap_GlobalBase); - Yap_ErrorMessage = NULL; + size = AdjustPageSize((ADDR)LCL0-LOCAL_GlobalBase); + LOCAL_ErrorMessage = NULL; start_growth_time = Yap_cputime(); gc_verbose = Yap_is_gc_verbose(); - stack_overflows++; + LOCAL_stack_overflows++; if (gc_verbose) { #if defined(YAPOR) || defined(THREADS) - fprintf(Yap_stderr, "%% Worker Id %d:\n", worker_id); + fprintf(GLOBAL_stderr, "%% Worker Id %d:\n", worker_id); #endif - fprintf(Yap_stderr, "%% Stack Overflow %d\n", stack_overflows); - fprintf(Yap_stderr, "%% Global: %8ld cells (%p-%p)\n", (unsigned long int)(H-(CELL *)Yap_GlobalBase),Yap_GlobalBase,H); - fprintf(Yap_stderr, "%% Local:%8ld cells (%p-%p)\n", (unsigned long int)(LCL0-ASP),LCL0,ASP); - fprintf(Yap_stderr, "%% Trail:%8ld cells (%p-%p)\n", - (unsigned long int)(TR-(tr_fr_ptr)Yap_TrailBase),Yap_TrailBase,TR); - fprintf(Yap_stderr, "%% Growing the stacks %ld bytes\n", (unsigned long int)size); + fprintf(GLOBAL_stderr, "%% Stack Overflow %d\n", LOCAL_stack_overflows); + fprintf(GLOBAL_stderr, "%% Global: %8ld cells (%p-%p)\n", (unsigned long int)(H-(CELL *)LOCAL_GlobalBase),LOCAL_GlobalBase,H); + fprintf(GLOBAL_stderr, "%% Local:%8ld cells (%p-%p)\n", (unsigned long int)(LCL0-ASP),LCL0,ASP); + fprintf(GLOBAL_stderr, "%% Trail:%8ld cells (%p-%p)\n", + (unsigned long int)(TR-(tr_fr_ptr)LOCAL_TrailBase),LOCAL_TrailBase,TR); + fprintf(GLOBAL_stderr, "%% Growing the stacks %ld bytes\n", (unsigned long int)size); } if (!execute_growstack(size, FALSE, TRUE, old_trp, tksp, vep PASS_REGS)) { LeaveGrowMode(GrowStackMode); return FALSE; } growth_time = Yap_cputime()-start_growth_time; - total_stack_overflow_time += growth_time; + LOCAL_total_stack_overflow_time += growth_time; if (gc_verbose) { - fprintf(Yap_stderr, "%% took %g sec\n", (double)growth_time/1000); - fprintf(Yap_stderr, "%% Total of %g sec expanding stacks \n", (double)total_stack_overflow_time/1000); + fprintf(GLOBAL_stderr, "%% took %g sec\n", (double)growth_time/1000); + fprintf(GLOBAL_stderr, "%% Total of %g sec expanding stacks \n", (double)LOCAL_total_stack_overflow_time/1000); } LeaveGrowMode(GrowStackMode); return TRUE; @@ -1678,7 +1666,7 @@ static int do_growtrail(long size, int contiguous_only, int in_parser, tr_fr_ptr #endif /* at least 64K for trail */ if (!size) - size = ((ADDR)TR-Yap_TrailBase); + size = ((ADDR)TR-LOCAL_TrailBase); size *= 2; if (size < YAP_ALLOC_SIZE) size = YAP_ALLOC_SIZE; @@ -1688,58 +1676,58 @@ static int do_growtrail(long size, int contiguous_only, int in_parser, tr_fr_ptr size=size0; /* adjust to a multiple of 256) */ size = AdjustPageSize(size); - trail_overflows++; + LOCAL_trail_overflows++; if (gc_verbose) { #if defined(YAPOR) || defined(THREADS) - fprintf(Yap_stderr, "%% Worker Id %d:\n", worker_id); + fprintf(GLOBAL_stderr, "%% Worker Id %d:\n", worker_id); #endif - fprintf(Yap_stderr, "%% Trail Overflow %d\n", trail_overflows); + fprintf(GLOBAL_stderr, "%% Trail Overflow %d\n", LOCAL_trail_overflows); #if USE_SYSTEM_MALLOC - fprintf(Yap_stderr, "%% Heap: %8ld cells (%p-%p)\n", (unsigned long int)(H-(CELL *)Yap_GlobalBase),(CELL *)Yap_GlobalBase,H); - fprintf(Yap_stderr, "%% Local:%8ld cells (%p-%p)\n", (unsigned long int)(LCL0-ASP),LCL0,ASP); - fprintf(Yap_stderr, "%% Trail:%8ld cells (%p-%p)\n", - (unsigned long int)(TR-(tr_fr_ptr)Yap_TrailBase),Yap_TrailBase,TR); + fprintf(GLOBAL_stderr, "%% Heap: %8ld cells (%p-%p)\n", (unsigned long int)(H-(CELL *)LOCAL_GlobalBase),(CELL *)LOCAL_GlobalBase,H); + fprintf(GLOBAL_stderr, "%% Local:%8ld cells (%p-%p)\n", (unsigned long int)(LCL0-ASP),LCL0,ASP); + fprintf(GLOBAL_stderr, "%% Trail:%8ld cells (%p-%p)\n", + (unsigned long int)(TR-(tr_fr_ptr)LOCAL_TrailBase),LOCAL_TrailBase,TR); #endif - fprintf(Yap_stderr, "%% growing the trail %ld bytes\n", size); + fprintf(GLOBAL_stderr, "%% growing the trail %ld bytes\n", size); } - Yap_ErrorMessage = NULL; - if (!Yap_AllowTrailExpansion) { - Yap_ErrorMessage = "Trail Overflow"; + LOCAL_ErrorMessage = NULL; + if (!GLOBAL_AllowTrailExpansion) { + LOCAL_ErrorMessage = "Trail Overflow"; return FALSE; } #if USE_SYSTEM_MALLOC execute_growstack(size, TRUE, in_parser, old_trp, tksp, vep PASS_REGS); #else if (!Yap_ExtendWorkSpace(size)) { - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; if (contiguous_only) { /* I can't expand in this case */ - trail_overflows--; + LOCAL_trail_overflows--; return FALSE; } execute_growstack(size, TRUE, in_parser, old_trp, tksp, vep PASS_REGS); } else { YAPEnterCriticalSection(); if (in_parser) { - TrDiff = LDiff = GDiff = BaseDiff = DelayDiff = XDiff = HDiff = GDiff0 = 0; + LOCAL_TrDiff = LOCAL_LDiff = LOCAL_GDiff = LOCAL_BaseDiff = LOCAL_DelayDiff = LOCAL_XDiff = LOCAL_HDiff = LOCAL_GDiff0 = 0; AdjustScannerStacks(tksp, vep PASS_REGS); } - Yap_TrailTop += size; + LOCAL_TrailTop += size; YAPLeaveCriticalSection(); } #endif growth_time = Yap_cputime()-start_growth_time; - total_trail_overflow_time += growth_time; + LOCAL_total_trail_overflow_time += growth_time; if (gc_verbose) { - fprintf(Yap_stderr, "%% took %g sec\n", (double)growth_time/1000); - fprintf(Yap_stderr, "%% Total of %g sec expanding trail \n", (double)total_trail_overflow_time/1000); + fprintf(GLOBAL_stderr, "%% took %g sec\n", (double)growth_time/1000); + fprintf(GLOBAL_stderr, "%% Total of %g sec expanding trail \n", (double)LOCAL_total_trail_overflow_time/1000); } - LOCK(SignalLock); - if (ActiveSignals == YAP_TROVF_SIGNAL) { + LOCK(LOCAL_SignalLock); + if (LOCAL_ActiveSignals == YAP_TROVF_SIGNAL) { CreepFlag = CalculateStackGap(); } - ActiveSignals &= ~YAP_TROVF_SIGNAL; - UNLOCK(SignalLock); + LOCAL_ActiveSignals &= ~YAP_TROVF_SIGNAL; + UNLOCK(LOCAL_SignalLock); return TRUE; } @@ -1801,8 +1789,8 @@ Yap_shift_visit(CELL **to_visit, CELL ***to_visit_maxp) static Int p_inform_trail_overflows( USES_REGS1 ) { - Term tn = MkIntTerm(trail_overflows); - Term tt = MkIntegerTerm(total_trail_overflow_time); + Term tn = MkIntTerm(LOCAL_trail_overflows); + Term tt = MkIntegerTerm(LOCAL_total_trail_overflow_time); return(Yap_unify(tn, ARG1) && Yap_unify(tt, ARG2)); } @@ -1831,8 +1819,8 @@ p_growheap( USES_REGS1 ) static Int p_inform_heap_overflows( USES_REGS1 ) { - Term tn = MkIntTerm(heap_overflows); - Term tt = MkIntegerTerm(total_heap_overflow_time); + Term tn = MkIntTerm(LOCAL_heap_overflows); + Term tt = MkIntegerTerm(LOCAL_total_heap_overflow_time); return(Yap_unify(tn, ARG1) && Yap_unify(tt, ARG2)); } @@ -1845,40 +1833,40 @@ Yap_CopyThreadStacks(int worker_q, int worker_p, int incremental) Int size; /* make sure both stacks have same size */ - Int p_size = FOREIGN_ThreadHandle(worker_p).ssize+FOREIGN_ThreadHandle(worker_p).tsize; - Int q_size = FOREIGN_ThreadHandle(worker_q).ssize+FOREIGN_ThreadHandle(worker_q).tsize; + Int p_size = REMOTE_ThreadHandle(worker_p).ssize+REMOTE_ThreadHandle(worker_p).tsize; + Int q_size = REMOTE_ThreadHandle(worker_q).ssize+REMOTE_ThreadHandle(worker_q).tsize; if (p_size != q_size) { - if (!(FOREIGN_ThreadHandle(worker_q).stack_address = realloc(FOREIGN_ThreadHandle(worker_q).stack_address,p_size*K1))) { + if (!(REMOTE_ThreadHandle(worker_q).stack_address = realloc(REMOTE_ThreadHandle(worker_q).stack_address,p_size*K1))) { exit(1); } } - FOREIGN_ThreadHandle(worker_q).ssize = FOREIGN_ThreadHandle(worker_p).ssize; - FOREIGN_ThreadHandle(worker_q).tsize = FOREIGN_ThreadHandle(worker_p).tsize; + REMOTE_ThreadHandle(worker_q).ssize = REMOTE_ThreadHandle(worker_p).ssize; + REMOTE_ThreadHandle(worker_q).tsize = REMOTE_ThreadHandle(worker_p).tsize; /* compute offset indicators */ - Yap_GlobalBase = Yap_thread_gl[worker_p].global_base; - Yap_LocalBase = Yap_thread_gl[worker_p].local_base; - Yap_TrailBase = Yap_thread_gl[worker_p].trail_base; - Yap_TrailTop = Yap_thread_gl[worker_p].trail_top; - size = FOREIGN_ThreadHandle(worker_q).stack_address-FOREIGN_ThreadHandle(worker_p).stack_address; - TrDiff = LDiff = GDiff = GDiff0 = DelayDiff = BaseDiff = size; - XDiff = HDiff = 0; - GSplit = NULL; - H = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->H_; - H0 = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->H0_; - B = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->B_; - ENV = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->ENV_; - YENV = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->YENV_; - ASP = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->ASP_; - TR = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->TR_; + LOCAL_GlobalBase = REMOTE_GlobalBase(worker_p); + LOCAL_LocalBase = REMOTE_LocalBase(worker_p); + LOCAL_TrailBase = REMOTE_TrailBase(worker_p); + LOCAL_TrailTop = REMOTE_TrailTop(worker_p); + size = REMOTE_ThreadHandle(worker_q).stack_address-REMOTE_ThreadHandle(worker_p).stack_address; + LOCAL_TrDiff = LOCAL_LDiff = LOCAL_GDiff = LOCAL_GDiff0 = LOCAL_DelayDiff = LOCAL_BaseDiff = size; + LOCAL_XDiff = LOCAL_HDiff = 0; + LOCAL_GSplit = NULL; + H = REMOTE_ThreadHandle(worker_p).current_yaam_regs->H_; + H0 = REMOTE_ThreadHandle(worker_p).current_yaam_regs->H0_; + B = REMOTE_ThreadHandle(worker_p).current_yaam_regs->B_; + ENV = REMOTE_ThreadHandle(worker_p).current_yaam_regs->ENV_; + YENV = REMOTE_ThreadHandle(worker_p).current_yaam_regs->YENV_; + ASP = REMOTE_ThreadHandle(worker_p).current_yaam_regs->ASP_; + TR = REMOTE_ThreadHandle(worker_p).current_yaam_regs->TR_; if (ASP > CellPtr(B)) ASP = CellPtr(B); - LCL0 = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->LCL0_; + LCL0 = REMOTE_ThreadHandle(worker_p).current_yaam_regs->LCL0_; #ifdef CUT_C - Yap_REGS.CUT_C_TOP = FOREIGN_ThreadHandle(worker_p).current_yaam_regs->CUT_C_TOP; + Yap_REGS.CUT_C_TOP = REMOTE_ThreadHandle(worker_p).current_yaam_regs->CUT_C_TOP; #endif - DynamicArrays = NULL; - StaticArrays = NULL; - GlobalVariables = NULL; + LOCAL_DynamicArrays = NULL; + LOCAL_StaticArrays = NULL; + LOCAL_GlobalVariables = NULL; SetHeapRegs(TRUE PASS_REGS); if (incremental) { IncrementalCopyStacksFromWorker( PASS_REGS1 ); @@ -1929,8 +1917,8 @@ p_growstack( USES_REGS1 ) static Int p_inform_stack_overflows( USES_REGS1 ) { /* */ - Term tn = MkIntTerm(stack_overflows); - Term tt = MkIntegerTerm(total_stack_overflow_time); + Term tn = MkIntTerm(LOCAL_stack_overflows); + Term tt = MkIntegerTerm(LOCAL_total_stack_overflow_time); return(Yap_unify(tn, ARG1) && Yap_unify(tt, ARG2)); @@ -1939,9 +1927,10 @@ p_inform_stack_overflows( USES_REGS1 ) Int Yap_total_stack_shift_time(void) { - return(total_heap_overflow_time+ - total_stack_overflow_time+ - total_trail_overflow_time); + CACHE_REGS + return(LOCAL_total_heap_overflow_time+ + LOCAL_total_stack_overflow_time+ + LOCAL_total_trail_overflow_time); } void diff --git a/C/heapgc.c b/C/heapgc.c index 3a0f90371..4f60e9678 100755 --- a/C/heapgc.c +++ b/C/heapgc.c @@ -93,103 +93,62 @@ typedef struct RB_red_blk_node { } rb_red_blk_node; #ifdef EASY_SHUNTING -#undef cont_top0 -#define cont_top0 (cont *)sTR +#undef LOCAL_cont_top0 +#define LOCAL_cont_top0 (cont *)LOCAL_sTR #endif -#if !defined(YAPOR) && !defined(THREADS) -/* in a single gc */ -static unsigned long int total_marked, total_oldies; /* number of heap objects marked */ - -#ifdef EASY_SHUNTING -static choiceptr current_B; - -static tr_fr_ptr sTR, sTR0; - -static CELL *prev_HB; -#endif - -static tr_fr_ptr new_TR; - -static CELL *HGEN; - -char *Yap_bp; - -static int discard_trail_entries = 0; - -#ifdef HYBRID_SCHEME -static CELL_PTR *iptop; -#endif - -#ifndef EASY_SHUNTING -static cont *cont_top0; -#endif -static cont *cont_top; - -static gc_ma_hash_entry gc_ma_hash_table[GC_MAVARS_HASH_SIZE]; - -static gc_ma_hash_entry *gc_ma_h_top, *gc_ma_h_list; - -static UInt gc_timestamp; /* an unsigned int */ - -static ADDR db_vec, db_vec0; - -static rb_red_blk_node *db_root, *db_nil; - -#endif /* !defined(YAPOR) && !defined(THREADS) */ - /* support for hybrid garbage collection scheme */ static void gc_growtrail(int committed, tr_fr_ptr begsTR, cont *old_cont_top0 USES_REGS) { - UInt sz = Yap_TrailTop-(ADDR)OldTR; + UInt sz = LOCAL_TrailTop-(ADDR)LOCAL_OldTR; /* ask for double the size */ sz = 2*sz; if (!Yap_growtrail(sz, TRUE)) { #ifdef EASY_SHUNTING if (begsTR) { - sTR = (tr_fr_ptr)old_cont_top0; + LOCAL_sTR = (tr_fr_ptr)old_cont_top0; while (begsTR != NULL) { tr_fr_ptr newsTR = (tr_fr_ptr)TrailTerm(begsTR); - TrailTerm(sTR) = TrailTerm(begsTR+1); - TrailTerm(sTR+1) = TrailTerm(begsTR+2); + TrailTerm(LOCAL_sTR) = TrailTerm(begsTR+1); + TrailTerm(LOCAL_sTR+1) = TrailTerm(begsTR+2); begsTR = newsTR; - sTR += 2; + LOCAL_sTR += 2; } } - set_conditionals(sTR PASS_REGS); + set_conditionals(LOCAL_sTR PASS_REGS); #endif /* could not find more trail */ save_machine_regs(); - siglongjmp(Yap_gc_restore, 2); + siglongjmp(LOCAL_gc_restore, 2); } } inline static void PUSH_CONTINUATION(CELL *v, int nof USES_REGS) { cont *x; - x = cont_top; + x = LOCAL_cont_top; x++; - if ((ADDR)x > Yap_TrailTop-1024) { + if ((ADDR)x > LOCAL_TrailTop-1024) { gc_growtrail(TRUE, NULL, NULL PASS_REGS); } x->v = v; x->nof = nof; - cont_top = x; + LOCAL_cont_top = x; } #define POP_CONTINUATION() { \ - if (cont_top == cont_top0) \ + if (LOCAL_cont_top == LOCAL_cont_top0) \ return; \ else { \ - int nof = cont_top->nof; \ - cont *x = cont_top; \ + int nof = LOCAL_cont_top->nof; \ + cont *x = LOCAL_cont_top; \ \ current = x->v; \ if (nof == 1) \ - cont_top = --x; \ + LOCAL_cont_top = --x; \ else { \ x->nof = nof-1; \ x->v = current+1; \ @@ -201,24 +160,24 @@ PUSH_CONTINUATION(CELL *v, int nof USES_REGS) { inline static void PUSH_POINTER(CELL *v USES_REGS) { - if (iptop >= (CELL_PTR *)ASP) return; - *iptop++ = v; + if (LOCAL_iptop >= (CELL_PTR *)ASP) return; + *LOCAL_iptop++ = v; } inline static void POP_POINTER( USES_REGS1 ) { - if (iptop >= (CELL_PTR *)ASP) return; - --iptop; + if (LOCAL_iptop >= (CELL_PTR *)ASP) return; + --LOCAL_iptop; } inline static void POPSWAP_POINTER(CELL_PTR *vp, CELL_PTR v USES_REGS) { - if (iptop >= (CELL_PTR *)ASP || iptop == vp) return; + if (LOCAL_iptop >= (CELL_PTR *)ASP || LOCAL_iptop == vp) return; if (*vp != v) return; - --iptop; - if (vp != iptop) - *vp = *iptop; + --LOCAL_iptop; + if (vp != LOCAL_iptop) + *vp = *LOCAL_iptop; } /* @@ -334,15 +293,15 @@ GC_MAVAR_HASH(CELL *addr) { static inline gc_ma_hash_entry * GC_ALLOC_NEW_MASPACE( USES_REGS1 ) { - gc_ma_hash_entry *new = gc_ma_h_top; - if ((char *)gc_ma_h_top > Yap_TrailTop-1024) + gc_ma_hash_entry *new = LOCAL_gc_ma_h_top; + if ((char *)LOCAL_gc_ma_h_top > LOCAL_TrailTop-1024) gc_growtrail(FALSE, NULL, NULL PASS_REGS); - gc_ma_h_top++; - cont_top = (cont *)gc_ma_h_top; + LOCAL_gc_ma_h_top++; + LOCAL_cont_top = (cont *)LOCAL_gc_ma_h_top; #ifdef EASY_SHUNTING - sTR = sTR0 = (tr_fr_ptr)cont_top; + LOCAL_sTR = LOCAL_sTR0 = (tr_fr_ptr)LOCAL_cont_top; #else - cont_top0 = cont_top; + LOCAL_cont_top0 = LOCAL_cont_top; #endif return new; } @@ -352,18 +311,18 @@ gc_lookup_ma_var(CELL *addr, tr_fr_ptr trp USES_REGS) { unsigned int i = GC_MAVAR_HASH(addr); gc_ma_hash_entry *nptr, *optr = NULL; - if (gc_ma_hash_table[i].timestmp != gc_timestamp) { - gc_ma_hash_table[i].timestmp = gc_timestamp; - gc_ma_hash_table[i].addr = addr; + if (LOCAL_gc_ma_hash_table[i].timestmp != LOCAL_gc_timestamp) { + LOCAL_gc_ma_hash_table[i].timestmp = LOCAL_gc_timestamp; + LOCAL_gc_ma_hash_table[i].addr = addr; #if TABLING - gc_ma_hash_table[i].loc = trp; - gc_ma_hash_table[i].more = gc_ma_h_list; - gc_ma_h_list = gc_ma_hash_table+i; + LOCAL_gc_ma_hash_table[i].loc = trp; + LOCAL_gc_ma_hash_table[i].more = LOCAL_gc_ma_h_list; + LOCAL_gc_ma_h_list = LOCAL_gc_ma_hash_table+i; #endif /* TABLING */ - gc_ma_hash_table[i].next = NULL; + LOCAL_gc_ma_hash_table[i].next = NULL; return NULL; } - nptr = gc_ma_hash_table+i; + nptr = LOCAL_gc_ma_hash_table+i; while (nptr) { optr = nptr; if (nptr->addr == addr) { @@ -383,32 +342,32 @@ gc_lookup_ma_var(CELL *addr, tr_fr_ptr trp USES_REGS) { nptr->addr = addr; #if TABLING nptr->loc = trp; - nptr->more = gc_ma_h_list; + nptr->more = LOCAL_gc_ma_h_list; #endif /* TABLING */ nptr->next = NULL; - gc_ma_h_list = nptr; + LOCAL_gc_ma_h_list = nptr; return NULL; } static inline void GC_NEW_MAHASH(gc_ma_hash_entry *top USES_REGS) { - UInt time = ++gc_timestamp; + UInt time = ++LOCAL_gc_timestamp; - gc_ma_h_list = NULL; + LOCAL_gc_ma_h_list = NULL; if (time == 0) { unsigned int i; /* damn, we overflowed */ for (i = 0; i < GC_MAVARS_HASH_SIZE; i++) - gc_ma_hash_table[i].timestmp = 0L; - time = ++gc_timestamp; + LOCAL_gc_ma_hash_table[i].timestmp = 0L; + time = ++LOCAL_gc_timestamp; } - gc_ma_h_top = top; - cont_top = (cont *)gc_ma_h_top; + LOCAL_gc_ma_h_top = top; + LOCAL_cont_top = (cont *)LOCAL_gc_ma_h_top; #ifdef EASY_SHUNTING - sTR = (tr_fr_ptr)cont_top; + LOCAL_sTR = (tr_fr_ptr)LOCAL_cont_top; #else - cont_top0 = cont_top; + LOCAL_cont_top0 = LOCAL_cont_top; #endif } @@ -419,11 +378,11 @@ GC_NEW_MAHASH(gc_ma_hash_entry *top USES_REGS) { static void check_pr_trail(tr_fr_ptr trp USES_REGS) { - if ((tr_fr_ptr)Yap_TrailTop-TR < 1024) { + if ((tr_fr_ptr)LOCAL_TrailTop-TR < 1024) { if (!Yap_growtrail(0, TRUE) || TRUE) { /* could not find more trail */ save_machine_regs(); - siglongjmp(Yap_gc_restore, 2); + siglongjmp(LOCAL_gc_restore, 2); } } } @@ -434,12 +393,12 @@ static void push_registers(Int num_regs, yamop *nextop USES_REGS) { int i; - StaticArrayEntry *sal = StaticArrays; + StaticArrayEntry *sal = LOCAL_StaticArrays; /* push array entries first */ - ArrayEntry *al = DynamicArrays; - GlobalEntry *gl = GlobalVariables; - TrailTerm(TR++) = GlobalArena; + ArrayEntry *al = LOCAL_DynamicArrays; + GlobalEntry *gl = LOCAL_GlobalVariables; + TrailTerm(TR++) = LOCAL_GlobalArena; while (al) { check_pr_trail(TR PASS_REGS); TrailTerm(TR++) = al->ValueOfVE; @@ -464,13 +423,13 @@ push_registers(Int num_regs, yamop *nextop USES_REGS) sal = sal->NextAE; } check_pr_trail(TR PASS_REGS); - TrailTerm(TR) = GcGeneration; + TrailTerm(TR) = LOCAL_GcGeneration; TR++; - TrailTerm(TR) = GcPhase; + TrailTerm(TR) = LOCAL_GcPhase; TR++; #ifdef COROUTINING - TrailTerm(TR) = WokenGoals; - TrailTerm(TR+1) = AttsMutableList; + TrailTerm(TR) = LOCAL_WokenGoals; + TrailTerm(TR+1) = LOCAL_AttsMutableList; TR += 2; #endif for (i = 1; i <= num_regs; i++) { @@ -510,13 +469,13 @@ pop_registers(Int num_regs, yamop *nextop USES_REGS) { int i; tr_fr_ptr ptr = TR; - StaticArrayEntry *sal = StaticArrays; + StaticArrayEntry *sal = LOCAL_StaticArrays; /* pop array entries first */ - ArrayEntry *al = DynamicArrays; - GlobalEntry *gl = GlobalVariables; + ArrayEntry *al = LOCAL_DynamicArrays; + GlobalEntry *gl = LOCAL_GlobalVariables; - GlobalArena = TrailTerm(ptr++); + LOCAL_GlobalArena = TrailTerm(ptr++); while (al) { al->ValueOfVE = TrailTerm(ptr++); al = al->NextAE; @@ -525,7 +484,7 @@ pop_registers(Int num_regs, yamop *nextop USES_REGS) gl->global = TrailTerm(ptr++); gl = gl->NextGE; } - sal = StaticArrays; + sal = LOCAL_StaticArrays; while (sal) { if (sal->ArrayType == array_of_nb_terms) { UInt arity = -sal->ArrayEArity; @@ -538,12 +497,12 @@ pop_registers(Int num_regs, yamop *nextop USES_REGS) } sal = sal->NextAE; } - GcGeneration = TrailTerm(ptr++); - GcPhase = TrailTerm(ptr++); + LOCAL_GcGeneration = TrailTerm(ptr++); + LOCAL_GcPhase = TrailTerm(ptr++); #ifdef COROUTINING #ifdef MULTI_ASSIGNMENT_VARIABLES - WokenGoals = TrailTerm(ptr++); - AttsMutableList = TrailTerm(ptr++); + LOCAL_WokenGoals = TrailTerm(ptr++); + LOCAL_AttsMutableList = TrailTerm(ptr++); #endif #endif for (i = 1; i <= num_regs; i++) @@ -591,10 +550,10 @@ count_cells_marked(void) static rb_red_blk_node * RBMalloc(UInt size USES_REGS) { - ADDR new = db_vec; + ADDR new = LOCAL_db_vec; - db_vec += size; - if ((ADDR)db_vec > Yap_TrailTop-1024) { + LOCAL_db_vec += size; + if ((ADDR)LOCAL_db_vec > LOCAL_TrailTop-1024) { gc_growtrail(FALSE, NULL, NULL PASS_REGS); } return (rb_red_blk_node *)new; @@ -607,12 +566,12 @@ RBTreeCreate(void) { /* see the comment in the rb_red_blk_tree structure in red_black_tree.h */ /* for information on nil and root */ - temp=db_nil= RBMalloc(sizeof(rb_red_blk_node) PASS_REGS); + temp=LOCAL_db_nil= RBMalloc(sizeof(rb_red_blk_node) PASS_REGS); temp->parent=temp->left=temp->right=temp; temp->red=0; temp->key=NULL; temp = RBMalloc(sizeof(rb_red_blk_node) PASS_REGS); - temp->parent=temp->left=temp->right=db_nil; + temp->parent=temp->left=temp->right=LOCAL_db_nil; temp->key=NULL; temp->red=0; return temp; @@ -640,7 +599,7 @@ RBTreeCreate(void) { static void LeftRotate(rb_red_blk_node* x USES_REGS) { rb_red_blk_node* y; - rb_red_blk_node* nil=db_nil; + rb_red_blk_node* nil=LOCAL_db_nil; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ @@ -671,7 +630,7 @@ LeftRotate(rb_red_blk_node* x USES_REGS) { x->parent=y; #ifdef DEBUG_ASSERT - Assert(!db_nil->red,"nil not red in LeftRotate"); + Assert(!LOCAL_db_nil->red,"nil not red in LeftRotate"); #endif } @@ -696,7 +655,7 @@ LeftRotate(rb_red_blk_node* x USES_REGS) { static void RightRotate(rb_red_blk_node* y USES_REGS) { rb_red_blk_node* x; - rb_red_blk_node* nil=db_nil; + rb_red_blk_node* nil=LOCAL_db_nil; /* I originally wrote this function to use the sentinel for */ /* nil to avoid checking for nil. However this introduces a */ @@ -726,7 +685,7 @@ RightRotate(rb_red_blk_node* y USES_REGS) { y->parent=x; #ifdef DEBUG_ASSERT - Assert(!db_nil->red,"nil not red in RightRotate"); + Assert(!LOCAL_db_nil->red,"nil not red in RightRotate"); #endif } @@ -750,11 +709,11 @@ TreeInsertHelp(rb_red_blk_node* z USES_REGS) { /* This function should only be called by InsertRBTree (see above) */ rb_red_blk_node* x; rb_red_blk_node* y; - rb_red_blk_node* nil=db_nil; + rb_red_blk_node* nil=LOCAL_db_nil; z->left=z->right=nil; - y=db_root; - x=db_root->left; + y=LOCAL_db_root; + x=LOCAL_db_root->left; while( x != nil) { y=x; if (x->key < z->key) { /* x.key > z.key */ @@ -764,7 +723,7 @@ TreeInsertHelp(rb_red_blk_node* z USES_REGS) { } } z->parent=y; - if ( (y == db_root) || + if ( (y == LOCAL_db_root) || (y->key < z->key)) { /* y.key > z.key */ y->left=z; } else { @@ -772,7 +731,7 @@ TreeInsertHelp(rb_red_blk_node* z USES_REGS) { } #ifdef DEBUG_ASSERT - Assert(!db_nil->red,"nil not red in TreeInsertHelp"); + Assert(!LOCAL_db_nil->red,"nil not red in TreeInsertHelp"); #endif } @@ -846,12 +805,12 @@ RBTreeInsert(CODEADDR key, CODEADDR end, db_entry_type db_type USES_REGS) { } } } - db_root->left->red=0; + LOCAL_db_root->left->red=0; return newNode; #ifdef DEBUG_ASSERT - Assert(!db_nil->red,"nil not red in RBTreeInsert"); - Assert(!db_root->red,"root not red in RBTreeInsert"); + Assert(!LOCAL_db_nil->red,"nil not red in RBTreeInsert"); + Assert(!LOCAL_db_root->red,"root not red in RBTreeInsert"); #endif } @@ -867,9 +826,9 @@ store_in_dbtable(CODEADDR entry, CODEADDR end, db_entry_type db_type USES_REGS) static rb_red_blk_node * find_ref_in_dbtable(CODEADDR entry USES_REGS) { - rb_red_blk_node *current = db_root->left; + rb_red_blk_node *current = LOCAL_db_root->left; - while (current != db_nil) { + while (current != LOCAL_db_nil) { if (current->key <= entry && current->lim > entry) { return current; } @@ -901,7 +860,7 @@ mark_db_fixed(CELL *ptr USES_REGS) { rb_red_blk_node *el; el = find_ref_in_dbtable((CODEADDR)ptr PASS_REGS); - if (el != db_nil) { + if (el != LOCAL_db_nil) { el->in_use = TRUE; } } @@ -912,9 +871,9 @@ init_dbtable(tr_fr_ptr trail_ptr USES_REGS) { MegaClause *mc = DeadMegaClauses; StaticIndex *si = DeadStaticIndices; - db_vec0 = db_vec = (ADDR)TR; - db_root = RBTreeCreate(); - while (trail_ptr > (tr_fr_ptr)Yap_TrailBase) { + LOCAL_db_vec0 = LOCAL_db_vec = (ADDR)TR; + LOCAL_db_root = RBTreeCreate(); + while (trail_ptr > (tr_fr_ptr)LOCAL_TrailBase) { register CELL trail_cell; trail_ptr--; @@ -932,7 +891,7 @@ init_dbtable(tr_fr_ptr trail_ptr USES_REGS) { #ifdef YAPOR_SBA (ADDR) pt0 >= HeapTop #else - (ADDR) pt0 >= Yap_TrailBase && (ADDR) pt0 < Yap_TrailTop + (ADDR) pt0 >= LOCAL_TrailBase && (ADDR) pt0 < LOCAL_TrailTop #endif ) { continue; @@ -973,9 +932,9 @@ init_dbtable(tr_fr_ptr trail_ptr USES_REGS) { store_in_dbtable((CODEADDR)mc, (CODEADDR)mc+mc->ClSize, dcl_entry PASS_REGS); mc = mc->ClNext; } - if (db_vec == db_vec0) { + if (LOCAL_db_vec == LOCAL_db_vec0) { /* could not find any entries: probably using LOG UPD semantics */ - db_vec0 = NULL; + LOCAL_db_vec0 = NULL; } } @@ -1019,17 +978,17 @@ inc_vars_of_type(CELL *curr,gc_types val) { static void put_type_info(unsigned long total) { - fprintf(Yap_stderr,"%% type info for %lu cells\n", total); - fprintf(Yap_stderr,"%% %lu vars\n", vars[gc_var]); - fprintf(Yap_stderr,"%% %lu refs\n", vars[gc_ref]); - fprintf(Yap_stderr,"%% %lu references from env\n", env_vars); - fprintf(Yap_stderr,"%% %lu atoms\n", vars[gc_atom]); - fprintf(Yap_stderr,"%% %lu small ints\n", vars[gc_int]); - fprintf(Yap_stderr,"%% %lu other numbers\n", vars[gc_num]); - fprintf(Yap_stderr,"%% %lu lists\n", vars[gc_list]); - fprintf(Yap_stderr,"%% %lu compound terms\n", vars[gc_appl]); - fprintf(Yap_stderr,"%% %lu functors\n", vars[gc_func]); - fprintf(Yap_stderr,"%% %lu suspensions\n", vars[gc_susp]); + fprintf(GLOBAL_stderr,"%% type info for %lu cells\n", total); + fprintf(GLOBAL_stderr,"%% %lu vars\n", vars[gc_var]); + fprintf(GLOBAL_stderr,"%% %lu refs\n", vars[gc_ref]); + fprintf(GLOBAL_stderr,"%% %lu references from env\n", env_vars); + fprintf(GLOBAL_stderr,"%% %lu atoms\n", vars[gc_atom]); + fprintf(GLOBAL_stderr,"%% %lu small ints\n", vars[gc_int]); + fprintf(GLOBAL_stderr,"%% %lu other numbers\n", vars[gc_num]); + fprintf(GLOBAL_stderr,"%% %lu lists\n", vars[gc_list]); + fprintf(GLOBAL_stderr,"%% %lu compound terms\n", vars[gc_appl]); + fprintf(GLOBAL_stderr,"%% %lu functors\n", vars[gc_func]); + fprintf(GLOBAL_stderr,"%% %lu suspensions\n", vars[gc_susp]); } static void @@ -1107,7 +1066,7 @@ check_global(void) { #if INSTRUMENT_GC if (IsVarTerm(ccurr)) { if (IsBlobFunctor((Functor)ccurr)) vars[gc_num]++; - else if (ccurr != 0 && (ccurr < (CELL)Yap_GlobalBase || ccurr > (CELL)Yap_TrailTop)) { + else if (ccurr != 0 && (ccurr < (CELL)LOCAL_GlobalBase || ccurr > (CELL)LOCAL_TrailTop)) { /* printf("%p: %s/%d\n", current, RepAtom(NameOfFunctor((Functor)ccurr))->StrOfAE, ArityOfFunctor((Functor)ccurr));*/ @@ -1155,16 +1114,16 @@ mark_variable(CELL_PTR current USES_REGS) CELL_PTR next; register CELL ccur; unsigned int arity; - char *local_bp = Yap_bp; + char *local_bp = LOCAL_bp; begin: if (UNMARKED_MARK(current,local_bp)) { POP_CONTINUATION(); } if (current >= H0 && current < H) { - total_marked++; - if (current < HGEN) { - total_oldies++; + LOCAL_total_marked++; + if (current < LOCAL_HGEN) { + LOCAL_total_oldies++; } } PUSH_POINTER(current PASS_REGS); @@ -1172,12 +1131,12 @@ mark_variable(CELL_PTR current USES_REGS) next = GET_NEXT(ccur); if (IsVarTerm(ccur)) { - if (IN_BETWEEN(Yap_GlobalBase,current,H) && GlobalIsAttVar(current) && current==next) { + if (IN_BETWEEN(LOCAL_GlobalBase,current,H) && GlobalIsAttVar(current) && current==next) { if (next < H0) POP_CONTINUATION(); if (!UNMARKED_MARK(next-1,local_bp)) { - total_marked++; - if (next-1 < HGEN) { - total_oldies++; + LOCAL_total_marked++; + if (next-1 < LOCAL_HGEN) { + LOCAL_total_oldies++; } PUSH_POINTER(next-1 PASS_REGS); } @@ -1193,7 +1152,7 @@ mark_variable(CELL_PTR current USES_REGS) if (!MARKED_PTR(next)) { if (IsVarTerm(cnext) && (CELL)next == cnext) { /* new global variable to new global variable */ - if (next > current && current < prev_HB && current >= HB && next >= HB && next < prev_HB) { + if (next > current && current < LOCAL_prev_HB && current >= HB && next >= HB && next < LOCAL_prev_HB) { #ifdef INSTRUMENT_GC inc_var(current, current); #endif @@ -1215,9 +1174,9 @@ mark_variable(CELL_PTR current USES_REGS) UNMARK(current); *current = cnext; if (current >= H0 && current < H) { - total_marked--; - if (current < HGEN) { - total_oldies--; + LOCAL_total_marked--; + if (current < LOCAL_HGEN) { + LOCAL_total_oldies--; } } POP_POINTER( PASS_REGS1 ); @@ -1237,9 +1196,9 @@ mark_variable(CELL_PTR current USES_REGS) *current = UNMARK_CELL(cnext); UNMARK(current); if (current >= H0 && current < H ) { - total_marked--; - if (current < HGEN) { - total_oldies--; + LOCAL_total_marked--; + if (current < LOCAL_HGEN) { + LOCAL_total_oldies--; } } POP_POINTER( PASS_REGS1 ); @@ -1254,12 +1213,12 @@ mark_variable(CELL_PTR current USES_REGS) } goto begin; #ifdef DEBUG - } else if (next < (CELL *)Yap_GlobalBase || next > (CELL *)Yap_TrailTop) { - fprintf(Yap_stderr, "OOPS in GC: marking, current=%p, *current=" UInt_FORMAT " next=%p\n", current, ccur, next); + } else if (next < (CELL *)LOCAL_GlobalBase || next > (CELL *)LOCAL_TrailTop) { + fprintf(GLOBAL_stderr, "OOPS in GC: marking, current=%p, *current=" UInt_FORMAT " next=%p\n", current, ccur, next); #endif } else { #ifdef COROUTING - total_smarked++; + LOCAL_total_smarked++; #endif #ifdef INSTRUMENT_GC inc_var(current, next); @@ -1282,9 +1241,9 @@ mark_variable(CELL_PTR current USES_REGS) /* speedup for strings */ if (IsAtomOrIntTerm(*next)) { if (!UNMARKED_MARK(next,local_bp)) { - total_marked++; - if (next < HGEN) { - total_oldies++; + LOCAL_total_marked++; + if (next < LOCAL_HGEN) { + LOCAL_total_oldies++; } PUSH_POINTER(next PASS_REGS); } @@ -1333,10 +1292,10 @@ mark_variable(CELL_PTR current USES_REGS) case (CELL)FunctorLongInt: MARK(next); MARK(next+2); - if (next < HGEN) { - total_oldies+=3; + if (next < LOCAL_HGEN) { + LOCAL_total_oldies+=3; } - total_marked += 3; + LOCAL_total_marked += 3; PUSH_POINTER(next PASS_REGS); PUSH_POINTER(next+2 PASS_REGS); POP_CONTINUATION(); @@ -1345,10 +1304,10 @@ mark_variable(CELL_PTR current USES_REGS) PUSH_POINTER(next PASS_REGS); { UInt sz = 1+SIZEOF_DOUBLE/SIZEOF_LONG_INT; - if (next < HGEN) { - total_oldies+= 1+sz; + if (next < LOCAL_HGEN) { + LOCAL_total_oldies+= 1+sz; } - total_marked += 1+sz; + LOCAL_total_marked += 1+sz; PUSH_POINTER(next+sz PASS_REGS); MARK(next+sz); } @@ -1359,9 +1318,9 @@ mark_variable(CELL_PTR current USES_REGS) ((MP_INT *)(next+2))->_mp_alloc*sizeof(mp_limb_t))/CellSize; MARK(next); /* size is given by functor + friends */ - if (next < HGEN) - total_oldies += 2+sz; - total_marked += 2+sz; + if (next < LOCAL_HGEN) + LOCAL_total_oldies += 2+sz; + LOCAL_total_marked += 2+sz; PUSH_POINTER(next PASS_REGS); sz++; MARK(next+sz); @@ -1377,18 +1336,18 @@ mark_variable(CELL_PTR current USES_REGS) #endif arity = ArityOfFunctor((Functor)(cnext)); MARK(next); - ++total_marked; - if (next < HGEN) { - ++total_oldies; + ++LOCAL_total_marked; + if (next < LOCAL_HGEN) { + ++LOCAL_total_oldies; } PUSH_POINTER(next PASS_REGS); next++; /* speedup for leaves */ while (arity && IsAtomOrIntTerm(*next)) { if (!UNMARKED_MARK(next,local_bp)) { - total_marked++; - if (next < HGEN) { - total_oldies++; + LOCAL_total_marked++; + if (next < LOCAL_HGEN) { + LOCAL_total_oldies++; } PUSH_POINTER(next PASS_REGS); } @@ -1435,7 +1394,7 @@ mark_external_reference(CELL *ptr USES_REGS) { if (ONHEAP(next)) { #ifdef HYBRID_SCHEME - CELL_PTR *old = iptop; + CELL_PTR *old = LOCAL_iptop; #endif mark_variable(ptr PASS_REGS); POPSWAP_POINTER(old, ptr PASS_REGS); @@ -1451,7 +1410,7 @@ mark_external_reference2(CELL *ptr USES_REGS) { if (ONHEAP(next)) { #ifdef HYBRID_SCHEME - CELL_PTR *old = iptop; + CELL_PTR *old = LOCAL_iptop; #endif mark_variable(ptr PASS_REGS); POPSWAP_POINTER(old, ptr PASS_REGS); @@ -1496,7 +1455,7 @@ mark_environments(CELL_PTR gc_ENV, OPREG size, CELL *pvbmap USES_REGS) #ifdef DEBUG if (size < 0 || size > 512) - fprintf(Yap_stderr,"OOPS in GC: env size for %p is " UInt_FORMAT "\n", gc_ENV, (CELL)size); + fprintf(GLOBAL_stderr,"OOPS in GC: env size for %p is " UInt_FORMAT "\n", gc_ENV, (CELL)size); #endif mark_db_fixed((CELL *)gc_ENV[E_CP] PASS_REGS); /* for each saved variable */ @@ -1574,14 +1533,14 @@ mark_environments(CELL_PTR gc_ENV, OPREG size, CELL *pvbmap USES_REGS) PredEntry *pe = EnvPreg(gc_ENV[E_CP]); op_numbers op = Yap_op_from_opcode(ENV_ToOp(gc_ENV[E_CP])); #if defined(ANALYST) || defined(DEBUG) - fprintf(Yap_stderr,"ENV %p-%p(%d) %s\n", gc_ENV, pvbmap, size-EnvSizeInCells, Yap_op_names[op]); + fprintf(GLOBAL_stderr,"ENV %p-%p(%d) %s\n", gc_ENV, pvbmap, size-EnvSizeInCells, Yap_op_names[op]); #else - fprintf(Yap_stderr,"ENV %p-%p(%d) %d\n", gc_ENV, pvbmap, size-EnvSizeInCells, (int)op); + fprintf(GLOBAL_stderr,"ENV %p-%p(%d) %d\n", gc_ENV, pvbmap, size-EnvSizeInCells, (int)op); #endif if (pe->ArityOfPE) - fprintf(Yap_stderr," %s/%d\n", RepAtom(NameOfFunctor(pe->FunctorOfPred))->StrOfAE, pe->ArityOfPE); + fprintf(GLOBAL_stderr," %s/%d\n", RepAtom(NameOfFunctor(pe->FunctorOfPred))->StrOfAE, pe->ArityOfPE); else - fprintf(Yap_stderr," %s\n", RepAtom((Atom)(pe->FunctorOfPred))->StrOfAE); + fprintf(GLOBAL_stderr," %s\n", RepAtom((Atom)(pe->FunctorOfPred))->StrOfAE); } #endif gc_ENV = (CELL_PTR) gc_ENV[E_E]; /* link to prev @@ -1610,15 +1569,15 @@ mark_trail(tr_fr_ptr trail_ptr, tr_fr_ptr trail_base, CELL *gc_H, choiceptr gc_B { #ifdef EASY_SHUNTING tr_fr_ptr begsTR = NULL, endsTR = NULL; - tr_fr_ptr OldsTR0 = sTR0; + tr_fr_ptr OldsTR0 = LOCAL_sTR0; #endif #ifdef COROUTINING CELL *detatt = NULL; #endif - cont *old_cont_top0 = cont_top0; + cont *old_cont_top0 = LOCAL_cont_top0; - GC_NEW_MAHASH((gc_ma_hash_entry *)cont_top0 PASS_REGS); + GC_NEW_MAHASH((gc_ma_hash_entry *)LOCAL_cont_top0 PASS_REGS); while (trail_base < trail_ptr) { register CELL trail_cell; @@ -1633,34 +1592,34 @@ mark_trail(tr_fr_ptr trail_ptr, tr_fr_ptr trail_base, CELL *gc_H, choiceptr gc_B /* perform early reset */ /* reset term to be a variable */ RESET_VARIABLE(hp); - discard_trail_entries++; + LOCAL_discard_trail_entries++; RESET_VARIABLE(&TrailTerm(trail_base)); #ifdef FROZEN_STACKS RESET_VARIABLE(&TrailVal(trail_base)); #endif - } else if (hp < (CELL *)Yap_GlobalBase || hp > (CELL *)Yap_TrailTop) { + } else if (hp < (CELL *)LOCAL_GlobalBase || hp > (CELL *)LOCAL_TrailTop) { /* pointers from the Heap back into the trail are process in mark_regs. */ /* do nothing !!! */ - } else if ((hp < (CELL *)gc_B && hp >= gc_H) || hp > (CELL *)Yap_TrailBase) { + } else if ((hp < (CELL *)gc_B && hp >= gc_H) || hp > (CELL *)LOCAL_TrailBase) { /* clean the trail, avoid dangling pointers! */ RESET_VARIABLE(&TrailTerm(trail_base)); #ifdef FROZEN_STACKS RESET_VARIABLE(&TrailVal(trail_base)); #endif - discard_trail_entries++; + LOCAL_discard_trail_entries++; } else { if (trail_cell == (CELL)trail_base) - discard_trail_entries++; + LOCAL_discard_trail_entries++; else { /* This is a bit of a mess: when I find an attributed variable that was bound nondeterministically, I know that after backtracking it will be back to be an unbound variable. The ideal solution would be to unbind all variables. The current solution is to remark it as an attributed variable */ - if (IN_BETWEEN(Yap_GlobalBase,hp,H) && GlobalIsAttVar(hp) && !UNMARKED_MARK(hp-1,Yap_bp)) { - total_marked++; + if (IN_BETWEEN(LOCAL_GlobalBase,hp,H) && GlobalIsAttVar(hp) && !UNMARKED_MARK(hp-1,LOCAL_bp)) { + LOCAL_total_marked++; PUSH_POINTER(hp-1 PASS_REGS); - if (hp-1 < HGEN) { - total_oldies++; + if (hp-1 < LOCAL_HGEN) { + LOCAL_total_oldies++; } mark_variable(hp+1 PASS_REGS); mark_variable(hp+2 PASS_REGS); @@ -1671,10 +1630,10 @@ mark_trail(tr_fr_ptr trail_ptr, tr_fr_ptr trail_base, CELL *gc_H, choiceptr gc_B } #ifdef EASY_SHUNTING if (hp < gc_H && hp >= H0 && !MARKED_PTR(hp)) { - tr_fr_ptr nsTR = (tr_fr_ptr)cont_top0; + tr_fr_ptr nsTR = (tr_fr_ptr)LOCAL_cont_top0; CELL *cptr = (CELL *)trail_cell; - if ((ADDR)nsTR > Yap_TrailTop-1024) { + if ((ADDR)nsTR > LOCAL_TrailTop-1024) { gc_growtrail(TRUE, begsTR, old_cont_top0 PASS_REGS); } TrailTerm(nsTR) = (CELL)NULL; @@ -1685,9 +1644,9 @@ mark_trail(tr_fr_ptr trail_ptr, tr_fr_ptr trail_base, CELL *gc_H, choiceptr gc_B else TrailTerm(endsTR) = (CELL)nsTR; endsTR = nsTR; - cont_top = (cont *)(nsTR+3); - sTR = (tr_fr_ptr)cont_top; - gc_ma_h_top = (gc_ma_hash_entry *)(nsTR+3); + LOCAL_cont_top = (cont *)(nsTR+3); + LOCAL_sTR = (tr_fr_ptr)LOCAL_cont_top; + LOCAL_gc_ma_h_top = (gc_ma_hash_entry *)(nsTR+3); RESET_VARIABLE(cptr); MARK(cptr); } @@ -1696,7 +1655,7 @@ mark_trail(tr_fr_ptr trail_ptr, tr_fr_ptr trail_base, CELL *gc_H, choiceptr gc_B } else if (IsPairTerm(trail_cell)) { /* can safely ignore this */ CELL *cptr = RepPair(trail_cell); - if (IN_BETWEEN(Yap_GlobalBase,cptr,H) && + if (IN_BETWEEN(LOCAL_GlobalBase,cptr,H) && GlobalIsAttVar(cptr)) { TrailTerm(trail_base) = (CELL)cptr; mark_external_reference(&TrailTerm(trail_base) PASS_REGS); @@ -1770,11 +1729,11 @@ mark_trail(tr_fr_ptr trail_ptr, tr_fr_ptr trail_base, CELL *gc_H, choiceptr gc_B remove_trash_entry: /* we can safely ignore this little monster */ #ifdef FROZEN_STACKS - discard_trail_entries += 2; + LOCAL_discard_trail_entries += 2; RESET_VARIABLE(&TrailTerm(trail_base)); RESET_VARIABLE(&TrailVal(trail_base)); #else - discard_trail_entries += 3; + LOCAL_discard_trail_entries += 3; RESET_VARIABLE(&TrailTerm(trail_base)); trail_base++; RESET_VARIABLE(&TrailTerm(trail_base)); @@ -1795,7 +1754,7 @@ mark_trail(tr_fr_ptr trail_ptr, tr_fr_ptr trail_base, CELL *gc_H, choiceptr gc_B values until the very end */ { - gc_ma_hash_entry *gl = gc_ma_h_list; + gc_ma_hash_entry *gl = LOCAL_gc_ma_h_list; while (gl) { mark_external_reference(&(TrailVal(gl->loc+1)) PASS_REGS); gl = gl->more; @@ -1804,19 +1763,19 @@ mark_trail(tr_fr_ptr trail_ptr, tr_fr_ptr trail_base, CELL *gc_H, choiceptr gc_B #endif /* TABLING */ #ifdef EASY_SHUNTING /* set back old variables */ - sTR = (tr_fr_ptr)old_cont_top0; + LOCAL_sTR = (tr_fr_ptr)old_cont_top0; while (begsTR != NULL) { tr_fr_ptr newsTR = (tr_fr_ptr)TrailTerm(begsTR); - TrailTerm(sTR) = TrailTerm(begsTR+1); - TrailTerm(sTR+1) = TrailTerm(begsTR+2); + TrailTerm(LOCAL_sTR) = TrailTerm(begsTR+1); + TrailTerm(LOCAL_sTR+1) = TrailTerm(begsTR+2); begsTR = newsTR; - sTR += 2; + LOCAL_sTR += 2; } - sTR0 = OldsTR0; + LOCAL_sTR0 = OldsTR0; #else - cont_top0 = old_cont_top0; + LOCAL_cont_top0 = old_cont_top0; #endif - cont_top = cont_top0; + LOCAL_cont_top = LOCAL_cont_top0; } /* @@ -1910,8 +1869,8 @@ mark_choicepoints(register choiceptr gc_B, tr_fr_ptr saved_TR, int very_verbose #endif /* DETERMINISTIC_TABLING */ mark_db_fixed((CELL *)(gc_B->cp_cp) PASS_REGS); #ifdef EASY_SHUNTING - current_B = gc_B; - prev_HB = HB; + LOCAL_current_B = gc_B; + LOCAL_prev_HB = HB; #endif HB = gc_B->cp_h; #ifdef INSTRUMENT_GC @@ -1940,19 +1899,19 @@ mark_choicepoints(register choiceptr gc_B, tr_fr_ptr saved_TR, int very_verbose PredEntry *pe = Yap_PredForChoicePt(gc_B); #if defined(ANALYST) || defined(DEBUG) if (pe == NULL) { - fprintf(Yap_stderr,"%% marked %ld (%s)\n", total_marked, Yap_op_names[opnum]); + fprintf(GLOBAL_stderr,"%% marked %ld (%s)\n", LOCAL_total_marked, Yap_op_names[opnum]); } else if (pe->ArityOfPE) { - fprintf(Yap_stderr,"%% %s/%d marked %ld (%s)\n", RepAtom(NameOfFunctor(pe->FunctorOfPred))->StrOfAE, pe->ArityOfPE, total_marked, Yap_op_names[opnum]); + fprintf(GLOBAL_stderr,"%% %s/%d marked %ld (%s)\n", RepAtom(NameOfFunctor(pe->FunctorOfPred))->StrOfAE, pe->ArityOfPE, LOCAL_total_marked, Yap_op_names[opnum]); } else { - fprintf(Yap_stderr,"%% %s marked %ld (%s)\n", RepAtom((Atom)(pe->FunctorOfPred))->StrOfAE, total_marked, Yap_op_names[opnum]); + fprintf(GLOBAL_stderr,"%% %s marked %ld (%s)\n", RepAtom((Atom)(pe->FunctorOfPred))->StrOfAE, LOCAL_total_marked, Yap_op_names[opnum]); } #else if (pe == NULL) { - fprintf(Yap_stderr,"%% marked %ld (%u)\n", total_marked, (unsigned int)opnum); + fprintf(GLOBAL_stderr,"%% marked %ld (%u)\n", LOCAL_total_marked, (unsigned int)opnum); } else if (pe->ArityOfPE) { - fprintf(Yap_stderr,"%% %s/%d marked %ld (%u)\n", RepAtom(NameOfFunctor(pe->FunctorOfPred))->StrOfAE, pe->ArityOfPE, total_marked, (unsigned int)opnum); + fprintf(GLOBAL_stderr,"%% %s/%d marked %ld (%u)\n", RepAtom(NameOfFunctor(pe->FunctorOfPred))->StrOfAE, pe->ArityOfPE, LOCAL_total_marked, (unsigned int)opnum); } else { - fprintf(Yap_stderr,"%% %s marked %ld (%u)\n", RepAtom((Atom)(pe->FunctorOfPred))->StrOfAE, total_marked, (unsigned int)opnum); + fprintf(GLOBAL_stderr,"%% %s marked %ld (%u)\n", RepAtom((Atom)(pe->FunctorOfPred))->StrOfAE, LOCAL_total_marked, (unsigned int)opnum); } #endif } @@ -2246,7 +2205,7 @@ mark_choicepoints(register choiceptr gc_B, tr_fr_ptr saved_TR, int very_verbose nargs = rtp->u.Otapl.s; break; default: - fprintf(Yap_stderr, "OOPS in GC: Unexpected opcode: %d\n", opnum); + fprintf(GLOBAL_stderr, "OOPS in GC: Unexpected opcode: %d\n", opnum); nargs = 0; #else default: @@ -2408,7 +2367,7 @@ sweep_trail(choiceptr gc_B, tr_fr_ptr old_TR USES_REGS) next = current; current = NULL; /* next, clean trail */ - source = dest = (tr_fr_ptr)Yap_TrailBase; + source = dest = (tr_fr_ptr)LOCAL_TrailBase; while (source < old_TR) { CELL trail_cell; @@ -2438,7 +2397,7 @@ sweep_trail(choiceptr gc_B, tr_fr_ptr old_TR USES_REGS) /* first, whatever we dumped on the trail. Easier just to do the registers separately? */ for (trail_ptr = old_TR; trail_ptr < TR; trail_ptr++) { - if (IN_BETWEEN(Yap_GlobalBase,TrailTerm(trail_ptr),Yap_TrailTop) && + if (IN_BETWEEN(LOCAL_GlobalBase,TrailTerm(trail_ptr),LOCAL_TrailTop) && MARKED_PTR(&TrailTerm(trail_ptr))) { UNMARK(&TrailTerm(trail_ptr)); if (HEAP_PTR(TrailTerm(trail_ptr))) { @@ -2448,7 +2407,7 @@ sweep_trail(choiceptr gc_B, tr_fr_ptr old_TR USES_REGS) } /* next, follows the real trail entries */ - trail_ptr = (tr_fr_ptr)Yap_TrailBase; + trail_ptr = (tr_fr_ptr)LOCAL_TrailBase; dest = trail_ptr; while (trail_ptr < old_TR) { register CELL trail_cell; @@ -2486,7 +2445,7 @@ sweep_trail(choiceptr gc_B, tr_fr_ptr old_TR USES_REGS) CELL *pt0 = RepPair(trail_cell); CELL flags; - if (IN_BETWEEN(Yap_GlobalBase, pt0, H) && GlobalIsAttVar(pt0)) { + if (IN_BETWEEN(LOCAL_GlobalBase, pt0, H) && GlobalIsAttVar(pt0)) { TrailTerm(dest) = trail_cell; /* be careful with partial gc */ if (HEAP_PTR(TrailTerm(dest))) { @@ -2500,9 +2459,9 @@ sweep_trail(choiceptr gc_B, tr_fr_ptr old_TR USES_REGS) /* process all segments */ if ( #ifdef YAPOR_SBA - (ADDR) pt0 >= Yap_GlobalBase + (ADDR) pt0 >= LOCAL_GlobalBase #else - (ADDR) pt0 >= Yap_TrailBase + (ADDR) pt0 >= LOCAL_TrailBase #endif ) { trail_ptr++; @@ -2607,7 +2566,7 @@ sweep_trail(choiceptr gc_B, tr_fr_ptr old_TR USES_REGS) #ifdef FROZEN_STACKS RESET_VARIABLE(&TrailVal(dest)); #endif - discard_trail_entries++; + LOCAL_discard_trail_entries++; } #if MULTI_ASSIGNMENT_VARIABLES } else { @@ -2682,30 +2641,30 @@ sweep_trail(choiceptr gc_B, tr_fr_ptr old_TR USES_REGS) dest++; } } - new_TR = dest; + LOCAL_new_TR = dest; if (is_gc_verbose()) { - if (old_TR != (tr_fr_ptr)Yap_TrailBase) - fprintf(Yap_stderr, + if (old_TR != (tr_fr_ptr)LOCAL_TrailBase) + fprintf(GLOBAL_stderr, "%% Trail: discarded %d (%ld%%) cells out of %ld\n", - discard_trail_entries, - (unsigned long int)(discard_trail_entries*100/(old_TR-(tr_fr_ptr)Yap_TrailBase)), - (unsigned long int)(old_TR-(tr_fr_ptr)Yap_TrailBase)); + LOCAL_discard_trail_entries, + (unsigned long int)(LOCAL_discard_trail_entries*100/(old_TR-(tr_fr_ptr)LOCAL_TrailBase)), + (unsigned long int)(old_TR-(tr_fr_ptr)LOCAL_TrailBase)); #ifdef DEBUG if (hp_entrs > 0) - fprintf(Yap_stderr, + fprintf(GLOBAL_stderr, "%% Trail: unmarked %ld dbentries (%ld%%) out of %ld\n", (long int)hp_not_in_use, (long int)(hp_not_in_use*100/hp_entrs), (long int)hp_entrs); if (hp_in_use_erased > 0 && hp_erased > 0) - fprintf(Yap_stderr, + fprintf(GLOBAL_stderr, "%% Trail: deleted %ld dbentries (%ld%%) out of %ld\n", (long int)hp_erased, (long int)(hp_erased*100/(hp_erased+hp_in_use_erased)), (long int)(hp_erased+hp_in_use_erased)); #endif if (OldHeapUsed) { - fprintf(Yap_stderr, + fprintf(GLOBAL_stderr, "%% Heap: recovered %ld bytes (%ld%%) out of %ld\n", (unsigned long int)(OldHeapUsed-HeapUsed), (unsigned long int)((OldHeapUsed-HeapUsed)/(OldHeapUsed/100)), @@ -2873,7 +2832,7 @@ sweep_choicepoints(choiceptr gc_B USES_REGS) restart_cp: /* - * fprintf(Yap_stderr,"sweeping cps: %x, %x, %x\n", + * fprintf(GLOBAL_stderr,"sweeping cps: %x, %x, %x\n", * *gc_B,CP_Extra(gc_B),CP_Nargs(gc_B)); */ /* any choice point */ @@ -3250,7 +3209,7 @@ compact_heap( USES_REGS1 ) } #endif /* TABLING */ next_hb = set_next_hb(gc_B PASS_REGS); - dest = H0 + total_marked - 1; + dest = H0 + LOCAL_total_marked - 1; gc_B = update_B_H(gc_B, H, dest+1, dest+2 #ifdef TABLING @@ -3320,14 +3279,14 @@ compact_heap( USES_REGS1 ) #ifdef DEBUG if (dest != start_from-1) - fprintf(Yap_stderr,"%% Bad Dest (%lu): %p should be %p\n", - (unsigned long int)GcCalls, + fprintf(GLOBAL_stderr,"%% Bad Dest (%lu): %p should be %p\n", + (unsigned long int)LOCAL_GcCalls, dest, - start_from); - if (total_marked != found_marked) - fprintf(Yap_stderr,"%% Upward (%lu): %lu total against %lu found\n", - (unsigned long int)GcCalls, - (unsigned long int)total_marked, + start_from-1); + if (LOCAL_total_marked != found_marked) + fprintf(GLOBAL_stderr,"%% Upward (%lu): %lu total against %lu found\n", + (unsigned long int)LOCAL_GcCalls, + (unsigned long int)LOCAL_total_marked, (unsigned long int)found_marked); found_marked = start_from-H0; #endif @@ -3383,10 +3342,10 @@ compact_heap( USES_REGS1 ) } } #ifdef DEBUG - if (total_marked != found_marked) - fprintf(Yap_stderr,"%% Downward (%lu): %lu total against %lu found\n", - (unsigned long int)GcCalls, - (unsigned long int)total_marked, + if (LOCAL_total_marked != found_marked) + fprintf(GLOBAL_stderr,"%% Downward (%lu): %lu total against %lu found\n", + (unsigned long int)LOCAL_GcCalls, + (unsigned long int)LOCAL_total_marked, (unsigned long int)found_marked); #endif @@ -3433,13 +3392,13 @@ icompact_heap( USES_REGS1 ) } #endif /* TABLING */ next_hb = set_next_hb(gc_B PASS_REGS); - dest = (CELL_PTR) H0 + total_marked - 1; + dest = (CELL_PTR) H0 + LOCAL_total_marked - 1; gc_B = update_B_H(gc_B, H, dest+1, dest+2 #ifdef TABLING , &depfr #endif /* TABLING */ ); - for (iptr = iptop - 1; iptr >= ibase; iptr--) { + for (iptr = LOCAL_iptop - 1; iptr >= ibase; iptr--) { CELL ccell; CELL_PTR current; @@ -3493,14 +3452,14 @@ icompact_heap( USES_REGS1 ) #ifdef DEBUG if (dest != H0-1) - fprintf(Yap_stderr,"%% Bad Dest (%lu): %p should be %p\n", - (unsigned long int)GcCalls, + fprintf(GLOBAL_stderr,"%% Bad Dest (%lu): %p should be %p\n", + (unsigned long int)LOCAL_GcCalls, dest, H0-1); - if (total_marked != found_marked) - fprintf(Yap_stderr,"%% Upward (%lu): %lu total against %lu found\n", - (unsigned long int)GcCalls, - (unsigned long int)total_marked, + if (LOCAL_total_marked != found_marked) + fprintf(GLOBAL_stderr,"%% Upward (%lu): %lu total against %lu found\n", + (unsigned long int)LOCAL_GcCalls, + (unsigned long int)LOCAL_total_marked, (unsigned long int)found_marked); found_marked = 0; #endif @@ -3513,7 +3472,7 @@ icompact_heap( USES_REGS1 ) */ dest = H0; - for (iptr = ibase; iptr < iptop; iptr++) { + for (iptr = ibase; iptr < LOCAL_iptop; iptr++) { CELL_PTR next; CELL *current = *iptr; CELL ccur = *current; @@ -3555,15 +3514,15 @@ icompact_heap( USES_REGS1 ) } } #ifdef DEBUG - if (H0+total_marked != dest) - fprintf(Yap_stderr,"%% Downward (%lu): %p total against %p found\n", - (unsigned long int)GcCalls, - H0+total_marked, + if (H0+LOCAL_total_marked != dest) + fprintf(GLOBAL_stderr,"%% Downward (%lu): %p total against %p found\n", + (unsigned long int)LOCAL_GcCalls, + H0+LOCAL_total_marked, dest); - if (total_marked != found_marked) - fprintf(Yap_stderr,"%% Downward (%lu): %lu total against %lu found\n", - (unsigned long int)GcCalls, - (unsigned long int)total_marked, + if (LOCAL_total_marked != found_marked) + fprintf(GLOBAL_stderr,"%% Downward (%lu): %lu total against %lu found\n", + (unsigned long int)LOCAL_GcCalls, + (unsigned long int)LOCAL_total_marked, (unsigned long int)found_marked); #endif @@ -3583,13 +3542,13 @@ icompact_heap( USES_REGS1 ) #ifdef EASY_SHUNTING static void set_conditionals(tr_fr_ptr str USES_REGS) { - while (str != sTR0) { + while (str != LOCAL_sTR0) { CELL *cptr; str -= 2; cptr = (CELL *)TrailTerm(str+1); *cptr = TrailTerm(str); } - sTR = sTR0 = NULL; + LOCAL_sTR = LOCAL_sTR0 = NULL; } #endif @@ -3604,18 +3563,18 @@ marking_phase(tr_fr_ptr old_TR, CELL *current_env, yamop *curp USES_REGS) { #ifdef EASY_SHUNTING - current_B = B; - prev_HB = H; + LOCAL_current_B = B; + LOCAL_prev_HB = H; #endif init_dbtable(old_TR PASS_REGS); #ifdef EASY_SHUNTING - sTR0 = (tr_fr_ptr)db_vec; - sTR = (tr_fr_ptr)db_vec; + LOCAL_sTR0 = (tr_fr_ptr)LOCAL_db_vec; + LOCAL_sTR = (tr_fr_ptr)LOCAL_db_vec; /* make sure we set HB before we do any variable shunting!!! */ #else - cont_top0 = (cont *)db_vec; + LOCAL_cont_top0 = (cont *)LOCAL_db_vec; #endif - cont_top = (cont *)db_vec; + LOCAL_cont_top = (cont *)LOCAL_db_vec; /* These two must be marked first so that our trail optimisation won't lose values */ mark_slots( PASS_REGS1 ); @@ -3624,7 +3583,7 @@ marking_phase(tr_fr_ptr old_TR, CELL *current_env, yamop *curp USES_REGS) mark_environments(current_env, EnvSize(curp), EnvBMap(curp) PASS_REGS); mark_choicepoints(B, old_TR, is_gc_very_verbose() PASS_REGS); /* choicepoints, and environs */ #ifdef EASY_SHUNTING - set_conditionals(sTR PASS_REGS); + set_conditionals(LOCAL_sTR PASS_REGS); #endif } @@ -3632,7 +3591,7 @@ static void sweep_oldgen(CELL *max, CELL *base USES_REGS) { CELL *ptr = base; - char *bpb = Yap_bp+(base-(CELL*)Yap_GlobalBase); + char *bpb = LOCAL_bp+(base-(CELL*)LOCAL_GlobalBase); while (ptr < max) { if (*bpb) { @@ -3656,19 +3615,19 @@ compaction_phase(tr_fr_ptr old_TR, CELL *current_env, yamop *curp USES_REGS) { CELL *CurrentH0 = NULL; - int icompact = (iptop < (CELL_PTR *)ASP && 10*total_marked < H-H0); + int icompact = (LOCAL_iptop < (CELL_PTR *)ASP && 10*LOCAL_total_marked < H-H0); if (icompact) { /* we are going to reuse the total space */ - if (HGEN != H0) { + if (LOCAL_HGEN != H0) { /* undo optimisation */ - total_marked += total_oldies; + LOCAL_total_marked += LOCAL_total_oldies; } } else { - if (HGEN != H0) { + if (LOCAL_HGEN != H0) { CurrentH0 = H0; - H0 = HGEN; - sweep_oldgen(HGEN, CurrentH0 PASS_REGS); + H0 = LOCAL_HGEN; + sweep_oldgen(LOCAL_HGEN, CurrentH0 PASS_REGS); } } sweep_slots( PASS_REGS1 ); @@ -3679,25 +3638,25 @@ compaction_phase(tr_fr_ptr old_TR, CELL *current_env, yamop *curp USES_REGS) if (icompact) { #ifdef DEBUG /* - if (total_marked + if (LOCAL_total_marked #ifdef COROUTINING - -total_smarked + -LOCAL_total_smarked #endif - != iptop-(CELL_PTR *)H && iptop < (CELL_PTR *)ASP -1024) - fprintf(Yap_stderr,"%% Oops on iptop-H (%ld) vs %ld\n", (unsigned long int)(iptop-(CELL_PTR *)H), total_marked); + != LOCAL_iptop-(CELL_PTR *)H && LOCAL_iptop < (CELL_PTR *)ASP -1024) + fprintf(GLOBAL_stderr,"%% Oops on LOCAL_iptop-H (%ld) vs %ld\n", (unsigned long int)(LOCAL_iptop-(CELL_PTR *)H), LOCAL_total_marked); */ #endif #if DEBUGX - int effectiveness = (((H-H0)-total_marked)*100)/(H-H0); - fprintf(Yap_stderr,"%% using pointers (%d)\n", effectiveness); + int effectiveness = (((H-H0)-LOCAL_total_marked)*100)/(H-H0); + fprintf(GLOBAL_stderr,"%% using pointers (%d)\n", effectiveness); #endif if (CurrentH0) { H0 = CurrentH0; - HGEN = H0; - total_marked += total_oldies; + LOCAL_HGEN = H0; + LOCAL_total_marked += LOCAL_total_oldies; CurrentH0 = NULL; } - quicksort((CELL_PTR *)H, 0, (iptop-(CELL_PTR *)H)-1); + quicksort((CELL_PTR *)H, 0, (LOCAL_iptop-(CELL_PTR *)H)-1); icompact_heap( PASS_REGS1 ); } else #endif /* HYBRID_SCHEME */ @@ -3705,8 +3664,8 @@ compaction_phase(tr_fr_ptr old_TR, CELL *current_env, yamop *curp USES_REGS) #ifdef DEBUG /* #ifdef HYBRID_SCHEME - int effectiveness = (((H-H0)-total_marked)*100)/(H-H0); - fprintf(stderr,"%% not using pointers (%d) ASP: %p, ip %p (expected %p) \n", effectiveness, ASP, iptop, H+total_marked); + int effectiveness = (((H-H0)-LOCAL_total_marked)*100)/(H-H0); + fprintf(stderr,"%% not using pointers (%d) ASP: %p, ip %p (expected %p) \n", effectiveness, ASP, LOCAL_iptop, H+LOCAL_total_marked); #endif */ @@ -3733,7 +3692,7 @@ do_gc(Int predarity, CELL *current_env, yamop *nextop USES_REGS) gc_verbose = is_gc_verbose(); effectiveness = 0; gc_trace = FALSE; - GcCalls++; + LOCAL_GcCalls++; #ifdef INSTRUMENT_GC { int i; @@ -3760,22 +3719,22 @@ do_gc(Int predarity, CELL *current_env, yamop *nextop USES_REGS) if (Yap_GetValue(AtomGcTrace) != TermNil) gc_trace = 1; if (gc_trace) { - fprintf(Yap_stderr, "%% gc\n"); + fprintf(GLOBAL_stderr, "%% gc\n"); } else if (gc_verbose) { #if defined(YAPOR) || defined(THREADS) - fprintf(Yap_stderr, "%% Worker Id %d:\n", worker_id); + fprintf(GLOBAL_stderr, "%% Worker Id %d:\n", worker_id); #endif - fprintf(Yap_stderr, "%% Start of garbage collection %lu:\n", (unsigned long int)GcCalls); - fprintf(Yap_stderr, "%% Global: %8ld cells (%p-%p)\n", (long int)heap_cells,H0,H); - fprintf(Yap_stderr, "%% Local:%8ld cells (%p-%p)\n", (unsigned long int)(LCL0-ASP),LCL0,ASP); - fprintf(Yap_stderr, "%% Trail:%8ld cells (%p-%p)\n", - (unsigned long int)(TR-(tr_fr_ptr)Yap_TrailBase),Yap_TrailBase,TR); + fprintf(GLOBAL_stderr, "%% Start of garbage collection %lu:\n", (unsigned long int)LOCAL_GcCalls); + fprintf(GLOBAL_stderr, "%% Global: %8ld cells (%p-%p)\n", (long int)heap_cells,H0,H); + fprintf(GLOBAL_stderr, "%% Local:%8ld cells (%p-%p)\n", (unsigned long int)(LCL0-ASP),LCL0,ASP); + fprintf(GLOBAL_stderr, "%% Trail:%8ld cells (%p-%p)\n", + (unsigned long int)(TR-(tr_fr_ptr)LOCAL_TrailBase),LOCAL_TrailBase,TR); } #if !USE_SYSTEM_MALLOC - if (HeapTop >= Yap_GlobalBase - MinHeapGap) { + if (HeapTop >= LOCAL_GlobalBase - MinHeapGap) { *--ASP = (CELL)current_env; if (!Yap_growheap(FALSE, MinHeapGap, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return -1; } current_env = (CELL *)*ASP; @@ -3783,15 +3742,15 @@ do_gc(Int predarity, CELL *current_env, yamop *nextop USES_REGS) } #endif time_start = Yap_cputime(); - if (sigsetjmp(Yap_gc_restore, 0) == 2) { + if (sigsetjmp(LOCAL_gc_restore, 0) == 2) { UInt sz; /* we cannot recover, fail system */ restore_machine_regs(); - sz = Yap_TrailTop-(ADDR)OldTR; + sz = LOCAL_TrailTop-(ADDR)LOCAL_OldTR; /* ask for double the size */ sz = 2*sz; - TR = OldTR; + TR = LOCAL_OldTR; *--ASP = (CELL)current_env; if ( @@ -3800,62 +3759,62 @@ do_gc(Int predarity, CELL *current_env, yamop *nextop USES_REGS) Yap_Error(OUT_OF_TRAIL_ERROR,TermNil,"out of %lB during gc", sz); return -1; } else { - total_marked = 0; - total_oldies = 0; + LOCAL_total_marked = 0; + LOCAL_total_oldies = 0; #ifdef COROUTING - total_smarked = 0; + LOCAL_total_smarked = 0; #endif - discard_trail_entries = 0; + LOCAL_discard_trail_entries = 0; current_env = (CELL *)*ASP; ASP++; } } #if EASY_SHUNTING - sTR0 = sTR = NULL; + LOCAL_sTR0 = LOCAL_sTR = NULL; #endif - total_marked = 0; - total_oldies = 0; + LOCAL_total_marked = 0; + LOCAL_total_oldies = 0; #ifdef COROUTING - total_smarked = 0; + LOCAL_total_smarked = 0; #endif - discard_trail_entries = 0; - alloc_sz = (CELL *)Yap_TrailTop-(CELL*)Yap_GlobalBase; - Yap_bp = Yap_PreAllocCodeSpace(); - while (Yap_bp+alloc_sz > (char *)AuxSp) { + LOCAL_discard_trail_entries = 0; + alloc_sz = (CELL *)LOCAL_TrailTop-(CELL*)LOCAL_GlobalBase; + LOCAL_bp = Yap_PreAllocCodeSpace(); + while (LOCAL_bp+alloc_sz > (char *)AuxSp) { /* not enough space */ *--ASP = (CELL)current_env; - Yap_bp = (char *)Yap_ExpandPreAllocCodeSpace(alloc_sz, NULL, TRUE); - if (!Yap_bp) + LOCAL_bp = (char *)Yap_ExpandPreAllocCodeSpace(alloc_sz, NULL, TRUE); + if (!LOCAL_bp) return -1; current_env = (CELL *)*ASP; ASP++; } - memset((void *)Yap_bp, 0, alloc_sz); + memset((void *)LOCAL_bp, 0, alloc_sz); #ifdef HYBRID_SCHEME - iptop = (CELL_PTR *)H; + LOCAL_iptop = (CELL_PTR *)H; #endif /* get the number of active registers */ - HGEN = VarOfTerm(Yap_ReadTimedVar(GcGeneration)); + LOCAL_HGEN = VarOfTerm(Yap_ReadTimedVar(LOCAL_GcGeneration)); - gc_phase = (UInt)IntegerOfTerm(Yap_ReadTimedVar(GcPhase)); - /* old HGEN are not very reliable, but still may have data to recover */ - if (gc_phase != GcCurrentPhase) { - HGEN = H0; + gc_phase = (UInt)IntegerOfTerm(Yap_ReadTimedVar(LOCAL_GcPhase)); + /* old LOCAL_HGEN are not very reliable, but still may have data to recover */ + if (gc_phase != LOCAL_GcCurrentPhase) { + LOCAL_HGEN = H0; } - /* fprintf(stderr,"HGEN is %ld, %p, %p/%p\n", IntegerOfTerm(Yap_ReadTimedVar(GcGeneration)), HGEN, H,H0);*/ - OldTR = (tr_fr_ptr)(old_TR = TR); + /* fprintf(stderr,"LOCAL_HGEN is %ld, %p, %p/%p\n", IntegerOfTerm(Yap_ReadTimedVar(LOCAL_GcGeneration)), LOCAL_HGEN, H,H0);*/ + LOCAL_OldTR = (tr_fr_ptr)(old_TR = TR); push_registers(predarity, nextop PASS_REGS); /* make sure we clean bits after a reset */ marking_phase(old_TR, current_env, nextop PASS_REGS); - if (total_oldies > ((HGEN-H0)*8)/10) { - total_marked -= total_oldies; - tot = total_marked+(HGEN-H0); + if (LOCAL_total_oldies > ((LOCAL_HGEN-H0)*8)/10) { + LOCAL_total_marked -= LOCAL_total_oldies; + tot = LOCAL_total_marked+(LOCAL_HGEN-H0); } else { - if (HGEN != H0) { - HGEN = H0; - GcCurrentPhase++; + if (LOCAL_HGEN != H0) { + LOCAL_HGEN = H0; + LOCAL_GcCurrentPhase++; } - tot = total_marked; + tot = LOCAL_total_marked; } m_time = Yap_cputime(); gc_time = m_time-time_start; @@ -3867,21 +3826,21 @@ do_gc(Int predarity, CELL *current_env, yamop *nextop USES_REGS) } else effectiveness = 0; if (gc_verbose) { - fprintf(Yap_stderr, "%% Mark: Marked %ld cells of %ld (efficiency: %ld%%) in %g sec\n", + fprintf(GLOBAL_stderr, "%% Mark: Marked %ld cells of %ld (efficiency: %ld%%) in %g sec\n", (long int)tot, (long int)heap_cells, (long int)effectiveness, (double)(m_time-time_start)/1000); - if (HGEN-H0) - fprintf(Yap_stderr,"%% previous generation has size " UInt_FORMAT ", with " UInt_FORMAT " (" UInt_FORMAT "%%) unmarked\n", (UInt)(HGEN-H0), (UInt)((HGEN-H0)-total_oldies), (UInt)(100*((HGEN-H0)-total_oldies)/(HGEN-H0))); + if (LOCAL_HGEN-H0) + fprintf(GLOBAL_stderr,"%% previous generation has size " UInt_FORMAT ", with " UInt_FORMAT " (" UInt_FORMAT "%%) unmarked\n", (UInt)(LOCAL_HGEN-H0), (UInt)((LOCAL_HGEN-H0)-LOCAL_total_oldies), (UInt)(100*((LOCAL_HGEN-H0)-LOCAL_total_oldies)/(LOCAL_HGEN-H0))); #ifdef INSTRUMENT_GC { int i; for (i=0; i<16; i++) { if (chain[i]) { - fprintf(Yap_stderr, "%% chain[%d]=%lu\n", i, chain[i]); + fprintf(GLOBAL_stderr, "%% chain[%d]=%lu\n", i, chain[i]); } } put_type_info((unsigned long int)tot); - fprintf(Yap_stderr,"%% %lu/%ld before and %lu/%ld after\n", old_vars, (unsigned long int)(B->cp_h-H0), new_vars, (unsigned long int)(H-B->cp_h)); - fprintf(Yap_stderr,"%% %ld choicepoints\n", num_bs); + fprintf(GLOBAL_stderr,"%% %lu/%ld before and %lu/%ld after\n", old_vars, (unsigned long int)(B->cp_h-H0), new_vars, (unsigned long int)(H-B->cp_h)); + fprintf(GLOBAL_stderr,"%% %ld choicepoints\n", num_bs); } #endif } @@ -3889,23 +3848,23 @@ do_gc(Int predarity, CELL *current_env, yamop *nextop USES_REGS) compaction_phase(old_TR, current_env, nextop PASS_REGS); TR = old_TR; pop_registers(predarity, nextop PASS_REGS); - TR = new_TR; - /* fprintf(Yap_stderr,"NEW HGEN %ld (%ld)\n", H-H0, HGEN-H0);*/ + TR = LOCAL_new_TR; + /* fprintf(GLOBAL_stderr,"NEW LOCAL_HGEN %ld (%ld)\n", H-H0, LOCAL_HGEN-H0);*/ { Term t = MkVarTerm(); - Yap_UpdateTimedVar(GcGeneration, t); + Yap_UpdateTimedVar(LOCAL_GcGeneration, t); } - Yap_UpdateTimedVar(GcPhase, MkIntegerTerm(GcCurrentPhase)); + Yap_UpdateTimedVar(LOCAL_GcPhase, MkIntegerTerm(LOCAL_GcCurrentPhase)); c_time = Yap_cputime(); if (gc_verbose) { - fprintf(Yap_stderr, "%% Compress: took %g sec\n", (double)(c_time-time_start)/1000); + fprintf(GLOBAL_stderr, "%% Compress: took %g sec\n", (double)(c_time-time_start)/1000); } gc_time += (c_time-time_start); - TotGcTime += gc_time; - TotGcRecovered += heap_cells-tot; + LOCAL_TotGcTime += gc_time; + LOCAL_TotGcRecovered += heap_cells-tot; if (gc_verbose) { - fprintf(Yap_stderr, "%% GC %lu took %g sec, total of %g sec doing GC so far.\n", (unsigned long int)GcCalls, (double)gc_time/1000, (double)TotGcTime/1000); - fprintf(Yap_stderr, "%% Left %ld cells free in stacks.\n", + fprintf(GLOBAL_stderr, "%% GC %lu took %g sec, total of %g sec doing GC so far.\n", (unsigned long int)LOCAL_GcCalls, (double)gc_time/1000, (double)LOCAL_TotGcTime/1000); + fprintf(GLOBAL_stderr, "%% Left %ld cells free in stacks.\n", (unsigned long int)(ASP-H)); } check_global(); @@ -3915,7 +3874,8 @@ do_gc(Int predarity, CELL *current_env, yamop *nextop USES_REGS) static int is_gc_verbose(void) { - if (Yap_PrologMode == BootMode) + CACHE_REGS + if (LOCAL_PrologMode == BootMode) return FALSE; #ifdef INSTRUMENT_GC /* always give info when we are debugging gc */ @@ -3935,7 +3895,8 @@ Yap_is_gc_verbose(void) static int is_gc_very_verbose(void) { - if (Yap_PrologMode == BootMode) + CACHE_REGS + if (LOCAL_PrologMode == BootMode) return FALSE; return Yap_GetValue(AtomGcVeryVerbose) != TermNil; } @@ -3944,15 +3905,15 @@ Int Yap_total_gc_time(void) { CACHE_REGS - return(TotGcTime); + return(LOCAL_TotGcTime); } static Int p_inform_gc( USES_REGS1 ) { - Term tn = MkIntegerTerm(TotGcTime); - Term tt = MkIntegerTerm(GcCalls); - Term ts = Yap_Mk64IntegerTerm((TotGcRecovered*sizeof(CELL))); + Term tn = MkIntegerTerm(LOCAL_TotGcTime); + Term tt = MkIntegerTerm(LOCAL_GcCalls); + Term ts = Yap_Mk64IntegerTerm((LOCAL_TotGcRecovered*sizeof(CELL))); return(Yap_unify(tn, ARG2) && Yap_unify(tt, ARG1) && Yap_unify(ts, ARG3)); @@ -3975,23 +3936,23 @@ call_gc(UInt gc_lim, Int predarity, CELL *current_env, yamop *nextop USES_REGS) gc_t = TRUE; } else { /* only go exponential for the first 6 calls, that would ask about 2MB minimum */ - if (GcCalls < 8) - gc_margin <<= GcCalls; + if (LOCAL_GcCalls < 8) + gc_margin <<= LOCAL_GcCalls; else { /* next grow linearly */ gc_margin <<= 8; /* don't do this: it forces the system to ask for ever more stack!! - gc_margin *= GcCalls; + gc_margin *= LOCAL_GcCalls; */ } } if (gc_margin < gc_lim) gc_margin = gc_lim; - HGEN = VarOfTerm(Yap_ReadTimedVar(GcGeneration)); - if (gc_on && !(Yap_PrologMode & InErrorMode) && + LOCAL_HGEN = VarOfTerm(Yap_ReadTimedVar(LOCAL_GcGeneration)); + if (gc_on && !(LOCAL_PrologMode & InErrorMode) && /* make sure there is a point in collecting the heap */ (ASP-H0)*sizeof(CELL) > gc_lim && - H-HGEN > (LCL0-ASP)/2) { + H-LOCAL_HGEN > (LCL0-ASP)/2) { effectiveness = do_gc(predarity, current_env, nextop PASS_REGS); if (effectiveness < 0) return FALSE; @@ -4020,10 +3981,10 @@ call_gc(UInt gc_lim, Int predarity, CELL *current_env, yamop *nextop USES_REGS) static void LeaveGCMode( USES_REGS1 ) { - if (Yap_PrologMode & GCMode) - Yap_PrologMode &= ~GCMode; - if (Yap_PrologMode & AbortMode) { - Yap_PrologMode &= ~AbortMode; + if (LOCAL_PrologMode & GCMode) + LOCAL_PrologMode &= ~GCMode; + if (LOCAL_PrologMode & AbortMode) { + LOCAL_PrologMode &= ~AbortMode; Yap_Error(PURE_ABORT, TermNil, ""); P = FAILCODE; } @@ -4034,11 +3995,11 @@ Yap_gc(Int predarity, CELL *current_env, yamop *nextop) { CACHE_REGS int res; - Yap_PrologMode |= GCMode; + LOCAL_PrologMode |= GCMode; res=call_gc(4096, predarity, current_env, nextop PASS_REGS); LeaveGCMode( PASS_REGS1 ); - if (Yap_PrologMode & GCMode) - Yap_PrologMode &= ~GCMode; + if (LOCAL_PrologMode & GCMode) + LOCAL_PrologMode &= ~GCMode; return res; } @@ -4049,7 +4010,7 @@ Yap_gcl(UInt gc_lim, Int predarity, CELL *current_env, yamop *nextop) int res; UInt min = CalculateStackGap()*sizeof(CELL); - Yap_PrologMode |= GCMode; + LOCAL_PrologMode |= GCMode; if (gc_lim < min) gc_lim = min; res = call_gc(gc_lim, predarity, current_env, nextop PASS_REGS); @@ -4062,7 +4023,7 @@ static Int p_gc( USES_REGS1 ) { int res; - Yap_PrologMode |= GCMode; + LOCAL_PrologMode |= GCMode; if (P->opc == Yap_opcode(_execute_cpred)) res = do_gc(0, ENV, CP PASS_REGS) >= 0; else @@ -4082,5 +4043,5 @@ void Yap_inc_mark_variable() { CACHE_REGS - total_marked++; + LOCAL_total_marked++; } diff --git a/C/index.c b/C/index.c index cbfac4ff9..20140c7e2 100644 --- a/C/index.c +++ b/C/index.c @@ -832,14 +832,14 @@ sort_group(GroupDef *grp, CELL *top, struct intermediates *cint) if (!(base = (CELL *)Yap_AllocCodeSpace(2*max*sizeof(CELL)))) { CACHE_REGS save_machine_regs(); - Yap_Error_Size = 2*max*sizeof(CELL); + LOCAL_Error_Size = 2*max*sizeof(CELL); siglongjmp(cint->CompilerBotch,2); } #else base = top; - while (top+2*max > (CELL *)Yap_TrailTop) { + while (top+2*max > (CELL *)LOCAL_TrailTop) { if (!Yap_growtrail(2*max*CellSize, TRUE)) { - Yap_Error_Size = 2*max*CellSize; + LOCAL_Error_Size = 2*max*CellSize; save_machine_regs(); siglongjmp(cint->CompilerBotch,4); return; @@ -2058,16 +2058,16 @@ groups_in(ClauseDef *min, ClauseDef *max, GroupDef *grp, struct intermediates *c } groups++; grp++; - while (grp+16 > (GroupDef *)Yap_TrailTop) { + while (grp+16 > (GroupDef *)LOCAL_TrailTop) { UInt sz = (groups+16)*sizeof(GroupDef); #if USE_SYSTEM_MALLOC - Yap_Error_Size = sz; + LOCAL_Error_Size = sz; /* grow stack */ save_machine_regs(); siglongjmp(cint->CompilerBotch,4); #else if (!Yap_growtrail(sz, TRUE)) { - Yap_Error_Size = sz; + LOCAL_Error_Size = sz; save_machine_regs(); siglongjmp(cint->CompilerBotch,4); return 0; @@ -2197,7 +2197,7 @@ emit_switch_space(UInt n, UInt item_size, struct intermediates *cint, CELL func_ UInt sz = sizeof(LogUpdIndex)+n*item_size; LogUpdIndex *cl = (LogUpdIndex *)Yap_AllocCodeSpace(sz); if (cl == NULL) { - Yap_Error_Size = sz; + LOCAL_Error_Size = sz; /* grow stack */ save_machine_regs(); siglongjmp(cint->CompilerBotch,2); @@ -2218,7 +2218,7 @@ emit_switch_space(UInt n, UInt item_size, struct intermediates *cint, CELL func_ UInt sz = sizeof(StaticIndex)+n*item_size; StaticIndex *cl = (StaticIndex *)Yap_AllocCodeSpace(sz); if (cl == NULL) { - Yap_Error_Size = sz; + LOCAL_Error_Size = sz; /* grow stack */ save_machine_regs(); siglongjmp(cint->CompilerBotch,2); @@ -3147,8 +3147,8 @@ copy_clauses(ClauseDef *max0, ClauseDef *min0, CELL *top, struct intermediates * { CACHE_REGS UInt sz = ((max0+1)-min0)*sizeof(ClauseDef); - if ((char *)top + sz >= Yap_TrailTop-4096) { - Yap_Error_Size = sz; + if ((char *)top + sz >= LOCAL_TrailTop-4096) { + LOCAL_Error_Size = sz; /* grow stack */ save_machine_regs(); siglongjmp(cint->CompilerBotch,4); @@ -3337,13 +3337,13 @@ compile_index(struct intermediates *cint) /* only global variable I use directly */ cint->i_labelno = 1; - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; #if USE_SYSTEM_MALLOC if (!cint->cls) { cint->cls = (ClauseDef *)Yap_AllocCodeSpace(NClauses*sizeof(ClauseDef)); if (!cint->cls) { /* tell how much space we need */ - Yap_Error_Size += NClauses*sizeof(ClauseDef); + LOCAL_Error_Size += NClauses*sizeof(ClauseDef); /* grow stack */ save_machine_regs(); siglongjmp(cint->CompilerBotch,2); @@ -3355,7 +3355,7 @@ compile_index(struct intermediates *cint) cint->cls = (ClauseDef *)H; if (cint->cls+2*NClauses > (ClauseDef *)(ASP-4096)) { /* tell how much space we need */ - Yap_Error_Size += NClauses*sizeof(ClauseDef); + LOCAL_Error_Size += NClauses*sizeof(ClauseDef); /* grow stack */ save_machine_regs(); siglongjmp(cint->CompilerBotch,3); @@ -3402,37 +3402,37 @@ Yap_PredIsIndexable(PredEntry *ap, UInt NSlots, yamop *next_pc) cint.code_addr = NULL; cint.blks = NULL; cint.cls = NULL; - Yap_Error_Size = 0; + LOCAL_Error_Size = 0; if ((setjres = sigsetjmp(cint.CompilerBotch, 0)) == 3) { restore_machine_regs(); recover_from_failed_susp_on_cls(&cint, 0); - if (!Yap_gcl(Yap_Error_Size, ap->ArityOfPE+NSlots, ENV, next_pc)) { + if (!Yap_gcl(LOCAL_Error_Size, ap->ArityOfPE+NSlots, ENV, next_pc)) { CleanCls(&cint); - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FAILCODE; } } else if (setjres == 2) { restore_machine_regs(); - Yap_Error_Size = recover_from_failed_susp_on_cls(&cint, Yap_Error_Size); - if (!Yap_growheap(FALSE, Yap_Error_Size, NULL)) { + LOCAL_Error_Size = recover_from_failed_susp_on_cls(&cint, LOCAL_Error_Size); + if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) { CleanCls(&cint); - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FAILCODE; } } else if (setjres == 4) { restore_machine_regs(); recover_from_failed_susp_on_cls(&cint, 0); - if (!Yap_growtrail(Yap_Error_Size, FALSE)) { + if (!Yap_growtrail(LOCAL_Error_Size, FALSE)) { CleanCls(&cint); - Yap_Error(OUT_OF_TRAIL_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_TRAIL_ERROR, TermNil, LOCAL_ErrorMessage); return FAILCODE; } } else if (setjres != 0) { restore_machine_regs(); recover_from_failed_susp_on_cls(&cint, 0); - if (!Yap_growheap(FALSE, Yap_Error_Size, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) { + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); CleanCls(&cint); return FAILCODE; } @@ -3442,25 +3442,25 @@ Yap_PredIsIndexable(PredEntry *ap, UInt NSlots, yamop *next_pc) cint.CodeStart = cint.BlobsStart = cint.cpc = cint.icpc = NULL; cint.expand_block = NULL; cint.label_offset = NULL; - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; if (compile_index(&cint) == (UInt)FAILCODE) { Yap_ReleaseCMem(&cint); CleanCls(&cint); return FAILCODE; } #ifdef DEBUG - if (Yap_Option['i' - 'a' + 1]) { + if (GLOBAL_Option['i' - 'a' + 1]) { Yap_ShowCode(&cint); } #endif /* globals for assembler */ - IPredArity = ap->ArityOfPE; + LOCAL_IPredArity = ap->ArityOfPE; if (cint.CodeStart) { if ((indx_out = Yap_assemble(ASSEMBLING_INDEX, TermNil, ap, FALSE, &cint, cint.i_labelno+1)) == NULL) { - if (!Yap_growheap(FALSE, Yap_Error_Size, NULL)) { + if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) { Yap_ReleaseCMem(&cint); CleanCls(&cint); - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return NULL; } goto restart_index; @@ -3483,7 +3483,7 @@ static istack_entry * push_stack(istack_entry *sp, Int arg, Term Tag, Term extra, struct intermediates *cint) { CACHE_REGS - if (sp+1 > (istack_entry *)Yap_TrailTop) { + if (sp+1 > (istack_entry *)LOCAL_TrailTop) { save_machine_regs(); siglongjmp(cint->CompilerBotch,4); } @@ -4369,7 +4369,7 @@ expand_index(struct intermediates *cint) { cint->cls = (ClauseDef *)Yap_AllocCodeSpace(nclauses*sizeof(ClauseDef)); if (!cint->cls) { /* tell how much space we need */ - Yap_Error_Size += NClauses*sizeof(ClauseDef); + LOCAL_Error_Size += NClauses*sizeof(ClauseDef); /* grow stack */ save_machine_regs(); siglongjmp(cint->CompilerBotch,2); @@ -4379,7 +4379,7 @@ expand_index(struct intermediates *cint) { cint->cls = (ClauseDef *)H; if (cint->cls+2*nclauses > (ClauseDef *)(ASP-4096)) { /* tell how much space we need (worst case) */ - Yap_Error_Size += 2*NClauses*sizeof(ClauseDef); + LOCAL_Error_Size += 2*NClauses*sizeof(ClauseDef); /* grow stack */ save_machine_regs(); siglongjmp(cint->CompilerBotch,3); @@ -4397,7 +4397,7 @@ expand_index(struct intermediates *cint) { cint->cls = (ClauseDef *)Yap_AllocCodeSpace(NClauses*sizeof(ClauseDef)); if (!cint->cls) { /* tell how much space we need */ - Yap_Error_Size += NClauses*sizeof(ClauseDef); + LOCAL_Error_Size += NClauses*sizeof(ClauseDef); /* grow stack */ save_machine_regs(); siglongjmp(cint->CompilerBotch,2); @@ -4407,7 +4407,7 @@ expand_index(struct intermediates *cint) { cint->cls = (ClauseDef *)H; if (cint->cls+2*NClauses > (ClauseDef *)(ASP-4096)) { /* tell how much space we need (worst case) */ - Yap_Error_Size += 2*NClauses*sizeof(ClauseDef); + LOCAL_Error_Size += 2*NClauses*sizeof(ClauseDef); save_machine_regs(); siglongjmp(cint->CompilerBotch,3); } @@ -4513,11 +4513,11 @@ ExpandIndex(PredEntry *ap, int ExtraArgs, yamop *nextop USES_REGS) { restore_machine_regs(); /* grow stack */ recover_from_failed_susp_on_cls(&cint, 0); - Yap_gcl(Yap_Error_Size, ap->ArityOfPE+ExtraArgs, ENV, nextop); + Yap_gcl(LOCAL_Error_Size, ap->ArityOfPE+ExtraArgs, ENV, nextop); } else if (cb == 2) { restore_machine_regs(); - Yap_Error_Size = recover_from_failed_susp_on_cls(&cint, Yap_Error_Size); - if (!Yap_growheap(FALSE, Yap_Error_Size, NULL)) { + LOCAL_Error_Size = recover_from_failed_susp_on_cls(&cint, LOCAL_Error_Size); + if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) { save_machine_regs(); if (ap->PredFlags & LogUpdatePredFlag) { Yap_kill_iblock((ClauseUnion *)ClauseCodeToLogUpdIndex(ap->cs.p_code.TrueCodeOfPred),NULL, ap); @@ -4540,14 +4540,14 @@ ExpandIndex(PredEntry *ap, int ExtraArgs, yamop *nextop USES_REGS) { #if defined(YAPOR) || defined(THREADS) } #endif - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); CleanCls(&cint); return FAILCODE; } } else if (cb == 4) { restore_machine_regs(); Yap_ReleaseCMem(&cint); - if (!Yap_growtrail(Yap_Error_Size, FALSE)) { + if (!Yap_growtrail(LOCAL_Error_Size, FALSE)) { save_machine_regs(); if (ap->PredFlags & LogUpdatePredFlag) { Yap_kill_iblock((ClauseUnion *)ClauseCodeToLogUpdIndex(ap->cs.p_code.TrueCodeOfPred),NULL, ap); @@ -4564,25 +4564,25 @@ ExpandIndex(PredEntry *ap, int ExtraArgs, yamop *nextop USES_REGS) { restart_index: cint.CodeStart = cint.cpc = cint.BlobsStart = cint.icpc = NIL; cint.CurrentPred = ap; - Yap_ErrorMessage = NULL; - Yap_Error_Size = 0; + LOCAL_ErrorMessage = NULL; + LOCAL_Error_Size = 0; if (P->opc == Yap_opcode(_expand_clauses)) { expand_clauses = P; } else { expand_clauses = NULL; } #ifdef DEBUG - if (Yap_Option['i' - 'a' + 1]) { + if (GLOBAL_Option['i' - 'a' + 1]) { Term tmod = ap->ModuleOfPred; if (!tmod) tmod = TermProlog; #if THREADS Yap_DebugPlWrite(MkIntegerTerm(worker_id)); - Yap_DebugPutc(Yap_c_error_stream,' '); + Yap_DebugPutc(LOCAL_c_error_stream,' '); #endif - Yap_DebugPutc(Yap_c_error_stream,'>'); - Yap_DebugPutc(Yap_c_error_stream,'\t'); + Yap_DebugPutc(LOCAL_c_error_stream,'>'); + Yap_DebugPutc(LOCAL_c_error_stream,'\t'); Yap_DebugPlWrite(tmod); - Yap_DebugPutc(Yap_c_error_stream,':'); + Yap_DebugPutc(LOCAL_c_error_stream,':'); if (ap->ModuleOfPred == IDB_MODULE) { Term t = Deref(ARG1); if (IsAtomTerm(t)) { @@ -4593,7 +4593,7 @@ ExpandIndex(PredEntry *ap, int ExtraArgs, yamop *nextop USES_REGS) { Functor f = FunctorOfTerm(t); Atom At = NameOfFunctor(f); Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(Yap_c_error_stream,'/'); + Yap_DebugPutc(LOCAL_c_error_stream,'/'); Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); } } else { @@ -4604,14 +4604,14 @@ ExpandIndex(PredEntry *ap, int ExtraArgs, yamop *nextop USES_REGS) { Functor f = ap->FunctorOfPred; Atom At = NameOfFunctor(f); Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(Yap_c_error_stream,'/'); + Yap_DebugPutc(LOCAL_c_error_stream,'/'); Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); } } - Yap_DebugPutc(Yap_c_error_stream,'\n'); + Yap_DebugPutc(LOCAL_c_error_stream,'\n'); #if THREADS Yap_DebugPlWrite(MkIntegerTerm(worker_id)); - Yap_DebugPutc(Yap_c_error_stream,' '); + Yap_DebugPutc(LOCAL_c_error_stream,' '); #endif } #endif @@ -4634,16 +4634,16 @@ ExpandIndex(PredEntry *ap, int ExtraArgs, yamop *nextop USES_REGS) { return FAILCODE; } #ifdef DEBUG - if (Yap_Option['i' - 'a' + 1]) { + if (GLOBAL_Option['i' - 'a' + 1]) { Yap_ShowCode(&cint); } #endif /* globals for assembler */ - IPredArity = ap->ArityOfPE; + LOCAL_IPredArity = ap->ArityOfPE; if (cint.CodeStart) { if ((indx_out = Yap_assemble(ASSEMBLING_EINDEX, TermNil, ap, FALSE, &cint, cint.i_labelno+1)) == NULL) { - if (!Yap_growheap(FALSE, Yap_Error_Size, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + if (!Yap_growheap(FALSE, LOCAL_Error_Size, NULL)) { + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); Yap_ReleaseCMem(&cint); CleanCls(&cint); return FAILCODE; @@ -4715,7 +4715,7 @@ static path_stack_entry * push_path(path_stack_entry *sp, yamop **pipc, ClauseDef *clp, struct intermediates *cint) { CACHE_REGS - if (sp+1 > (path_stack_entry *)Yap_TrailTop) { + if (sp+1 > (path_stack_entry *)LOCAL_TrailTop) { save_machine_regs(); siglongjmp(cint->CompilerBotch,4); } @@ -4732,7 +4732,7 @@ static path_stack_entry * fetch_new_block(path_stack_entry *sp, yamop **pipc, PredEntry *ap, struct intermediates *cint) { CACHE_REGS - if (sp+1 > (path_stack_entry *)Yap_TrailTop) { + if (sp+1 > (path_stack_entry *)LOCAL_TrailTop) { save_machine_regs(); siglongjmp(cint->CompilerBotch,4); } @@ -6028,31 +6028,31 @@ Yap_AddClauseToIndex(PredEntry *ap, yamop *beg, int first) { cint.CodeStart = cint.BlobsStart = cint.cpc = cint.icpc = NIL; if ((cb = sigsetjmp(cint.CompilerBotch, 0)) == 3) { restore_machine_regs(); - Yap_gcl(Yap_Error_Size, ap->ArityOfPE, ENV, CP); + Yap_gcl(LOCAL_Error_Size, ap->ArityOfPE, ENV, CP); save_machine_regs(); } else if (cb == 2) { restore_machine_regs(); - Yap_growheap(FALSE, Yap_Error_Size, NULL); + Yap_growheap(FALSE, LOCAL_Error_Size, NULL); save_machine_regs(); } else if (cb == 4) { restore_machine_regs(); - Yap_growtrail(Yap_Error_Size, FALSE); + Yap_growtrail(LOCAL_Error_Size, FALSE); save_machine_regs(); } if (cb) { Yap_RemoveIndexation(ap); return; } - Yap_Error_Size = 0; - Yap_ErrorMessage = NULL; + LOCAL_Error_Size = 0; + LOCAL_ErrorMessage = NULL; #ifdef DEBUG - if (Yap_Option['i' - 'a' + 1]) { + if (GLOBAL_Option['i' - 'a' + 1]) { Term tmod = ap->ModuleOfPred; if (!tmod) tmod = TermProlog; - Yap_DebugPutc(Yap_c_error_stream,'+'); - Yap_DebugPutc(Yap_c_error_stream,'\t'); + Yap_DebugPutc(LOCAL_c_error_stream,'+'); + Yap_DebugPutc(LOCAL_c_error_stream,'\t'); Yap_DebugPlWrite(tmod); - Yap_DebugPutc(Yap_c_error_stream,':'); + Yap_DebugPutc(LOCAL_c_error_stream,':'); if (ap->ModuleOfPred == IDB_MODULE) { Term t = Deref(ARG1); if (IsAtomTerm(t)) { @@ -6063,7 +6063,7 @@ Yap_AddClauseToIndex(PredEntry *ap, yamop *beg, int first) { Functor f = FunctorOfTerm(t); Atom At = NameOfFunctor(f); Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(Yap_c_error_stream,'/'); + Yap_DebugPutc(LOCAL_c_error_stream,'/'); Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); } } else { @@ -6074,11 +6074,11 @@ Yap_AddClauseToIndex(PredEntry *ap, yamop *beg, int first) { Functor f = ap->FunctorOfPred; Atom At = NameOfFunctor(f); Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(Yap_c_error_stream,'/'); + Yap_DebugPutc(LOCAL_c_error_stream,'/'); Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); } } - Yap_DebugPutc(Yap_c_error_stream,'\n'); + Yap_DebugPutc(LOCAL_c_error_stream,'\n'); } #endif stack = (path_stack_entry *)TR; @@ -6504,19 +6504,19 @@ Yap_RemoveClauseFromIndex(PredEntry *ap, yamop *beg) { cint.CodeStart = cint.BlobsStart = cint.cpc = cint.icpc = NULL; if ((cb = sigsetjmp(cint.CompilerBotch, 0)) == 3) { restore_machine_regs(); - Yap_gcl(Yap_Error_Size, ap->ArityOfPE, ENV, CP); + Yap_gcl(LOCAL_Error_Size, ap->ArityOfPE, ENV, CP); save_machine_regs(); } else if (cb == 2) { restore_machine_regs(); - Yap_growheap(FALSE, Yap_Error_Size, NULL); + Yap_growheap(FALSE, LOCAL_Error_Size, NULL); save_machine_regs(); } else if (cb == 4) { restore_machine_regs(); - Yap_growtrail(Yap_Error_Size, FALSE); + Yap_growtrail(LOCAL_Error_Size, FALSE); save_machine_regs(); } - Yap_Error_Size = 0; - Yap_ErrorMessage = NULL; + LOCAL_Error_Size = 0; + LOCAL_ErrorMessage = NULL; if (cb) { /* cannot rely on the code */ if (ap->PredFlags & LogUpdatePredFlag) { @@ -6530,14 +6530,14 @@ Yap_RemoveClauseFromIndex(PredEntry *ap, yamop *beg) { return; } #ifdef DEBUG - if (Yap_Option['i' - 'a' + 1]) { + if (GLOBAL_Option['i' - 'a' + 1]) { Term tmod = ap->ModuleOfPred; if (!tmod) tmod = TermProlog; - Yap_DebugPutc(Yap_c_error_stream,'-'); - Yap_DebugPutc(Yap_c_error_stream,'\t'); + Yap_DebugPutc(LOCAL_c_error_stream,'-'); + Yap_DebugPutc(LOCAL_c_error_stream,'\t'); Yap_DebugPlWrite(tmod); - Yap_DebugPutc(Yap_c_error_stream,':'); + Yap_DebugPutc(LOCAL_c_error_stream,':'); if (ap->ModuleOfPred != IDB_MODULE) { if (ap->ArityOfPE == 0) { Atom At = (Atom)ap->FunctorOfPred; @@ -6546,7 +6546,7 @@ Yap_RemoveClauseFromIndex(PredEntry *ap, yamop *beg) { Functor f = ap->FunctorOfPred; Atom At = NameOfFunctor(f); Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(Yap_c_error_stream,'/'); + Yap_DebugPutc(LOCAL_c_error_stream,'/'); Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); } } else { @@ -6560,11 +6560,11 @@ Yap_RemoveClauseFromIndex(PredEntry *ap, yamop *beg) { Functor f = ap->FunctorOfPred; Atom At = NameOfFunctor(f); Yap_DebugPlWrite(MkAtomTerm(At)); - Yap_DebugPutc(Yap_c_error_stream,'/'); + Yap_DebugPutc(LOCAL_c_error_stream,'/'); Yap_DebugPlWrite(MkIntegerTerm(ArityOfFunctor(f))); } } - Yap_DebugPutc(Yap_c_error_stream,'\n'); + Yap_DebugPutc(LOCAL_c_error_stream,'\n'); } #endif stack = (path_stack_entry *)TR; @@ -6656,6 +6656,7 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y CACHE_REGS CELL *s_reg = NULL; Term t = TermNil; + int blob_term = FALSE; yamop *start_pc = ipc; choiceptr b0 = NULL; yamop **jlbl = NULL; @@ -6974,6 +6975,7 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y /* instructions type e */ case _switch_on_type: t = Deref(ARG1); + blob_term = FALSE; if (IsVarTerm(t)) { jlbl = &(ipc->u.llll.l4); ipc = ipc->u.llll.l4; @@ -6993,6 +6995,7 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y break; case _switch_list_nl: t = Deref(ARG1); + blob_term = FALSE; if (IsVarTerm(t)) { jlbl = &(ipc->u.ollll.l4); ipc = ipc->u.ollll.l4; @@ -7013,6 +7016,7 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y break; case _switch_on_arg_type: t = Deref(XREGS[arg_from_x(ipc->u.xllll.x)]); + blob_term = FALSE; if (IsVarTerm(t)) { jlbl = &(ipc->u.xllll.l4); ipc = ipc->u.xllll.l4; @@ -7032,6 +7036,7 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y break; case _switch_on_sub_arg_type: t = Deref(s_reg[ipc->u.sllll.s]); + blob_term = FALSE; if (IsVarTerm(t)) { jlbl = &(ipc->u.sllll.l4); ipc = ipc->u.sllll.l4; @@ -7051,6 +7056,7 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y break; case _if_not_then: t = Deref(ARG1); + blob_term = FALSE; if (IsVarTerm(t)) { jlbl = &(ipc->u.clll.l3); ipc = ipc->u.clll.l3; @@ -7086,14 +7092,17 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y break; case _index_dbref: t = AbsAppl(s_reg-1); + blob_term = FALSE; ipc = NEXTOP(ipc,e); break; case _index_blob: t = Yap_DoubleP_key(s_reg); + blob_term = TRUE; ipc = NEXTOP(ipc,e); break; case _index_long: t = Yap_IntP_key(s_reg); + blob_term = TRUE; ipc = NEXTOP(ipc,e); break; case _switch_on_cons: @@ -7114,8 +7123,13 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y break; case _expand_index: case _expand_clauses: - XREGS[ap->ArityOfPE+1] = (CELL)s_reg; - XREGS[ap->ArityOfPE+2] = (CELL)t; + if (blob_term) { /* protect garbage collector */ + XREGS[ap->ArityOfPE+1] = (CELL)&XREGS[ap->ArityOfPE+1]; + XREGS[ap->ArityOfPE+2] = TermNil; + } else { + XREGS[ap->ArityOfPE+1] = (CELL)s_reg; + XREGS[ap->ArityOfPE+2] = t; + } XREGS[ap->ArityOfPE+3] = Terms[0]; XREGS[ap->ArityOfPE+4] = Terms[1]; XREGS[ap->ArityOfPE+5] = Terms[2]; @@ -7126,8 +7140,11 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y } #endif ipc = ExpandIndex(ap, 5, cp_pc PASS_REGS); - s_reg = (CELL *)XREGS[ap->ArityOfPE+1]; - t = XREGS[ap->ArityOfPE+2]; + if (!blob_term) { /* protect garbage collector */ + s_reg = (CELL *)XREGS[ap->ArityOfPE+1]; + t = XREGS[ap->ArityOfPE+2]; + } + blob_term = FALSE; Terms[0] = XREGS[ap->ArityOfPE+3]; Terms[1] = XREGS[ap->ArityOfPE+4]; Terms[2] = XREGS[ap->ArityOfPE+5]; @@ -7151,15 +7168,22 @@ Yap_FollowIndexingCode(PredEntry *ap, yamop *ipc, Term Terms[3], yamop *ap_pc, y break; } case _index_pred: - XREGS[ap->ArityOfPE+1] = (CELL)s_reg; - XREGS[ap->ArityOfPE+2] = (CELL)t; + if (blob_term) { /* protect garbage collector */ + XREGS[ap->ArityOfPE+1] = (CELL)&XREGS[ap->ArityOfPE+1]; + XREGS[ap->ArityOfPE+2] = TermNil; + } else { + XREGS[ap->ArityOfPE+1] = (CELL)s_reg; + XREGS[ap->ArityOfPE+2] = t; + } XREGS[ap->ArityOfPE+3] = Terms[0]; XREGS[ap->ArityOfPE+4] = Terms[1]; XREGS[ap->ArityOfPE+5] = Terms[2]; Yap_IPred(ap, 5, cp_pc); start_pc = ipc = ap->cs.p_code.TrueCodeOfPred; - s_reg = (CELL *)XREGS[ap->ArityOfPE+1]; - t = XREGS[ap->ArityOfPE+2]; + if (!blob_term) { /* protect garbage collector */ + s_reg = (CELL *)XREGS[ap->ArityOfPE+1]; + t = XREGS[ap->ArityOfPE+2]; + } Terms[0] = XREGS[ap->ArityOfPE+3]; Terms[1] = XREGS[ap->ArityOfPE+4]; Terms[2] = XREGS[ap->ArityOfPE+5]; diff --git a/C/init.c b/C/init.c index bd11aaa7b..55a1b4a99 100755 --- a/C/init.c +++ b/C/init.c @@ -34,8 +34,11 @@ static char SccsId[] = "%W% %G%"; #include "tracer.h" #endif #ifdef YAPOR +#ifdef YAPOR_COW +#include +#endif /* YAPOR_COW */ #include "or.macros.h" -#endif /* YAPOR */ +#endif /* YAPOR */ #if defined(YAPOR) || defined(TABLING) #if HAVE_SYS_TYPES_H #include @@ -55,7 +58,6 @@ static char SccsId[] = "%W% %G%"; #define LOGFILE "logfile" -int Yap_output_msg = FALSE; #ifdef MACC STATIC_PROTO(void InTTYLine, (char *)); @@ -73,118 +75,15 @@ STATIC_PROTO(void InitStdPreds,(void)); STATIC_PROTO(void InitFlags, (void)); STATIC_PROTO(void InitCodes, (void)); STATIC_PROTO(void InitVersion, (void)); - +STD_PROTO(void exit, (int)); static void InitWorker(int wid); -STD_PROTO(void exit, (int)); - /************** YAP PROLOG GLOBAL VARIABLES *************************/ /************* variables related to memory allocation ***************/ - -#if defined(THREADS) - ADDR Yap_HeapBase; -struct restore_info rinfo[MAX_THREADS]; - -struct thread_globs Yap_thread_gl[MAX_THREADS]; - -pthread_t Yap_master_thread; - -#else - -struct restore_info rinfo; - -ADDR Yap_HeapBase, - Yap_LocalBase, - Yap_GlobalBase, - Yap_TrailBase, - Yap_TrailTop; - -/************ variables concerned with Error Handling *************/ -char *Yap_ErrorMessage; /* used to pass error messages */ -Term Yap_Error_Term; /* used to pass error terms */ -yap_error_number Yap_Error_TYPE; /* used to pass the error */ -UInt Yap_Error_Size; /* used to pass a size associated with an error */ - -/******************* storing error messages ****************************/ -char Yap_ErrorSay[MAX_ERROR_MSG_SIZE]; - -/* if we botched in a LongIO operation */ -jmp_buf Yap_IOBotch; - -/* if we botched in the compiler */ -jmp_buf Yap_CompilerBotch; - -/************ variables concerned with Error Handling *************/ -sigjmp_buf Yap_RestartEnv; /* used to restart after an abort execution */ - -/********* IO support *****/ - -/********* parsing ********************************************/ - -TokEntry *Yap_tokptr, *Yap_toktide; -VarEntry *Yap_VarTable, *Yap_AnonVarTable; -int Yap_eot_before_eof = FALSE; - -/******************* intermediate buffers **********************/ - -char Yap_FileNameBuf[YAP_FILENAME_MAX], - Yap_FileNameBuf2[YAP_FILENAME_MAX]; - -#endif /* THREADS */ - -/******** whether Yap is responsible for signal handling******************/ -int Yap_PrologShouldHandleInterrupts; - -/********* readline support *****/ -#if HAVE_LIBREADLINE - -char *_line = (char *) NULL; - -#endif - -#ifdef MPWSHELL -/********** informing if we are in the MPW shell ********************/ - -int mpwshell = FALSE; - -#endif - -#ifdef EMACS - -int emacs_mode = FALSE; -char emacs_tmp[256], emacs_tmp2[256]; - -#endif - -/********* Prolog State ********************************************/ - -Int Yap_PrologMode = BootMode; - -int Yap_CritLocks = 0; - -/********* streams ********************************************/ - -YP_FILE *Yap_stdin; -YP_FILE *Yap_stdout; -YP_FILE *Yap_stderr; - - -/************** Access to yap initial arguments ***************************/ - -char **Yap_argv; -int Yap_argc; - -/************** Extensions to Terms ***************************************/ - -#ifdef COROUTINING -/* array with the ops for your favourite extensions */ -ext_op attas[attvars_ext+1]; -#endif - /************** declarations local to init.c ************************/ static char *optypes[] = {"", "xfx", "xfy", "yfx", "xf", "yf", "fx", "fy"}; @@ -197,10 +96,6 @@ int Yap_page_size; void **Yap_ABSMI_OPCODES; #endif -#if USE_SOCKET -int Yap_sockets_io=0; -#endif - #if DEBUG #if COROUTINING int Yap_Portray_delays = FALSE; @@ -306,7 +201,7 @@ static void SetOp(int p, int type, char *at, Term m) { #ifdef DEBUG - if (Yap_Option[5]) + if (GLOBAL_Option[5]) fprintf(stderr,"[setop %d %s %s]\n", p, optypes[type], at); #endif OpDec(p, optypes[type], Yap_LookupAtom(at), m); @@ -448,8 +343,8 @@ InitDebug(void) int i; for (i = 1; i < 20; ++i) - Yap_Option[i] = 0; - if (Yap_output_msg) { + GLOBAL_Option[i] = 0; + if (GLOBAL_output_msg) { char ch; #if HAVE_ISATTY @@ -464,10 +359,10 @@ InitDebug(void) fprintf(stderr,"m Machine\t p parser\n"); while ((ch = YP_putchar(YP_getchar())) != '\n') if (ch >= 'a' && ch <= 'z') - Yap_Option[ch - 'a' + 1] = 1; - if (Yap_Option['l' - 96]) { - Yap_logfile = fopen(LOGFILE, "w"); - if (Yap_logfile == NULL) { + GLOBAL_Option[ch - 'a' + 1] = 1; + if (GLOBAL_Option['l' - 96]) { + GLOBAL_logfile = fopen(LOGFILE, "w"); + if (GLOBAL_logfile == NULL) { fprintf(stderr,"can not open %s\n", LOGFILE); getchar(); exit(0); @@ -1166,20 +1061,68 @@ InitInvisibleAtoms(void) INIT_RWLOCK(Yap_heap_regs->invisiblechain.AERWLock); } + +#ifdef YAPOR +void Yap_init_yapor_workers(void) { + CACHE_REGS + int proc; +#ifdef YAPOR_THREADS + return; +#endif /* YAPOR_THREADS */ +#ifdef YAPOR_COW + GLOBAL_master_worker = getpid(); + if (GLOBAL_number_workers > 1) { + int son; + son = fork(); + if (son == -1) + Yap_Error(FATAL_ERROR, TermNil, "fork error (Yap_init_yapor_workers)"); + if (son > 0) { + /* I am the father, I must stay here and wait for my children to all die */ + struct sigaction sigact; + sigact.sa_handler = SIG_DFL; + sigemptyset(&sigact.sa_mask); + sigact.sa_flags = SA_RESTART; + sigaction(SIGINT, &sigact, NULL); + pause(); + exit(0); + } else + GLOBAL_worker_pid(0) = getpid(); + } +#endif /* YAPOR_COW */ + for (proc = 1; proc < GLOBAL_number_workers; proc++) { + int son; + son = fork(); + if (son == -1) + Yap_Error(FATAL_ERROR, TermNil, "fork error (Yap_init_yapor_workers)"); + if (son == 0) { + /* new worker */ + worker_id = proc; + Yap_remap_yapor_memory(); + LOCAL = REMOTE(worker_id); + memcpy(REMOTE(worker_id), REMOTE(0), sizeof(struct worker_local)); + InitWorker(worker_id); + break; + } else + GLOBAL_worker_pid(proc) = son; + } +} +#endif /* YAPOR */ + + #ifdef THREADS static void InitThreadHandle(int wid) { - FOREIGN_ThreadHandle(wid).in_use = FALSE; - FOREIGN_ThreadHandle(wid).zombie = FALSE; - FOREIGN_ThreadHandle(wid).local_preds = NULL; + REMOTE_ThreadHandle(wid).in_use = FALSE; + REMOTE_ThreadHandle(wid).zombie = FALSE; + REMOTE_ThreadHandle(wid).local_preds = NULL; #ifdef LOW_LEVEL_TRACER - FOREIGN_ThreadHandle(wid).thread_inst_count = 0LL; + REMOTE_ThreadHandle(wid).thread_inst_count = 0LL; #endif - pthread_mutex_init(&(FOREIGN_ThreadHandle(wid).tlock), NULL); - pthread_mutex_init(&(FOREIGN_ThreadHandle(wid).tlock_status), NULL); - FOREIGN_ThreadHandle(wid).tdetach = (CELL)0; - FOREIGN_ThreadHandle(wid).cmod = (CELL)0; + pthread_mutex_init(&(REMOTE_ThreadHandle(wid).tlock), NULL); + pthread_mutex_init(&(REMOTE_ThreadHandle(wid).tlock_status), NULL); + REMOTE_ThreadHandle(wid).tdetach = (CELL)0; + REMOTE_ThreadHandle(wid).cmod = (CELL)0; } int @@ -1189,7 +1132,7 @@ Yap_InitThread(int new_id) if (new_id) { if (!(new_s = (struct worker_local *)calloc(sizeof(struct worker_local), 1))) return FALSE; - Yap_WLocal[new_id] = new_s; + Yap_local[new_id] = new_s; } InitWorker(new_id); return TRUE; @@ -1201,32 +1144,32 @@ InitFirstWorkerThreadHandle(void) { #ifdef THREADS CACHE_REGS - ThreadHandle.id = 0; - ThreadHandle.in_use = TRUE; - ThreadHandle.default_yaam_regs = + LOCAL_ThreadHandle.id = 0; + LOCAL_ThreadHandle.in_use = TRUE; + LOCAL_ThreadHandle.default_yaam_regs = &Yap_standard_regs; - ThreadHandle.pthread_handle = pthread_self(); - pthread_mutex_init(&FOREIGN_ThreadHandle(0).tlock, NULL); - pthread_mutex_init(&FOREIGN_ThreadHandle(0).tlock_status, NULL); - ThreadHandle.tdetach = MkAtomTerm(AtomFalse); + LOCAL_ThreadHandle.pthread_handle = pthread_self(); + pthread_mutex_init(&REMOTE_ThreadHandle(0).tlock, NULL); + pthread_mutex_init(&REMOTE_ThreadHandle(0).tlock_status, NULL); + LOCAL_ThreadHandle.tdetach = MkAtomTerm(AtomFalse); #endif } static void InitScratchPad(int wid) { - FOREIGN(wid)->scratchpad.ptr = NULL; - FOREIGN(wid)->scratchpad.sz = SCRATCH_START_SIZE; - FOREIGN(wid)->scratchpad.msz = SCRATCH_START_SIZE; + REMOTE_ScratchPad(wid).ptr = NULL; + REMOTE_ScratchPad(wid).sz = SCRATCH_START_SIZE; + REMOTE_ScratchPad(wid).msz = SCRATCH_START_SIZE; } void Yap_CloseScratchPad(void) { CACHE_REGS - Yap_FreeCodeSpace(ScratchPad.ptr); - ScratchPad.sz = SCRATCH_START_SIZE; - ScratchPad.msz = SCRATCH_START_SIZE; + Yap_FreeCodeSpace(LOCAL_ScratchPad.ptr); + LOCAL_ScratchPad.sz = SCRATCH_START_SIZE; + LOCAL_ScratchPad.msz = SCRATCH_START_SIZE; } #include "iglobals.h" @@ -1241,11 +1184,11 @@ struct global_data Yap_Global; #endif #if defined(THREADS) -struct worker_local *Yap_WLocal[MAX_THREADS]; +struct worker_local *Yap_local[MAX_THREADS]; #elif defined(YAPOR) -struct worker_local *Yap_WLocal; +struct worker_local *Yap_local; #else /* !THREADS && !YAPOR */ -struct worker_local Yap_WLocal; +struct worker_local Yap_local; #endif static void @@ -1255,7 +1198,7 @@ InitCodes(void) #if THREADS int wid; for (wid = 1; wid < MAX_THREADS; wid++) { - Yap_WLocal[wid] = NULL; + Yap_local[wid] = NULL; } #endif #include "ihstruct.h" @@ -1304,11 +1247,11 @@ Yap_InitWorkspace(UInt Heap, UInt Stack, UInt Trail, UInt Atts, UInt max_table_s /* initialise system stuff */ #if PUSH_REGS #ifdef THREADS - if (!(Yap_WLocal[0] = (struct worker_local *)calloc(sizeof(struct worker_local), 1))) + if (!(Yap_local[0] = (struct worker_local *)calloc(sizeof(struct worker_local), 1))) return; pthread_key_create(&Yap_yaamregs_key, NULL); pthread_setspecific(Yap_yaamregs_key, (const void *)&Yap_standard_regs); - Yap_master_thread = pthread_self(); + GLOBAL_master_thread = pthread_self(); #else /* In this case we need to initialise the abstract registers */ Yap_regp = &Yap_standard_regs; @@ -1319,11 +1262,8 @@ Yap_InitWorkspace(UInt Heap, UInt Stack, UInt Trail, UInt Atts, UInt max_table_s #ifdef THREADS Yap_regp = ((REGSTORE *)pthread_getspecific(Yap_yaamregs_key)); - Yap_regp->worker_id_ = 0; -#endif - /* Init signal handling and time */ - /* also init memory page size, required by later functions */ - Yap_InitSysbits (); + LOCAL = REMOTE(0); +#endif /* THREADS */ if (Heap < MinHeapSpace) Heap = MinHeapSpace; Heap = AdjustPageSize(Heap * K); @@ -1338,8 +1278,10 @@ Yap_InitWorkspace(UInt Heap, UInt Stack, UInt Trail, UInt Atts, UInt max_table_s Atts = 2048*sizeof(CELL); else Atts = AdjustPageSize(Atts * K); -#ifdef YAPOR +#if defined(YAPOR) || defined(THREADS) worker_id = 0; +#endif /* YAPOR || THREADS */ +#ifdef YAPOR if (n_workers > MAX_WORKERS) Yap_Error(INTERNAL_ERROR, TermNil, "excessive number of workers"); #ifdef YAPOR_COPY @@ -1353,16 +1295,16 @@ Yap_InitWorkspace(UInt Heap, UInt Stack, UInt Trail, UInt Atts, UInt max_table_s #endif /* YAPOR_COPY - YAPOR_COW - YAPOR_SBA - YAPOR_THREADS */ #endif /* YAPOR */ #if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA) - Yap_init_optyap_memory(Trail, Heap, Stack+Atts, n_workers); + Yap_init_yapor_stacks_memory(Trail, Heap, Stack+Atts, n_workers); #else - Yap_InitMemory (Trail, Heap, Stack+Atts); + Yap_InitMemory(Trail, Heap, Stack+Atts); #endif #if defined(YAPOR) || defined(TABLING) - Yap_init_optyap_data(max_table_size, n_workers, sch_loop, delay_load); + Yap_init_global_optyap_data(max_table_size, n_workers, sch_loop, delay_load); #endif /* YAPOR || TABLING */ - Yap_AttsSize = Atts; - Yap_InitTime (); + Yap_AttsSize = Atts; + Yap_InitTime(); /* InitAbsmi must be done before InitCodes */ /* This must be done before initialising predicates */ for (i = 0; i <= LAST_FLAG; i++) { @@ -1394,17 +1336,17 @@ Yap_HaltRegisterHook (HaltHookFunc f, void * env) return FALSE; h->environment = env; h->hook = f; - LOCK(Yap_BGL); - h->next = Yap_HaltHooks; - Yap_HaltHooks = h; - UNLOCK(Yap_BGL); + LOCK(GLOBAL_BGL); + h->next = GLOBAL_HaltHooks; + GLOBAL_HaltHooks = h; + UNLOCK(GLOBAL_BGL); return TRUE; } static void run_halt_hooks(int code) { - struct halt_hook *hooke = Yap_HaltHooks; + struct halt_hook *hooke = GLOBAL_HaltHooks; while (hooke) { hooke->hook(code, hooke->environment); @@ -1415,11 +1357,12 @@ run_halt_hooks(int code) void Yap_exit (int value) { + CACHE_REGS #if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA) - Yap_unmap_optyap_memory(); -#endif + Yap_unmap_yapor_memory(); +#endif /* YAPOR_COPY || YAPOR_COW || YAPOR_SBA */ - if (! (Yap_PrologMode & BootMode) ) { + if (! (LOCAL_PrologMode & BootMode) ) { #ifdef LOW_PROF remove("PROFPREDS"); remove("PROFILING"); diff --git a/C/inlines.c b/C/inlines.c index 9c0d62274..218123292 100755 --- a/C/inlines.c +++ b/C/inlines.c @@ -405,9 +405,9 @@ p_dif( USES_REGS1 ) * We may wake up goals during our attempt to unify the * two terms. If we are adding to the tail of a list of * woken goals that should be ok, but otherwise we need - * to restore WokenGoals to its previous value. + * to restore LOCAL_WokenGoals to its previous value. */ - CELL OldWokenGoals = Yap_ReadTimedVar(WokenGoals); + CELL OldWokenGoals = Yap_ReadTimedVar(LOCAL_WokenGoals); #endif register tr_fr_ptr pt0; /* store the old value of TR for clearing bindings */ @@ -425,7 +425,7 @@ p_dif( USES_REGS1 ) d0 = Yap_IUnify(d0, d1); #ifdef COROUTINING /* now restore Woken Goals to its old value */ - Yap_UpdateTimedVar(WokenGoals, OldWokenGoals); + Yap_UpdateTimedVar(LOCAL_WokenGoals, OldWokenGoals); if (OldWokenGoals == TermNil) { Yap_undo_signal(YAP_WAKEUP_SIGNAL); } @@ -719,7 +719,7 @@ p_functor( USES_REGS1 ) /* functor(?,?,?) */ d0 = AbsAppl(H); if (pt1+d1 > ENV - CreepFlag) { if (!Yap_gcl((1+d1)*sizeof(CELL), 3, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } goto restart; diff --git a/C/iopreds.c b/C/iopreds.c index 8baceb7e4..b2784ce1c 100644 --- a/C/iopreds.c +++ b/C/iopreds.c @@ -183,17 +183,17 @@ Yap_DebugGetc() } if ((ch = *lp++) == 0) ch = '\n', eolflg = 1; - if (Yap_Option['l' - 96]) - putc(ch, Yap_logfile); + if (GLOBAL_Option['l' - 96]) + putc(ch, GLOBAL_logfile); return (ch); } int Yap_DebugPutc(int sno, wchar_t ch) { - if (Yap_Option['l' - 96]) - (void) putc(ch, Yap_logfile); - return (putc(ch, Yap_stderr)); + if (GLOBAL_Option['l' - 96]) + (void) putc(ch, GLOBAL_logfile); + return (putc(ch, GLOBAL_stderr)); } void @@ -206,7 +206,7 @@ void Yap_DebugErrorPutc(int c) { CACHE_REGS - Yap_DebugPutc (Yap_c_error_stream, c); + Yap_DebugPutc (LOCAL_c_error_stream, c); } #endif @@ -238,7 +238,7 @@ typedef struct stream_ref int beam_write (void) { Yap_StartSlots(); - Yap_plwrite (ARG1, Stream[Yap_c_output_stream].stream_wputc, 0, 1200); + Yap_plwrite (ARG1, Stream[LOCAL_c_output_stream].stream_wputc, 0, 1200); Yap_CloseSlots(); if (EX != 0L) { Term ball = Yap_PopTermFromDB(EX); @@ -273,8 +273,8 @@ syntax_error (TokEntry * tokptr, IOSTREAM *st, Term *outp) /* make sure to globalise variable */ Yap_unify(*outp, MkVarTerm()); start = tokptr->TokPos; - clean_vars(Yap_VarTable); - clean_vars(Yap_AnonVarTable); + clean_vars(LOCAL_VarTable); + clean_vars(LOCAL_AnonVarTable); while (1) { Term ts[2]; @@ -286,7 +286,7 @@ syntax_error (TokEntry * tokptr, IOSTREAM *st, Term *outp) H = Hi; break; } - if (tokptr == Yap_toktide) { + if (tokptr == LOCAL_toktide) { err = tokptr->TokPos; out = count; } @@ -402,31 +402,31 @@ Yap_StringToTerm(char *s,Term *tp) if (sno == NULL) return FALSE; TR_before_parse = TR; - tokstart = Yap_tokptr = Yap_toktide = Yap_tokenizer(sno, &tpos); + tokstart = LOCAL_tokptr = LOCAL_toktide = Yap_tokenizer(sno, &tpos); if (tokstart == NIL || tokstart->Tok == Ord (eot_tok)) { if (tp) { *tp = MkAtomTerm(AtomEOFBeforeEOT); } - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); Sclose(sno); return FALSE; - } else if (Yap_ErrorMessage) { + } else if (LOCAL_ErrorMessage) { if (tp) { - *tp = MkAtomTerm(Yap_LookupAtom(Yap_ErrorMessage)); + *tp = MkAtomTerm(Yap_LookupAtom(LOCAL_ErrorMessage)); } - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); Sclose(sno); return FALSE; } t = Yap_Parse(); TR = TR_before_parse; - if (!t || Yap_ErrorMessage) { + if (!t || LOCAL_ErrorMessage) { GenerateSyntaxError(tp, tokstart, sno PASS_REGS); - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); Sclose(sno); return FALSE; } - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); Sclose(sno); return t; } @@ -436,13 +436,13 @@ Int Yap_FirstLineInParse (void) { CACHE_REGS - return StartLine; + return LOCAL_StartLine; } static Int p_startline ( USES_REGS1 ) { - return (Yap_unify_constant (ARG1, MkIntegerTerm (StartLine))); + return (Yap_unify_constant (ARG1, MkIntegerTerm (LOCAL_StartLine))); } /* control the parser error handler */ @@ -512,25 +512,25 @@ Yap_readTerm(void *st0, Term *tp, Term *varnames, Term *terror, Term *tpos) if (st == NULL) { return FALSE; } - tokstart = Yap_tokptr = Yap_toktide = Yap_tokenizer(st, tpos); - if (Yap_ErrorMessage) + tokstart = LOCAL_tokptr = LOCAL_toktide = Yap_tokenizer(st, tpos); + if (LOCAL_ErrorMessage) { - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); if (terror) - *terror = MkAtomTerm(Yap_LookupAtom(Yap_ErrorMessage)); - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + *terror = MkAtomTerm(Yap_LookupAtom(LOCAL_ErrorMessage)); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); return FALSE; } pt = Yap_Parse(); - if (Yap_ErrorMessage || pt == (CELL)0) { + if (LOCAL_ErrorMessage || pt == (CELL)0) { GenerateSyntaxError(terror, tokstart, st PASS_REGS); - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); return FALSE; } if (varnames) { - *varnames = Yap_VarNames(Yap_VarTable, TermNil); + *varnames = Yap_VarNames(LOCAL_VarTable, TermNil); if (!*varnames) { - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); return FALSE; } } @@ -554,9 +554,6 @@ static Int { Term t, v; TokEntry *tokstart; -#if EMACS - int emacs_cares = FALSE; -#endif Term tmod = Deref(ARG3), OCurrentModule = CurrentModule, tpos; extern void Yap_setCurrentSourceLocation(IOSTREAM **s); @@ -567,7 +564,7 @@ static Int Yap_Error(TYPE_ERROR_ATOM, tmod, "read_term/2"); return FALSE; } - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; tpos = Yap_StreamPosition(inp_stream); if (!Yap_unify(tpos,ARG5)) { /* do this early so that we do not have to protect it in case of stack expansion */ @@ -585,33 +582,32 @@ static Int /* Scans the term using stack space */ while (TRUE) { old_H = H; - Yap_eot_before_eof = FALSE; tpos = Yap_StreamPosition(inp_stream); - tokstart = Yap_tokptr = Yap_toktide = Yap_tokenizer(inp_stream, &tpos); - if (Yap_Error_TYPE != YAP_NO_ERROR && seekable) { + tokstart = LOCAL_tokptr = LOCAL_toktide = Yap_tokenizer(inp_stream, &tpos); + if (LOCAL_Error_TYPE != YAP_NO_ERROR && seekable) { H = old_H; - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); if (seekable) { Sseek64(inp_stream, cpos, SIO_SEEK_SET); } - if (Yap_Error_TYPE == OUT_OF_TRAIL_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_TRAIL_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growtrail (sizeof(CELL) * K16, FALSE)) { return FALSE; } - } else if (Yap_Error_TYPE == OUT_OF_AUXSPACE_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + } else if (LOCAL_Error_TYPE == OUT_OF_AUXSPACE_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_ExpandPreAllocCodeSpace(0, NULL, TRUE)) { return FALSE; } - } else if (Yap_Error_TYPE == OUT_OF_HEAP_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + } else if (LOCAL_Error_TYPE == OUT_OF_HEAP_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growheap(FALSE, 0, NULL)) { return FALSE; } - } else if (Yap_Error_TYPE == OUT_OF_STACK_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_gcl(Yap_Error_Size, nargs, ENV, CP)) { + } else if (LOCAL_Error_TYPE == OUT_OF_STACK_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_gcl(LOCAL_Error_Size, nargs, ENV, CP)) { return FALSE; } } @@ -620,18 +616,18 @@ static Int break; } } - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_TYPE = YAP_NO_ERROR; /* preserve value of H after scanning: otherwise we may lose strings and floats */ old_H = H; if (tokstart != NULL && tokstart->Tok == Ord (eot_tok)) { /* did we get the end of file from an abort? */ - if (Yap_ErrorMessage && - !strcmp(Yap_ErrorMessage,"Abort")) { - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + if (LOCAL_ErrorMessage && + !strcmp(LOCAL_ErrorMessage,"Abort")) { + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); return FALSE; } else { - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); return Yap_unify_constant(ARG2, MkAtomTerm (AtomEof)) && Yap_unify_constant(ARG4, TermNil); @@ -639,61 +635,61 @@ static Int } repeat_cycle: CurrentModule = tmod; - if (Yap_ErrorMessage || (t = Yap_Parse()) == 0) { + if (LOCAL_ErrorMessage || (t = Yap_Parse()) == 0) { CurrentModule = OCurrentModule; - if (Yap_ErrorMessage) { + if (LOCAL_ErrorMessage) { int res; - if (!strcmp(Yap_ErrorMessage,"Stack Overflow") || - !strcmp(Yap_ErrorMessage,"Trail Overflow") || - !strcmp(Yap_ErrorMessage,"Heap Overflow")) { + if (!strcmp(LOCAL_ErrorMessage,"Stack Overflow") || + !strcmp(LOCAL_ErrorMessage,"Trail Overflow") || + !strcmp(LOCAL_ErrorMessage,"Heap Overflow")) { /* ignore term we just built */ tr_fr_ptr old_TR = TR; H = old_H; - TR = (tr_fr_ptr)ScannerStack; + TR = (tr_fr_ptr)LOCAL_ScannerStack; - if (!strcmp(Yap_ErrorMessage,"Stack Overflow")) - res = Yap_growstack_in_parser(&old_TR, &tokstart, &Yap_VarTable); - else if (!strcmp(Yap_ErrorMessage,"Heap Overflow")) - res = Yap_growheap_in_parser(&old_TR, &tokstart, &Yap_VarTable); + if (!strcmp(LOCAL_ErrorMessage,"Stack Overflow")) + res = Yap_growstack_in_parser(&old_TR, &tokstart, &LOCAL_VarTable); + else if (!strcmp(LOCAL_ErrorMessage,"Heap Overflow")) + res = Yap_growheap_in_parser(&old_TR, &tokstart, &LOCAL_VarTable); else - res = Yap_growtrail_in_parser(&old_TR, &tokstart, &Yap_VarTable); + res = Yap_growtrail_in_parser(&old_TR, &tokstart, &LOCAL_VarTable); if (res) { - ScannerStack = (char *)TR; + LOCAL_ScannerStack = (char *)TR; TR = old_TR; old_H = H; - Yap_tokptr = Yap_toktide = tokstart; - Yap_ErrorMessage = NULL; + LOCAL_tokptr = LOCAL_toktide = tokstart; + LOCAL_ErrorMessage = NULL; goto repeat_cycle; } - ScannerStack = (char *)TR; + LOCAL_ScannerStack = (char *)TR; TR = old_TR; } } if (ParserErrorStyle == QUIET_ON_PARSER_ERROR) { /* just fail */ - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); return FALSE; } else if (ParserErrorStyle == CONTINUE_ON_PARSER_ERROR) { - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; /* try again */ goto repeat_cycle; } else { Term terr = syntax_error(tokstart, inp_stream, &ARG2); - if (Yap_ErrorMessage == NULL) - Yap_ErrorMessage = "SYNTAX ERROR"; + if (LOCAL_ErrorMessage == NULL) + LOCAL_ErrorMessage = "SYNTAX ERROR"; if (ParserErrorStyle == EXCEPTION_ON_PARSER_ERROR) { - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); - Yap_Error(SYNTAX_ERROR,terr,Yap_ErrorMessage); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); + Yap_Error(SYNTAX_ERROR,terr,LOCAL_ErrorMessage); return FALSE; } else /* FAIL ON PARSER ERROR */ { Term t[2]; t[0] = terr; - t[1] = MkAtomTerm(Yap_LookupAtom(Yap_ErrorMessage)); - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + t[1] = MkAtomTerm(Yap_LookupAtom(LOCAL_ErrorMessage)); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); return Yap_unify(ARG6,Yap_MkApplTerm(Yap_MkFunctor(AtomError,2),2,t)); } } @@ -703,17 +699,14 @@ static Int break; } } -#if EMACS - first_char = tokstart->TokPos; -#endif /* EMACS */ if (!Yap_unify(t, ARG2)) return FALSE; if (AtomOfTerm (Deref (ARG1)) == AtomTrue) { while (TRUE) { CELL *old_H = H; - if (setjmp(Yap_IOBotch) == 0) { - v = Yap_VarNames(Yap_VarTable, TermNil); + if (setjmp(LOCAL_IOBotch) == 0) { + v = Yap_VarNames(LOCAL_VarTable, TermNil); break; } else { tr_fr_ptr old_TR; @@ -722,16 +715,16 @@ static Int old_TR = TR; /* restart global */ H = old_H; - TR = (tr_fr_ptr)ScannerStack; - Yap_growstack_in_parser(&old_TR, &tokstart, &Yap_VarTable); - ScannerStack = (char *)TR; + TR = (tr_fr_ptr)LOCAL_ScannerStack; + Yap_growstack_in_parser(&old_TR, &tokstart, &LOCAL_VarTable); + LOCAL_ScannerStack = (char *)TR; TR = old_TR; } } - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); return Yap_unify (v, ARG4); } else { - Yap_clean_tokenizer(tokstart, Yap_VarTable, Yap_AnonVarTable); + Yap_clean_tokenizer(tokstart, LOCAL_VarTable, LOCAL_AnonVarTable); return TRUE; } } @@ -976,7 +969,7 @@ p_char_conversion( USES_REGS1 ) CharConversionTable2 = Yap_AllocCodeSpace(NUMBER_OF_CHARS*sizeof(char)); while (CharConversionTable2 == NULL) { if (!Yap_growheap(FALSE, NUMBER_OF_CHARS*sizeof(char), NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return(FALSE); } } @@ -1110,9 +1103,6 @@ Yap_InitBackIO (void) void Yap_InitIOPreds(void) { - Yap_stdin = stdin; - Yap_stdout = stdout; - Yap_stderr = stderr; if (!Stream) Stream = (StreamDesc *)Yap_AllocCodeSpace(sizeof(StreamDesc)*MaxStreams); /* here the Input/Output predicates */ diff --git a/C/load_aix.c b/C/load_aix.c index 654d30b90..7e9bf1c51 100644 --- a/C/load_aix.c +++ b/C/load_aix.c @@ -65,16 +65,16 @@ LoadForeign(StringList ofiles, StringList libs, /* load wants to follow the LIBRARY_PATH */ if (ofiles->next != NULL || libs != NULL) { - strcpy(Yap_ErrorSay," Load Failed: in AIX you must load a single object file"); + strcpy(LOCAL_ErrorSay," Load Failed: in AIX you must load a single object file"); return LOAD_FAILLED; } - if (!Yap_TrueFileName(AtomName(ofiles->name), Yap_FileNameBuf, TRUE)) { - strcpy(Yap_ErrorSay, " Trying to open unexisting file in LoadForeign "); + if (!Yap_TrueFileName(AtomName(ofiles->name), LOCAL_FileNameBuf, TRUE)) { + strcpy(LOCAL_ErrorSay, " Trying to open unexisting file in LoadForeign "); return LOAD_FAILLED; } /* In AIX, just call load and everything will go in */ - if ((*init_proc=((YapInitProc *)load(Yap_FileNameBuf,0,NULL))) == NULL) { - strcpy(Yap_ErrorSay,sys_errlist[errno]); + if ((*init_proc=((YapInitProc *)load(LOCAL_FileNameBuf,0,NULL))) == NULL) { + strcpy(LOCAL_ErrorSay,sys_errlist[errno]); return LOAD_FAILLED; } return LOAD_SUCCEEDED; diff --git a/C/load_aout.c b/C/load_aout.c index 0c2e2c1b6..bc96d8b8b 100644 --- a/C/load_aout.c +++ b/C/load_aout.c @@ -18,7 +18,7 @@ #include "Foreign.h" #ifdef A_OUT - +this code is no being maintained anymore #include #if STDC_HEADERS #include @@ -43,7 +43,7 @@ #endif #include -static char YapExecutable[YAP_FILE_MAX]; + #define oktox(n) \ (0==stat(n,&stbuf)&&(stbuf.st_mode&S_IFMT)==S_IFREG&&0==access(n,X_OK)) @@ -64,10 +64,10 @@ Yap_FindExecutable(char *name) cp = (char *)getenv("PATH"); if (cp == NULL) cp = ".:/usr/ucb:/bin:/usr/bin:/usr/local/bin"; - if (*Yap_argv[0] == '/') { - if (oktox(Yap_argv[0])) { - strcpy(Yap_FileNameBuf, Yap_argv[0]); - Yap_TrueFileName(Yap_FileNameBuf, YapExecutable, TRUE); + if (*GLOBAL_argv[0] == '/') { + if (oktox(GLOBAL_argv[0])) { + strcpy(LOCAL_FileNameBuf, GLOBAL_argv[0]); + Yap_TrueFileName(LOCAL_FileNameBuf, GLOBAL_Executable, TRUE); return; } } @@ -79,24 +79,24 @@ Yap_FindExecutable(char *name) * argv[0] */ - for (cp2 = Yap_FileNameBuf; (*cp) != 0 && (*cp) != ':';) + for (cp2 = LOCAL_FileNameBuf; (*cp) != 0 && (*cp) != ':';) *cp2++ = *cp++; *cp2++ = '/'; - strcpy(cp2, Yap_argv[0]); + strcpy(cp2, GLOBAL_argv[0]); if (*cp) cp++; - if (!oktox(Yap_FileNameBuf)) + if (!oktox(LOCAL_FileNameBuf)) continue; - Yap_TrueFileName(Yap_FileNameBuf, YapExecutable, TRUE); + Yap_TrueFileName(LOCAL_FileNameBuf, GLOBAL_Executable, TRUE); return; } /* one last try for dual systems */ - strcpy(Yap_FileNameBuf, Yap_argv[0]); - Yap_TrueFileName(Yap_FileNameBuf, YapExecutable, TRUE); - if (oktox(YapExecutable)) + strcpy(LOCAL_FileNameBuf, GLOBAL_argv[0]); + Yap_TrueFileName(LOCAL_FileNameBuf, GLOBAL_Executable, TRUE); + if (oktox(GLOBAL_Executable)) return; else - Yap_Error(SYSTEM_ERROR,MkAtomTerm(Yap_LookupAtom(YapExecutable)), + Yap_Error(SYSTEM_ERROR,MkAtomTerm(Yap_LookupAtom(GLOBAL_Executable)), "cannot find file being executed"); } @@ -174,22 +174,22 @@ LoadForeign(StringList ofiles, /* prepare the magic */ if (strlen(o_files) + strlen(l_files) + strlen(proc_name) + - strlen(YapExecutable) > 2*MAXPATHLEN) { - strcpy(Yap_ErrorSay, " too many parameters in load_foreign/3 "); + strlen(GLOBAL_Executable) > 2*MAXPATHLEN) { + strcpy(LOCAL_ErrorSay, " too many parameters in load_foreign/3 "); return LOAD_FAILLED; } sprintf(command, "/usr/bin/ld -N -A %s -o %s -u _%s %s %s -lc", - YapExecutable, + GLOBAL_Executable, tfile, proc_name, o_files, l_files); /* now, do the magic */ if (system(command) != 0) { unlink(tfile); - strcpy(Yap_ErrorSay," ld returned error status in load_foreign_files "); + strcpy(LOCAL_ErrorSay," ld returned error status in load_foreign_files "); return LOAD_FAILLED; } /* now check the music has played */ if ((fildes = open(tfile, O_RDONLY)) < 0) { - strcpy(Yap_ErrorSay," unable to open temp file in load_foreign_files "); + strcpy(LOCAL_ErrorSay," unable to open temp file in load_foreign_files "); return LOAD_FAILLED; } /* it did, get the mice */ @@ -204,28 +204,28 @@ LoadForeign(StringList ofiles, firstloadImSz = loadImageSize; /* now fetch the space we need */ if (!(FCodeBase = Yap_AllocCodeSpace((int) loadImageSize))) { - strcpy(Yap_ErrorSay," unable to allocate space for external code "); + strcpy(LOCAL_ErrorSay," unable to allocate space for external code "); return LOAD_FAILLED; } /* now, a new incantation to load the new foreign code */ sprintf(command, "/usr/bin/ld -N -A %s -T %lx -o %s -u _%s %s %s -lc", - YapExecutable, + GLOBAL_Executable, (unsigned long) FCodeBase, tfile, proc_name, o_files, l_files); /* and do it */ if (system(command) != 0) { unlink(tfile); - strcpy(Yap_ErrorSay," ld returned error status in load_foreign_files "); + strcpy(LOCAL_ErrorSay," ld returned error status in load_foreign_files "); return LOAD_FAILLED; } if ((fildes = open(tfile, O_RDONLY)) < 0) { - strcpy(Yap_ErrorSay," unable to open temp file in load_foreign_files "); + strcpy(LOCAL_ErrorSay," unable to open temp file in load_foreign_files "); return LOAD_FAILLED; } read(fildes, (char *) &header, sizeof(header)); loadImageSize = header.a_text + header.a_data + header.a_bss; if (firstloadImSz < loadImageSize) { - strcpy(Yap_ErrorSay," miscalculation in load_foreign/3 "); + strcpy(LOCAL_ErrorSay," miscalculation in load_foreign/3 "); return LOAD_FAILLED; } /* now search for our init function */ @@ -236,11 +236,11 @@ LoadForeign(StringList ofiles, func_info[0].n_un.n_name = entry_fun; func_info[1].n_un.n_name = NULL; if (nlist(tfile, func_info) == -1) { - strcpy(Yap_ErrorSay," in nlist(3) "); + strcpy(LOCAL_ErrorSay," in nlist(3) "); return LOAD_FAILLED; } if (func_info[0].n_type == 0) { - strcpy(Yap_ErrorSay," in nlist(3) "); + strcpy(LOCAL_ErrorSay," in nlist(3) "); return LOAD_FAILLED; } *init_proc = (YapInitProc)(func_info[0].n_value); diff --git a/C/load_coff.c b/C/load_coff.c index bb090f131..89fb345dc 100644 --- a/C/load_coff.c +++ b/C/load_coff.c @@ -19,7 +19,7 @@ #include "Foreign.h" #ifdef COFF - +this code is no being maintained anymore #include #include #include @@ -45,8 +45,6 @@ #define N_TXTOFF(x) (sizeof(struct filehdr)+(x).f_opthdr+(x).f_nscns*sizeof(struct scnhdr)) -static char YapExecutable[YAP_FILE_MAX]; - /* * YAP_FindExecutable(argv[0]) should be called on yap initialization to @@ -62,10 +60,10 @@ Yap_FindExecutable(char *name) cp = (char *)getenv("PATH"); if (cp == NULL) cp = ".:/usr/ucb:/bin:/usr/bin:/usr/local/bin"; - if (*Yap_argv[0] == '/') { - if (oktox(Yap_argv[0])) { - strcpy(Yap_FileNameBuf, Yap_argv[0]); - Yap_TrueFileName(Yap_FileNameBuf, YapExecutable, TRUE); + if (*GLOBAL_argv[0] == '/') { + if (oktox(GLOBAL_argv[0])) { + strcpy(LOCAL_FileNameBuf, GLOBAL_argv[0]); + Yap_TrueFileName(LOCAL_FileNameBuf, GLOBAL_Executable, TRUE); return; } } @@ -77,24 +75,24 @@ Yap_FindExecutable(char *name) * argv[0] */ - for (cp2 = Yap_FileNameBuf; (*cp) != 0 && (*cp) != ':';) + for (cp2 = LOCAL_FileNameBuf; (*cp) != 0 && (*cp) != ':';) *cp2++ = *cp++; *cp2++ = '/'; - strcpy(cp2, Yap_argv[0]); + strcpy(cp2, GLOBAL_argv[0]); if (*cp) cp++; - if (!oktox(Yap_FileNameBuf)) + if (!oktox(LOCAL_FileNameBuf)) continue; - Yap_TrueFileName(Yap_FileNameBuf, YapExecutable, TRUE); + Yap_TrueFileName(LOCAL_FileNameBuf, GLOBAL_Executable, TRUE); return; } /* one last try for dual systems */ - strcpy(Yap_FileNameBuf, Yap_argv[0]); - Yap_TrueFileName(Yap_FileNameBuf, YapExecutable, TRUE); - if (oktox(YapExecutable)) + strcpy(LOCAL_FileNameBuf, GLOBAL_argv[0]); + Yap_TrueFileName(LOCAL_FileNameBuf, GLOBAL_Executable, TRUE); + if (oktox(GLOBAL_Executable)) return; else - Yap_Error(SYSTEM_ERROR,MkAtomTerm(Yap_LookupAtom(YapExecutable)), + Yap_Error(SYSTEM_ERROR,MkAtomTerm(Yap_LookupAtom(GLOBAL_Executable)), "cannot find file being executed"); } @@ -175,22 +173,22 @@ LoadForeign(StringList ofiles, /* prepare the magic */ if (strlen(o_files) + strlen(l_files) + strlen(proc_name) + - strlen(YapExecutable) > 2*MAXPATHLEN) { - strcpy(Yap_ErrorSay, " too many parameters in load_foreign/3 "); + strlen(GLOBAL_Executable) > 2*MAXPATHLEN) { + strcpy(LOCAL_ErrorSay, " too many parameters in load_foreign/3 "); return LOAD_FAILLED; } sprintf(command, "/usr/bin/ld -N -A %s -o %s %s %s -lc", - YapExecutable, + GLOBAL_Executable, tfile, o_files, l_files); /* now, do the magic */ if (system(command) != 0) { unlink(tfile); - strcpy(Yap_ErrorSay," ld returned error status in load_foreign_files "); + strcpy(LOCAL_ErrorSay," ld returned error status in load_foreign_files "); return LOAD_FAILLED; } /* now check the music has played */ if ((fildes = open(tfile, O_RDONLY)) < 0) { - strcpy(Yap_ErrorSay," unable to open temp file in load_foreign_files "); + strcpy(LOCAL_ErrorSay," unable to open temp file in load_foreign_files "); return LOAD_FAILLED; } /* it did, get the mice */ @@ -220,7 +218,7 @@ LoadForeign(StringList ofiles, || activate_code(ForeignCodeBase, u1) #endif /* pyr */ ) { - strcpy(Yap_ErrorSay," unable to allocate space for external code "); + strcpy(LOCAL_ErrorSay," unable to allocate space for external code "); return LOAD_FAILLED; } #ifdef mips @@ -253,11 +251,11 @@ LoadForeign(StringList ofiles, /* and do it */ if (system(command) != 0) { unlink(tfile); - strcpy(Yap_ErrorSay," ld returned error status in load_foreign_files "); + strcpy(LOCAL_ErrorSay," ld returned error status in load_foreign_files "); return LOAD_FAILLED; } if ((fildes = open(tfile, O_RDONLY)) < 0) { - strcpy(Yap_ErrorSay," unable to open temp file in load_foreign_files "); + strcpy(LOCAL_ErrorSay," unable to open temp file in load_foreign_files "); return LOAD_FAILLED; } read(fildes, (char *) &fileHeader, sizeof(fileHeader)); @@ -269,7 +267,7 @@ LoadForeign(StringList ofiles, } loadImageSize = sysHeader.tsize + sysHeader.dsize + sysHeader.bsize; if (firstloadImSz < loadImageSize) { - strcpy(Yap_ErrorSay," miscalculation in load_foreign/3 "); + strcpy(LOCAL_ErrorSay," miscalculation in load_foreign/3 "); return LOAD_FAILLED; } /* now search for our init function */ @@ -285,11 +283,11 @@ LoadForeign(StringList ofiles, func_info[0].n_name = entry_fun; func_info[1].n_name = NULL; if (nlist(tfile, func_info) == -1) { - strcpy(Yap_ErrorSay," in nlist(3) "); + strcpy(LOCAL_ErrorSay," in nlist(3) "); return LOAD_FAILLED; } if (func_info[0].n_type == 0) { - strcpy(Yap_ErrorSay," in nlist(3) "); + strcpy(LOCAL_ErrorSay," in nlist(3) "); return LOAD_FAILLED; } *init_proc = (YapInitProc)(func_info[0].n_value); diff --git a/C/load_dl.c b/C/load_dl.c index fe7394d4d..ff3131e9a 100755 --- a/C/load_dl.c +++ b/C/load_dl.c @@ -94,18 +94,18 @@ LoadForeign(StringList ofiles, StringList libs, CACHE_REGS while (libs) { - if (!Yap_TrueFileName(AtomName(libs->name), Yap_FileNameBuf, TRUE)) { + if (!Yap_TrueFileName(AtomName(libs->name), LOCAL_FileNameBuf, TRUE)) { /* use LD_LIBRARY_PATH */ - strncpy(Yap_FileNameBuf, AtomName(libs->name), YAP_FILENAME_MAX); + strncpy(LOCAL_FileNameBuf, AtomName(libs->name), YAP_FILENAME_MAX); } #ifdef __osf__ - if((libs->handle=dlopen(Yap_FileNameBuf,RTLD_LAZY)) == NULL) + if((libs->handle=dlopen(LOCAL_FileNameBuf,RTLD_LAZY)) == NULL) #else - if((libs->handle=dlopen(Yap_FileNameBuf,RTLD_LAZY|RTLD_GLOBAL)) == NULL) + if((libs->handle=dlopen(LOCAL_FileNameBuf,RTLD_LAZY|RTLD_GLOBAL)) == NULL) #endif { - strcpy(Yap_ErrorSay,dlerror()); + strcpy(LOCAL_ErrorSay,dlerror()); return LOAD_FAILLED; } libs = libs->next; @@ -118,18 +118,18 @@ LoadForeign(StringList ofiles, StringList libs, other routines */ /* dlopen wants to follow the LD_CONFIG_PATH */ - if (!Yap_TrueFileName(AtomName(ofiles->name), Yap_FileNameBuf, TRUE)) { - strcpy(Yap_ErrorSay, "%% Trying to open unexisting file in LoadForeign"); + if (!Yap_TrueFileName(AtomName(ofiles->name), LOCAL_FileNameBuf, TRUE)) { + strcpy(LOCAL_ErrorSay, "%% Trying to open unexisting file in LoadForeign"); return LOAD_FAILLED; } #ifdef __osf__ - if((handle=dlopen(Yap_FileNameBuf,RTLD_LAZY)) == 0) + if((handle=dlopen(LOCAL_FileNameBuf,RTLD_LAZY)) == 0) #else - if((handle=dlopen(Yap_FileNameBuf,RTLD_LAZY|RTLD_GLOBAL)) == 0) + if((handle=dlopen(LOCAL_FileNameBuf,RTLD_LAZY|RTLD_GLOBAL)) == 0) #endif { - fprintf(stderr,"dlopen of %s failed with error %s\n", Yap_FileNameBuf, dlerror()); -/* strcpy(Yap_ErrorSay,dlerror());*/ + fprintf(stderr,"dlopen of %s failed with error %s\n", LOCAL_FileNameBuf, dlerror()); +/* strcpy(LOCAL_ErrorSay,dlerror());*/ return LOAD_FAILLED; } @@ -142,7 +142,7 @@ LoadForeign(StringList ofiles, StringList libs, } if(! *init_proc) { - strcpy(Yap_ErrorSay,"Could not locate initialization routine"); + strcpy(LOCAL_ErrorSay,"Could not locate initialization routine"); return LOAD_FAILLED; } diff --git a/C/load_dld.c b/C/load_dld.c index 94f279539..e697011d8 100644 --- a/C/load_dld.c +++ b/C/load_dld.c @@ -20,8 +20,7 @@ #include #include -static char YapExecutable[YAP_FILE_MAX]; - +this code is no being maintained anymore /* * YAP_FindExecutable(argv[0]) should be called on yap initialization to @@ -33,9 +32,9 @@ Yap_FindExecutable(char *name) /* use dld_find_executable */ char *res; if(name != NULL && (res=dld_find_executable(name))) { - strcpy(YapExecutable,res); + strcpy(GLOBAL_Executable,res); } else { - strcpy(YapExecutable,"./yap"); + strcpy(GLOBAL_Executable,"./yap"); } } @@ -71,9 +70,9 @@ LoadForeign(StringList ofiles, StringList libs, int error; if(firstTime) { - error = dld_init(YapExecutable); + error = dld_init(GLOBAL_Executable); if(error) { - strcpy(Yap_ErrorSay,dld_strerror(error)); + strcpy(LOCAL_ErrorSay,dld_strerror(error)); return LOAD_FAILLED; } firstTime=0; @@ -81,7 +80,7 @@ LoadForeign(StringList ofiles, StringList libs, while (ofiles) { if((error=dld_link(AtomName(ofiles->name))) !=0) { - strcpy(Yap_ErrorSay,dld_strerror(error)); + strcpy(LOCAL_ErrorSay,dld_strerror(error)); return LOAD_FAILLED; } ofiles = ofiles->next; @@ -91,14 +90,14 @@ LoadForeign(StringList ofiles, StringList libs, /* TODO: handle libs */ *init_proc = (YapInitProc) dld_get_func(proc_name); if(! *init_proc) { - strcpy(Yap_ErrorSay,"Could not locate initialization routine"); + strcpy(LOCAL_ErrorSay,"Could not locate initialization routine"); return LOAD_FAILLED; } if(!dld_function_executable_p(proc_name)) { char **undefs = dld_list_undefined_sym(); char **p = undefs; int k = dld_undefined_sym_count; - strcpy(Yap_ErrorSay,"Could not resolve all symbols"); + strcpy(LOCAL_ErrorSay,"Could not resolve all symbols"); while(k) { YP_printf("[undefined symbol %s]\n",*p++); --k; diff --git a/C/load_dll.c b/C/load_dll.c index 972ec0ec5..4bb21c1d3 100755 --- a/C/load_dll.c +++ b/C/load_dll.c @@ -66,16 +66,16 @@ LoadForeign(StringList ofiles, StringList libs, while (ofiles) { HINSTANCE handle; - if (Yap_TrueFileName(AtomName(ofiles->name), Yap_FileNameBuf, TRUE) && - (handle=LoadLibrary(Yap_FileNameBuf)) != 0) + if (Yap_TrueFileName(AtomName(ofiles->name), LOCAL_FileNameBuf, TRUE) && + (handle=LoadLibrary(LOCAL_FileNameBuf)) != 0) { - Yap_ErrorSay[0]=~'\0'; + LOCAL_ErrorSay[0]=~'\0'; if (*init_proc == NULL) *init_proc = (YapInitProc)GetProcAddress((HMODULE)handle, proc_name); } else { FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), Yap_ErrorSay, 256, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), LOCAL_ErrorSay, 256, NULL); } ofiles = ofiles->next; @@ -87,15 +87,15 @@ LoadForeign(StringList ofiles, StringList libs, char * s = AtomName(libs->name); if (s[0] == '-') { - strcat(Yap_FileNameBuf,s+2); - strcat(Yap_FileNameBuf,".dll"); + strcat(LOCAL_FileNameBuf,s+2); + strcat(LOCAL_FileNameBuf,".dll"); } else { - strcpy(Yap_FileNameBuf,s); + strcpy(LOCAL_FileNameBuf,s); } - if((handle=LoadLibrary(Yap_FileNameBuf)) == 0) + if((handle=LoadLibrary(LOCAL_FileNameBuf)) == 0) { -/* strcpy(Yap_ErrorSay,dlerror());*/ +/* strcpy(LOCAL_ErrorSay,dlerror());*/ return LOAD_FAILLED; } @@ -106,7 +106,7 @@ LoadForeign(StringList ofiles, StringList libs, } if(*init_proc == NULL) { - strcpy(Yap_ErrorSay,"Could not locate initialization routine"); + strcpy(LOCAL_ErrorSay,"Could not locate initialization routine"); return LOAD_FAILLED; } diff --git a/C/load_dyld.c b/C/load_dyld.c index 8e7b47b25..1367a9c9c 100644 --- a/C/load_dyld.c +++ b/C/load_dyld.c @@ -28,13 +28,13 @@ */ #import -static int dl_errno; + static char * mydlerror(void) { char *errString; - switch(dl_errno) { + switch(LOCAL_dl_errno) { default: case NSObjectFileImageFailure: case NSObjectFileImageFormat: @@ -76,7 +76,7 @@ mydlopen(char *path) NSModule handle = NULL; dyld_result = NSCreateObjectFileImageFromFile(path, &ofile); if (dyld_result != NSObjectFileImageSuccess) { - dl_errno = dyld_result; + LOCAL_dl_errno = dyld_result; } else { /* NSLinkModule will cause the run to abort on any link error's */ /* not very friendly but the error recovery functionality is limited */ @@ -145,14 +145,14 @@ LoadForeign(StringList ofiles, StringList libs, void *handle; /* mydlopen wants to follow the LD_CONFIG_PATH */ - if (!Yap_TrueFileName(AtomName(ofiles->name), Yap_FileNameBuf, TRUE)) { - strcpy(Yap_ErrorSay, "%% Trying to open unexisting file in LoadForeign"); + if (!Yap_TrueFileName(AtomName(ofiles->name), LOCAL_FileNameBuf, TRUE)) { + strcpy(LOCAL_ErrorSay, "%% Trying to open unexisting file in LoadForeign"); return LOAD_FAILLED; } - if((handle=mydlopen(Yap_FileNameBuf)) == 0) + if((handle=mydlopen(LOCAL_FileNameBuf)) == 0) { fprintf(stderr,"calling dlopen with error %s\n", mydlerror()); -/* strcpy(Yap_ErrorSay,dlerror());*/ +/* strcpy(LOCAL_ErrorSay,dlerror());*/ return LOAD_FAILLED; } @@ -166,16 +166,16 @@ LoadForeign(StringList ofiles, StringList libs, char *s = AtomName(lib->name); if (ls[0] == '-') { - strcpy(Yap_FileNameBuf,"lib"); - strcat(Yap_FileNameBuf,s+2); - strcat(Yap_FileNameBuf,".so"); + strcpy(LOCAL_FileNameBuf,"lib"); + strcat(LOCAL_FileNameBuf,s+2); + strcat(LOCAL_FileNameBuf,".so"); } else { - strcpy(Yap_FileNameBuf,s); + strcpy(LOCAL_FileNameBuf,s); } - if((libs->handle=mydlopen(Yap_FileNameBuf)) == NULL) + if((libs->handle=mydlopen(LOCAL_FileNameBuf)) == NULL) { - strcpy(Yap_ErrorSay,mydlerror()); + strcpy(LOCAL_ErrorSay,mydlerror()); return LOAD_FAILLED; } libs = libs->next; @@ -184,7 +184,7 @@ LoadForeign(StringList ofiles, StringList libs, *init_proc = (YapInitProc) mydlsym(proc_name); if(! *init_proc) { - strcpy(Yap_ErrorSay,"Could not locate initialization routine"); + strcpy(LOCAL_ErrorSay,"Could not locate initialization routine"); return LOAD_FAILLED; } diff --git a/C/load_foreign.c b/C/load_foreign.c index e3d4aaa12..d4d3d351e 100755 --- a/C/load_foreign.c +++ b/C/load_foreign.c @@ -47,7 +47,7 @@ p_load_foreign( USES_REGS1 ) StringList new; Int returncode = FALSE; - strcpy(Yap_ErrorSay,"Invalid arguments"); + strcpy(LOCAL_ErrorSay,"Invalid arguments"); /* collect the list of object files */ t = Deref(ARG1); @@ -225,10 +225,10 @@ p_open_shared_objects( USES_REGS1 ) { void Yap_InitLoadForeign( void ) { - if (Yap_argv == NULL) + if (GLOBAL_argv == NULL) Yap_FindExecutable("yap"); else - Yap_FindExecutable(Yap_argv[0]); + Yap_FindExecutable(GLOBAL_argv[0]); Yap_InitCPred("$load_foreign_files", 3, p_load_foreign, SafePredFlag|SyncPredFlag|HiddenPredFlag); Yap_InitCPred("$open_shared_objects", 0, p_open_shared_objects, SafePredFlag|HiddenPredFlag); Yap_InitCPred("$open_shared_object", 3, p_open_shared_object, SyncPredFlag|HiddenPredFlag); diff --git a/C/load_none.c b/C/load_none.c index 45aeb5c54..9a9c4a01c 100644 --- a/C/load_none.c +++ b/C/load_none.c @@ -40,7 +40,7 @@ static Int LoadForeign(StringList ofiles, StringList libs, char *proc_name, YapInitProc *init_proc) { - strcpy(Yap_ErrorSay,"load_foreign not supported in this version of Yap"); + strcpy(LOCAL_ErrorSay,"load_foreign not supported in this version of Yap"); return LOAD_FAILLED; } diff --git a/C/load_shl.c b/C/load_shl.c index 0ff8799d4..25c1f573c 100644 --- a/C/load_shl.c +++ b/C/load_shl.c @@ -61,17 +61,17 @@ LoadForeign( StringList ofiles, StringList libs, int valid_fname; /* shl_load wants to follow the LD_CONFIG_PATH */ - valid_fname = Yap_TrueFileName( AtomName(ofiles->name), Yap_FileNameBuf, TRUE ); + valid_fname = Yap_TrueFileName( AtomName(ofiles->name), LOCAL_FileNameBuf, TRUE ); if( !valid_fname ) { - strcpy( Yap_ErrorSay, "%% Trying to open non-existing file in LoadForeign" ); + strcpy( LOCAL_ErrorSay, "%% Trying to open non-existing file in LoadForeign" ); return LOAD_FAILLED; } ofiles->handle = Yap_AllocCodeSpace( sizeof(shl_t) ); - *(shl_t *)ofiles->handle = shl_load( Yap_FileNameBuf, BIND_DEFERRED, 0 ); + *(shl_t *)ofiles->handle = shl_load( LOCAL_FileNameBuf, BIND_DEFERRED, 0 ); if( *(shl_t *)ofiles->handle == NULL ) { - strncpy( Yap_ErrorSay, strerror(errno), MAX_ERROR_MSG_SIZE ); + strncpy( LOCAL_ErrorSay, strerror(errno), MAX_ERROR_MSG_SIZE ); return LOAD_FAILLED; } @@ -84,7 +84,7 @@ LoadForeign( StringList ofiles, StringList libs, } if( init_missing ) { - strcpy( Yap_ErrorSay, "Could not locate initialization routine" ); + strcpy( LOCAL_ErrorSay, "Could not locate initialization routine" ); return LOAD_FAILLED; } @@ -92,17 +92,17 @@ LoadForeign( StringList ofiles, StringList libs, char *s = AtomName(lib->s); if( s[0] == '-' ) { - strcpy( Yap_FileNameBuf, "lib" ); - strcat( Yap_FileNameBuf, s+2 ); - strcat( Yap_FileNameBuf, ".sl" ); + strcpy( LOCAL_FileNameBuf, "lib" ); + strcat( LOCAL_FileNameBuf, s+2 ); + strcat( LOCAL_FileNameBuf, ".sl" ); } else { - strcpy( Yap_FileNameBuf, s ); + strcpy( LOCAL_FileNameBuf, s ); } - *(shl_t *)libs->handle = shl_load( Yap_FileNameBuf, BIND_DEFERRED, 0 ); + *(shl_t *)libs->handle = shl_load( LOCAL_FileNameBuf, BIND_DEFERRED, 0 ); if( *(shl_t *)libs->handle == NULL ) { - strncpy( Yap_ErrorSay, strerror(errno), MAX_ERROR_MSG_SIZE ); + strncpy( LOCAL_ErrorSay, strerror(errno), MAX_ERROR_MSG_SIZE ); return LOAD_FAILLED; } diff --git a/C/parser.c b/C/parser.c index ead666d36..044c85c96 100644 --- a/C/parser.c +++ b/C/parser.c @@ -77,7 +77,7 @@ STATIC_PROTO(Term ParseTerm, (int, JMPBUFF * CACHE_TYPE)); #define TRY(S,P) \ { Volatile JMPBUFF *saveenv, newenv; \ - Volatile TokEntry *saveT=Yap_tokptr; \ + Volatile TokEntry *saveT=LOCAL_tokptr; \ Volatile CELL *saveH=H; \ Volatile int savecurprio=curprio; \ saveenv=FailBuff; \ @@ -90,13 +90,13 @@ STATIC_PROTO(Term ParseTerm, (int, JMPBUFF * CACHE_TYPE)); else { FailBuff=saveenv; \ H=saveH; \ curprio = savecurprio; \ - Yap_tokptr=saveT; \ + LOCAL_tokptr=saveT; \ } \ } #define TRY3(S,P,F) \ { Volatile JMPBUFF *saveenv, newenv; \ - Volatile TokEntry *saveT=Yap_tokptr; \ + Volatile TokEntry *saveT=LOCAL_tokptr; \ Volatile CELL *saveH=H; \ saveenv=FailBuff; \ if(!sigsetjmp(newenv.JmpBuff, 0)) { \ @@ -108,7 +108,7 @@ STATIC_PROTO(Term ParseTerm, (int, JMPBUFF * CACHE_TYPE)); else { \ FailBuff=saveenv; \ H=saveH; \ - Yap_tokptr=saveT; \ + LOCAL_tokptr=saveT; \ F } \ } @@ -122,15 +122,15 @@ Yap_LookupVar(char *var) /* lookup variable in variables table */ VarEntry *p; #ifdef DEBUG - if (Yap_Option[4]) - fprintf(Yap_stderr,"[LookupVar %s]", var); + if (GLOBAL_Option[4]) + fprintf(GLOBAL_stderr,"[LookupVar %s]", var); #endif if (var[0] != '_' || var[1] != '\0') { - VarEntry **op = &Yap_VarTable; + VarEntry **op = &LOCAL_VarTable; unsigned char *vp = (unsigned char *)var; UInt hv; - p = Yap_VarTable; + p = LOCAL_VarTable; hv = HashFunction(vp) % AtomHashTableSize; while (p != NULL) { CELL hpv = p->hv; @@ -161,8 +161,8 @@ Yap_LookupVar(char *var) /* lookup variable in variables table */ } else { /* anon var */ p = (VarEntry *) Yap_AllocScannerMemory(sizeof(VarEntry) + 2); - p->VarLeft = Yap_AnonVarTable; - Yap_AnonVarTable = p; + p->VarLeft = LOCAL_AnonVarTable; + LOCAL_AnonVarTable = p; p->VarRight = NULL; p->hv = 0L; p->VarRep[0] = '_'; @@ -182,7 +182,7 @@ VarNames(VarEntry *p,Term l USES_REGS) VarNames(p->VarLeft,l PASS_REGS) PASS_REGS)); if (H > ASP-4096) { save_machine_regs(); - siglongjmp(Yap_IOBotch,1); + siglongjmp(LOCAL_IOBotch,1); } return(o); } else { @@ -295,24 +295,19 @@ Yap_IsPosfixOp(Atom op, int *pptr, int *lpptr) inline static void GNextToken( USES_REGS1 ) { - if (Yap_tokptr->Tok == Ord(eot_tok)) + if (LOCAL_tokptr->Tok == Ord(eot_tok)) return; -#ifdef EMACS - if ((Yap_tokptr = Yap_tokptr->TokNext)->TokPos > Yap_toktide->TokPos) - Yap_toktide = Yap_tokptr; -#else - if (Yap_tokptr == Yap_toktide) - Yap_toktide = Yap_tokptr = Yap_tokptr->TokNext; + if (LOCAL_tokptr == LOCAL_toktide) + LOCAL_toktide = LOCAL_tokptr = LOCAL_tokptr->TokNext; else - Yap_tokptr = Yap_tokptr->TokNext; -#endif + LOCAL_tokptr = LOCAL_tokptr->TokNext; } inline static void checkfor(Term c, JMPBUFF *FailBuff USES_REGS) { - if (Yap_tokptr->Tok != Ord(Ponctuation_tok) - || Yap_tokptr->TokInfo != c) + if (LOCAL_tokptr->Tok != Ord(Ponctuation_tok) + || LOCAL_tokptr->TokInfo != c) FAIL; NextToken; } @@ -331,16 +326,16 @@ ParseArgs(Atom a, JMPBUFF *FailBuff USES_REGS) p = (Term *) ParserAuxSp; while (1) { Term *tp = (Term *)ParserAuxSp; - if (ParserAuxSp+1 > Yap_TrailTop) { - Yap_ErrorMessage = "Trail Overflow"; + if (ParserAuxSp+1 > LOCAL_TrailTop) { + LOCAL_ErrorMessage = "Trail Overflow"; FAIL; } *tp++ = Unsigned(ParseTerm(999, FailBuff PASS_REGS)); ParserAuxSp = (char *)tp; ++nargs; - if (Yap_tokptr->Tok != Ord(Ponctuation_tok)) + if (LOCAL_tokptr->Tok != Ord(Ponctuation_tok)) break; - if (((int) Yap_tokptr->TokInfo) != ',') + if (((int) LOCAL_tokptr->TokInfo) != ',') break; NextToken; } @@ -350,12 +345,12 @@ ParseArgs(Atom a, JMPBUFF *FailBuff USES_REGS) * order */ if (H > ASP-(nargs+1)) { - Yap_ErrorMessage = "Stack Overflow"; + LOCAL_ErrorMessage = "Stack Overflow"; FAIL; } func = Yap_MkFunctor(a, nargs); if (func == NULL) { - Yap_ErrorMessage = "Heap Overflow"; + LOCAL_ErrorMessage = "Heap Overflow"; FAIL; } #ifdef SFUNC @@ -370,7 +365,7 @@ ParseArgs(Atom a, JMPBUFF *FailBuff USES_REGS) t = Yap_MkApplTerm(func, nargs, p); #endif if (H > ASP-4096) { - Yap_ErrorMessage = "Stack Overflow"; + LOCAL_ErrorMessage = "Stack Overflow"; return TermNil; } /* check for possible overflow against local stack */ @@ -389,25 +384,25 @@ ParseList(JMPBUFF *FailBuff USES_REGS) to_store = H; H+=2; to_store[0] = ParseTerm(999, FailBuff PASS_REGS); - if (Yap_tokptr->Tok == Ord(Ponctuation_tok)) { - if (((int) Yap_tokptr->TokInfo) == ',') { + if (LOCAL_tokptr->Tok == Ord(Ponctuation_tok)) { + if (((int) LOCAL_tokptr->TokInfo) == ',') { NextToken; - if (Yap_tokptr->Tok == Ord(Name_tok) - && strcmp(RepAtom((Atom)(Yap_tokptr->TokInfo))->StrOfAE, "..") == 0) { + if (LOCAL_tokptr->Tok == Ord(Name_tok) + && strcmp(RepAtom((Atom)(LOCAL_tokptr->TokInfo))->StrOfAE, "..") == 0) { NextToken; to_store[1] = ParseTerm(999, FailBuff PASS_REGS); } else { /* check for possible overflow against local stack */ if (H > ASP-4096) { to_store[1] = TermNil; - Yap_ErrorMessage = "Stack Overflow"; + LOCAL_ErrorMessage = "Stack Overflow"; FAIL; } else { to_store[1] = AbsPair(H); goto loop; } } - } else if (((int) Yap_tokptr->TokInfo) == '|') { + } else if (((int) LOCAL_tokptr->TokInfo) == '|') { NextToken; to_store[1] = ParseTerm(999, FailBuff PASS_REGS); } else { @@ -436,14 +431,14 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) Volatile int curprio = 0, opprio, oplprio, oprprio; Volatile Atom opinfo; - switch (Yap_tokptr->Tok) { + switch (LOCAL_tokptr->Tok) { case Name_tok: - t = Yap_tokptr->TokInfo; + t = LOCAL_tokptr->TokInfo; NextToken; /* special rules apply for +1, -2.3, etc... */ - if (Yap_tokptr->Tok == Number_tok) { + if (LOCAL_tokptr->Tok == Number_tok) { if ((Atom)t == AtomMinus) { - t = Yap_tokptr->TokInfo; + t = LOCAL_tokptr->TokInfo; if (IsIntTerm(t)) t = MkIntTerm(-IntOfTerm(t)); else if (IsFloatTerm(t)) @@ -459,12 +454,12 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) break; } } - if ((Yap_tokptr->Tok != Ord(Ponctuation_tok) - || Unsigned(Yap_tokptr->TokInfo) != 'l') + if ((LOCAL_tokptr->Tok != Ord(Ponctuation_tok) + || Unsigned(LOCAL_tokptr->TokInfo) != 'l') && IsPrefixOp((Atom)t, &opprio, &oprprio PASS_REGS) ) { - if (Yap_tokptr->Tok == Name_tok) { - Atom at = (Atom)Yap_tokptr->TokInfo; + if (LOCAL_tokptr->Tok == Name_tok) { + Atom at = (Atom)LOCAL_tokptr->TokInfo; #ifndef _MSC_VER if ((Atom)t == AtomPlus) { if (at == AtomInf) { @@ -495,14 +490,14 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) /* build appl on the heap */ func = Yap_MkFunctor((Atom) t, 1); if (func == NULL) { - Yap_ErrorMessage = "Heap Overflow"; + LOCAL_ErrorMessage = "Heap Overflow"; FAIL; } t = ParseTerm(oprprio, FailBuff PASS_REGS); t = Yap_MkApplTerm(func, 1, &t); /* check for possible overflow against local stack */ if (H > ASP-4096) { - Yap_ErrorMessage = "Stack Overflow"; + LOCAL_ErrorMessage = "Stack Overflow"; FAIL; } curprio = opprio; @@ -511,21 +506,21 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) ) } } - if (Yap_tokptr->Tok == Ord(Ponctuation_tok) - && Unsigned(Yap_tokptr->TokInfo) == 'l') + if (LOCAL_tokptr->Tok == Ord(Ponctuation_tok) + && Unsigned(LOCAL_tokptr->TokInfo) == 'l') t = ParseArgs((Atom) t, FailBuff PASS_REGS); else t = MkAtomTerm((Atom)t); break; case Number_tok: - t = Yap_tokptr->TokInfo; + t = LOCAL_tokptr->TokInfo; NextToken; break; case String_tok: /* build list on the heap */ { - Volatile char *p = (char *) Yap_tokptr->TokInfo; + Volatile char *p = (char *) LOCAL_tokptr->TokInfo; if (*p == 0) t = MkAtomTerm(AtomNil); else if (yap_flags[YAP_DOUBLE_QUOTES_FLAG] == STRING_AS_CHARS) @@ -533,7 +528,7 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) else if (yap_flags[YAP_DOUBLE_QUOTES_FLAG] == STRING_AS_ATOM) { Atom at = Yap_LookupAtom(p); if (at == NIL) { - Yap_ErrorMessage = "Heap Overflow"; + LOCAL_ErrorMessage = "Heap Overflow"; FAIL; } t = MkAtomTerm(at); @@ -545,7 +540,7 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) case WString_tok: /* build list on the heap */ { - Volatile wchar_t *p = (wchar_t *) Yap_tokptr->TokInfo; + Volatile wchar_t *p = (wchar_t *) LOCAL_tokptr->TokInfo; if (*p == 0) t = MkAtomTerm(AtomNil); else if (yap_flags[YAP_DOUBLE_QUOTES_FLAG] == STRING_AS_CHARS) @@ -559,7 +554,7 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) break; case Var_tok: - varinfo = (VarEntry *) (Yap_tokptr->TokInfo); + varinfo = (VarEntry *) (LOCAL_tokptr->TokInfo); if ((t = varinfo->VarAdr) == TermNil) { t = varinfo->VarAdr = MkVarTerm(); } @@ -570,7 +565,7 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) FAIL; case Ponctuation_tok: - switch ((int) Yap_tokptr->TokInfo) { + switch ((int) LOCAL_tokptr->TokInfo) { case '(': case 'l': /* non solo ( */ NextToken; @@ -588,7 +583,7 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) t = Yap_MkApplTerm(FunctorBraces, 1, &t); /* check for possible overflow against local stack */ if (H > ASP-4096) { - Yap_ErrorMessage = "Stack Overflow"; + LOCAL_ErrorMessage = "Stack Overflow"; FAIL; } checkfor((Term) '}', FailBuff PASS_REGS); @@ -605,17 +600,17 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) /* main loop to parse infix and posfix operators starts here */ while (TRUE) { - if (Yap_tokptr->Tok == Ord(Name_tok) - && Yap_HasOp((Atom)(Yap_tokptr->TokInfo))) { - Atom save_opinfo = opinfo = (Atom)(Yap_tokptr->TokInfo); + if (LOCAL_tokptr->Tok == Ord(Name_tok) + && Yap_HasOp((Atom)(LOCAL_tokptr->TokInfo))) { + Atom save_opinfo = opinfo = (Atom)(LOCAL_tokptr->TokInfo); if (IsInfixOp(save_opinfo, &opprio, &oplprio, &oprprio PASS_REGS) && opprio <= prio && oplprio >= curprio) { /* try parsing as infix operator */ Volatile int oldprio = curprio; TRY3( - func = Yap_MkFunctor((Atom) Yap_tokptr->TokInfo, 2); + func = Yap_MkFunctor((Atom) LOCAL_tokptr->TokInfo, 2); if (func == NULL) { - Yap_ErrorMessage = "Heap Overflow"; + LOCAL_ErrorMessage = "Heap Overflow"; FAIL; } NextToken; @@ -626,7 +621,7 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) t = Yap_MkApplTerm(func, 2, args); /* check for possible overflow against local stack */ if (H > ASP-4096) { - Yap_ErrorMessage = "Stack Overflow"; + LOCAL_ErrorMessage = "Stack Overflow"; FAIL; } }, @@ -641,15 +636,15 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) if (IsPosfixOp(opinfo, &opprio, &oplprio PASS_REGS) && opprio <= prio && oplprio >= curprio) { /* parse as posfix operator */ - Functor func = Yap_MkFunctor((Atom) Yap_tokptr->TokInfo, 1); + Functor func = Yap_MkFunctor((Atom) LOCAL_tokptr->TokInfo, 1); if (func == NULL) { - Yap_ErrorMessage = "Heap Overflow"; + LOCAL_ErrorMessage = "Heap Overflow"; FAIL; } t = Yap_MkApplTerm(func, 1, &t); /* check for possible overflow against local stack */ if (H > ASP-4096) { - Yap_ErrorMessage = "Stack Overflow"; + LOCAL_ErrorMessage = "Stack Overflow"; FAIL; } curprio = opprio; @@ -658,8 +653,8 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) } break; } - if (Yap_tokptr->Tok == Ord(Ponctuation_tok)) { - if (Unsigned(Yap_tokptr->TokInfo) == ',' && + if (LOCAL_tokptr->Tok == Ord(Ponctuation_tok)) { + if (Unsigned(LOCAL_tokptr->TokInfo) == ',' && prio >= 1000 && curprio <= 999) { Volatile Term args[2]; NextToken; @@ -668,12 +663,12 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) t = Yap_MkApplTerm(FunctorComma, 2, args); /* check for possible overflow against local stack */ if (H > ASP-4096) { - Yap_ErrorMessage = "Stack Overflow"; + LOCAL_ErrorMessage = "Stack Overflow"; FAIL; } curprio = 1000; continue; - } else if (Unsigned(Yap_tokptr->TokInfo) == '|' && + } else if (Unsigned(LOCAL_tokptr->TokInfo) == '|' && IsInfixOp(AtomVBar, &opprio, &oplprio, &oprprio PASS_REGS) && opprio <= prio && oplprio >= curprio) { Volatile Term args[2]; @@ -683,23 +678,23 @@ ParseTerm(int prio, JMPBUFF *FailBuff USES_REGS) t = Yap_MkApplTerm(FunctorVBar, 2, args); /* check for possible overflow against local stack */ if (H > ASP-4096) { - Yap_ErrorMessage = "Stack Overflow"; + LOCAL_ErrorMessage = "Stack Overflow"; FAIL; } curprio = opprio; continue; } } - if (Yap_tokptr->Tok <= Ord(WString_tok)) + if (LOCAL_tokptr->Tok <= Ord(WString_tok)) FAIL; break; } #ifdef DEBUG - if (Yap_Option['p' - 'a' + 1]) { - Yap_DebugPutc(Yap_c_error_stream,'['); + if (GLOBAL_Option['p' - 'a' + 1]) { + Yap_DebugPutc(LOCAL_c_error_stream,'['); Yap_DebugPlWrite(t); - Yap_DebugPutc(Yap_c_error_stream,']'); - Yap_DebugPutc(Yap_c_error_stream,'\n'); + Yap_DebugPutc(LOCAL_c_error_stream,']'); + Yap_DebugPutc(LOCAL_c_error_stream,'\n'); } #endif return t; @@ -715,7 +710,7 @@ Yap_Parse(void) if (!sigsetjmp(FailBuff.JmpBuff, 0)) { t = ParseTerm(1200, &FailBuff PASS_REGS); - if (Yap_tokptr->Tok != Ord(eot_tok)) + if (LOCAL_tokptr->Tok != Ord(eot_tok)) return (0L); return (t); } else diff --git a/C/save.c b/C/save.c index 32bcfeae8..80924d8c2 100755 --- a/C/save.c +++ b/C/save.c @@ -164,19 +164,19 @@ do_system_error(yap_error_number etype, const char *msg) CACHE_REGS #if HAVE_SNPRINTF #if HAVE_STRERROR - snprintf(Yap_ErrorSay,MAX_ERROR_MSG_SIZE,"%s (%s when reading %s)", msg, strerror(errno), Yap_FileNameBuf); + snprintf(LOCAL_ErrorSay,MAX_ERROR_MSG_SIZE,"%s (%s when reading %s)", msg, strerror(errno), LOCAL_FileNameBuf); #else - snprintf(Yap_ErrorSay,MAX_ERROR_MSG_SIZE,"%s, (system error %d when reading %s)",msg,errno,Yap_FileNameBuf); + snprintf(LOCAL_ErrorSay,MAX_ERROR_MSG_SIZE,"%s, (system error %d when reading %s)",msg,errno,LOCAL_FileNameBuf); #endif #else #if HAVE_STRERROR - sprintf(Yap_ErrorSay,"%s, (%s when reading %s)",msg,strerror(errno),Yap_FileNameBuf); + sprintf(LOCAL_ErrorSay,"%s, (%s when reading %s)",msg,strerror(errno),LOCAL_FileNameBuf); #else - sprintf(Yap_ErrorSay,"%s, (system error %d when reading %s)",msg,errno,Yap_FileNameBuf); + sprintf(LOCAL_ErrorSay,"%s, (system error %d when reading %s)",msg,errno,LOCAL_FileNameBuf); #endif #endif - Yap_ErrorMessage = Yap_ErrorSay; - Yap_Error_TYPE = etype; + LOCAL_ErrorMessage = LOCAL_ErrorSay; + LOCAL_Error_TYPE = etype; return -1; } @@ -227,7 +227,7 @@ static int splfild = 0; #ifdef DEBUG_RESTORE4 static FILE *errout; #else -#define errout Yap_stderr +#define errout GLOBAL_stderr #endif #endif /* DEBUG */ @@ -349,13 +349,13 @@ put_info(int info, int mode USES_REGS) return -1; /* current state of stacks, to be used by SavedInfo */ /* space available in heap area */ - if (putout(Unsigned(Yap_GlobalBase)-Unsigned(Yap_HeapBase)) < 0) + if (putout(Unsigned(LOCAL_GlobalBase)-Unsigned(Yap_HeapBase)) < 0) return -1; /* space available for stacks */ - if (putout(Unsigned(Yap_LocalBase)-Unsigned(Yap_GlobalBase)) < 0) + if (putout(Unsigned(LOCAL_LocalBase)-Unsigned(LOCAL_GlobalBase)) < 0) return -1; /* space available for trail */ - if (putout(Unsigned(Yap_TrailTop)-Unsigned(Yap_TrailBase)) < 0) + if (putout(Unsigned(LOCAL_TrailTop)-Unsigned(LOCAL_TrailBase)) < 0) return -1; /* Space used in heap area */ if (putout(Unsigned(HeapTop)-Unsigned(Yap_HeapBase)) < 0) @@ -364,10 +364,10 @@ put_info(int info, int mode USES_REGS) if (putout(Unsigned(LCL0)-Unsigned(ASP)) < 0) return -1; /* Space used for global stack */ - if (putout(Unsigned(H) - Unsigned(Yap_GlobalBase)) < 0) + if (putout(Unsigned(H) - Unsigned(LOCAL_GlobalBase)) < 0) return -1; /* Space used for trail */ - if (putout(Unsigned(TR) - Unsigned(Yap_TrailBase)) < 0) + if (putout(Unsigned(TR) - Unsigned(LOCAL_TrailBase)) < 0) return -1; return 0; } @@ -422,18 +422,18 @@ save_regs(int mode USES_REGS) return -1; if (mode == DO_EVERYTHING) { #ifdef COROUTINING - if (putout(WokenGoals) < 0) + if (putout(LOCAL_WokenGoals) < 0) return -1; #endif #ifdef DEPTH_LIMIT if (putout(DEPTH) < 0) return -1; #endif - if (putout(GcGeneration) < 0) + if (putout(LOCAL_GcGeneration) < 0) return -1; - if (putout(GcPhase) < 0) + if (putout(LOCAL_GcPhase) < 0) return -1; - if (putout(GcCurrentPhase) < 0) + if (putout(LOCAL_GcCurrentPhase) < 0) return -1; } /* The operand base */ @@ -459,11 +459,11 @@ save_regs(int mode USES_REGS) return -1; if (putcellptr(CellPtr(AuxTop)) < 0) return -1; - if (putcellptr(CellPtr(ScratchPad.ptr)) < 0) + if (putcellptr(CellPtr(LOCAL_ScratchPad.ptr)) < 0) return -1; - if (putout(ScratchPad.sz) < 0) + if (putout(LOCAL_ScratchPad.sz) < 0) return -1; - if (putout(ScratchPad.msz) < 0) + if (putout(LOCAL_ScratchPad.msz) < 0) return -1; if (mode == DO_EVERYTHING) { /* put the old trail base, just in case it moves again */ @@ -473,7 +473,7 @@ save_regs(int mode USES_REGS) if (putout(ARG2) < 0) return -1; } - if (putcellptr(CellPtr(Yap_TrailBase)) < 0) + if (putcellptr(CellPtr(LOCAL_TrailBase)) < 0) return -1; } return 0; @@ -528,18 +528,18 @@ save_stacks(int mode USES_REGS) if (mywrite(splfild, (char *) ASP, j) < 0) return -1; /* Save the global stack */ - j = Unsigned(H) - Unsigned(Yap_GlobalBase); - if (mywrite(splfild, (char *) Yap_GlobalBase, j) < 0) + j = Unsigned(H) - Unsigned(LOCAL_GlobalBase); + if (mywrite(splfild, (char *) LOCAL_GlobalBase, j) < 0) return -1; /* Save the trail */ - j = Unsigned(TR) - Unsigned(Yap_TrailBase); - if (mywrite(splfild, (char *) Yap_TrailBase, j) < 0) + j = Unsigned(TR) - Unsigned(LOCAL_TrailBase); + if (mywrite(splfild, (char *) LOCAL_TrailBase, j) < 0) return -1; break; case DO_ONLY_CODE: { tr_fr_ptr tr_ptr = TR; - while (tr_ptr != (tr_fr_ptr)Yap_TrailBase) { + while (tr_ptr != (tr_fr_ptr)LOCAL_TrailBase) { CELL val = TrailTerm(tr_ptr-1); if (IsVarTerm(val)) { CELL *d1 = VarOfTerm(val); @@ -577,18 +577,18 @@ do_save(int mode USES_REGS) { Term t1 = Deref(ARG1); if (Yap_HoleSize) { - Yap_Error(SYSTEM_ERROR,MkAtomTerm(Yap_LookupAtom(Yap_FileNameBuf)), + Yap_Error(SYSTEM_ERROR,MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf)), "restore/1: address space has holes of size %ld, cannot save", (long int)Yap_HoleSize); return FALSE; } - if (!Yap_GetName(Yap_FileNameBuf, YAP_FILENAME_MAX, t1)) { + if (!Yap_GetName(LOCAL_FileNameBuf, YAP_FILENAME_MAX, t1)) { Yap_Error(TYPE_ERROR_LIST,t1,"save/1"); return FALSE; } Scleanup(); Yap_CloseStreams(TRUE); - if ((splfild = open_file(Yap_FileNameBuf, O_WRONLY | O_CREAT)) < 0) { - Yap_Error(SYSTEM_ERROR,MkAtomTerm(Yap_LookupAtom(Yap_FileNameBuf)), + if ((splfild = open_file(LOCAL_FileNameBuf, O_WRONLY | O_CREAT)) < 0) { + Yap_Error(SYSTEM_ERROR,MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf)), "restore/1, open(%s)", strerror(errno)); return(FALSE); } @@ -616,14 +616,14 @@ p_save2( USES_REGS1 ) Term t; #ifdef YAPOR - if (Yap_number_workers != 1) { + if (GLOBAL_number_workers != 1) { Yap_Error(SYSTEM_ERROR,TermNil, "cannot perform save: more than a worker/thread running"); return(FALSE); } #endif /* YAPOR */ #ifdef THREADS - if (Yap_NOfThreads != 1) { + if (GLOBAL_NOfThreads != 1) { Yap_Error(SYSTEM_ERROR,TermNil, "cannot perform save: more than a worker/thread running"); return(FALSE); @@ -682,42 +682,42 @@ check_header(CELL *info, CELL *ATrail, CELL *AStack, CELL *AHeap USES_REGS) } } if (strcmp(pp, msg) != 0) { - Yap_ErrorMessage = Yap_ErrorSay; - strncpy(Yap_ErrorMessage, "saved state ", MAX_ERROR_MSG_SIZE); - strncat(Yap_ErrorMessage, Yap_FileNameBuf, MAX_ERROR_MSG_SIZE); - strncat(Yap_ErrorMessage, " failed to match version ID", MAX_ERROR_MSG_SIZE); - Yap_Error_TYPE = CONSISTENCY_ERROR; + LOCAL_ErrorMessage = LOCAL_ErrorSay; + strncpy(LOCAL_ErrorMessage, "saved state ", MAX_ERROR_MSG_SIZE); + strncat(LOCAL_ErrorMessage, LOCAL_FileNameBuf, MAX_ERROR_MSG_SIZE); + strncat(LOCAL_ErrorMessage, " failed to match version ID", MAX_ERROR_MSG_SIZE); + LOCAL_Error_TYPE = CONSISTENCY_ERROR; return FAIL_RESTORE; } /* check info on header */ /* ignore info on saved state */ *info = get_header_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return FAIL_RESTORE; /* check the restore mode */ mode = get_header_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return FAIL_RESTORE; if (mode != DO_EVERYTHING && mode != DO_ONLY_CODE) { return FAIL_RESTORE; } /* ignore info on stacks size */ *AHeap = get_header_cell(); - if (Yap_ErrorMessage) { + if (LOCAL_ErrorMessage) { return FAIL_RESTORE; } *AStack = get_header_cell(); - if (Yap_ErrorMessage) { + if (LOCAL_ErrorMessage) { return FAIL_RESTORE; } *ATrail = get_header_cell(); - if (Yap_ErrorMessage) { + if (LOCAL_ErrorMessage) { return FAIL_RESTORE; } /* now, check whether we got enough enough space to load the saved space */ hp_size = get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return FAIL_RESTORE; while (Yap_HeapBase != NULL && hp_size > Unsigned(HeapLim) - Unsigned(Yap_HeapBase)) { @@ -727,31 +727,31 @@ check_header(CELL *info, CELL *ATrail, CELL *AStack, CELL *AHeap USES_REGS) } if (mode == DO_EVERYTHING) { lc_size = get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return FAIL_RESTORE; gb_size=get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return FAIL_RESTORE; - if (Yap_HeapBase != NULL && lc_size+gb_size > Unsigned(Yap_LocalBase) - Unsigned(Yap_GlobalBase)) { - if (Yap_ErrorMessage != NULL) - Yap_ErrorMessage = "could not allocate enough stack space"; + if (Yap_HeapBase != NULL && lc_size+gb_size > Unsigned(LOCAL_LocalBase) - Unsigned(LOCAL_GlobalBase)) { + if (LOCAL_ErrorMessage != NULL) + LOCAL_ErrorMessage = "could not allocate enough stack space"; return FAIL_RESTORE; } - if (Yap_HeapBase != NULL && (tr_size = get_cell()) > Unsigned(Yap_TrailTop) - Unsigned(Yap_TrailBase)) { - if (Yap_ErrorMessage != NULL) - Yap_ErrorMessage = "could not allocate enough trail space"; + if (Yap_HeapBase != NULL && (tr_size = get_cell()) > Unsigned(LOCAL_TrailTop) - Unsigned(LOCAL_TrailBase)) { + if (LOCAL_ErrorMessage != NULL) + LOCAL_ErrorMessage = "could not allocate enough trail space"; return FAIL_RESTORE; } } else { /* skip cell size */ get_header_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return FAIL_RESTORE; get_header_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return FAIL_RESTORE; get_header_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return FAIL_RESTORE; } return(mode); @@ -761,38 +761,38 @@ check_header(CELL *info, CELL *ATrail, CELL *AStack, CELL *AHeap USES_REGS) static int get_heap_info(USES_REGS1) { - OldHeapBase = (ADDR) get_cellptr(); - if (Yap_ErrorMessage) + LOCAL_OldHeapBase = (ADDR) get_cellptr(); + if (LOCAL_ErrorMessage) return -1; - OldHeapTop = (ADDR) get_cellptr(); + LOCAL_OldHeapTop = (ADDR) get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; OldHeapUsed = (Int) get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; FreeBlocks = (BlockHeader *) get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; AuxBase = (ADDR)get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; AuxSp = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; AuxTop = (ADDR)get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; - ScratchPad.ptr = (ADDR)get_cellptr(); - if (Yap_ErrorMessage) + LOCAL_ScratchPad.ptr = (ADDR)get_cellptr(); + if (LOCAL_ErrorMessage) return -1; - ScratchPad.sz = get_cell(); - if (Yap_ErrorMessage) + LOCAL_ScratchPad.sz = get_cell(); + if (LOCAL_ErrorMessage) return -1; - ScratchPad.msz = get_cell(); - if (Yap_ErrorMessage) + LOCAL_ScratchPad.msz = get_cell(); + if (LOCAL_ErrorMessage) return -1; - HDiff = Unsigned(Yap_HeapBase) - Unsigned(OldHeapBase); + LOCAL_HDiff = Unsigned(Yap_HeapBase) - Unsigned(LOCAL_OldHeapBase); return 1; } @@ -802,130 +802,130 @@ get_heap_info(USES_REGS1) static int get_regs(int flag USES_REGS) { - CELL *NewGlobalBase = (CELL *)Yap_GlobalBase; + CELL *NewGlobalBase = (CELL *)LOCAL_GlobalBase; CELL *NewLCL0 = LCL0; CELL *OldXREGS; /* Get regs */ compile_arrays = (int)get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; if (flag == DO_EVERYTHING) { CP = (yamop *)get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; ENV = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; ASP = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; /* N = get_cell(); */ H0 = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; LCL0 = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; H = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; HB = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; B = (choiceptr)get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; TR = (tr_fr_ptr)get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; YENV = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; S = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; P = (yamop *)get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; CreepFlag = get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; EX = (struct DB_TERM *)get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; #if defined(YAPOR_SBA) || defined(TABLING) H_FZ = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; B_FZ = (choiceptr)get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; TR_FZ = (tr_fr_ptr)get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; #endif /* YAPOR_SBA || TABLING */ } CurrentModule = get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; if (flag == DO_EVERYTHING) { #ifdef COROUTINING - WokenGoals = get_cell(); - if (Yap_ErrorMessage) + LOCAL_WokenGoals = get_cell(); + if (LOCAL_ErrorMessage) return -1; #endif #ifdef DEPTH_LIMIT DEPTH = get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; #endif - GcGeneration = get_cell(); - if (Yap_ErrorMessage) + LOCAL_GcGeneration = get_cell(); + if (LOCAL_ErrorMessage) return -1; - GcPhase = get_cell(); - if (Yap_ErrorMessage) + LOCAL_GcPhase = get_cell(); + if (LOCAL_ErrorMessage) return -1; - GcCurrentPhase = get_cell(); - if (Yap_ErrorMessage) + LOCAL_GcCurrentPhase = get_cell(); + if (LOCAL_ErrorMessage) return -1; } /* Get the old bases */ OldXREGS = get_cellptr(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; which_save = get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; - XDiff = (CELL)XREGS - (CELL)OldXREGS; - if (Yap_ErrorMessage) + LOCAL_XDiff = (CELL)XREGS - (CELL)OldXREGS; + if (LOCAL_ErrorMessage) return -1; if (get_heap_info( PASS_REGS1 ) < 0) return -1; if (flag == DO_EVERYTHING) { ARG1 = get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; if (which_save == 2) { ARG2 = get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; } /* get old trail base */ - OldTrailBase = (ADDR)get_cellptr(); - if (Yap_ErrorMessage) + LOCAL_OldTrailBase = (ADDR)get_cellptr(); + if (LOCAL_ErrorMessage) return -1; /* Save the old register where we can easily access them */ - OldASP = ASP; - OldLCL0 = LCL0; - OldGlobalBase = (CELL *)Yap_GlobalBase; - OldH = H; - OldTR = TR; - GDiff = Unsigned(NewGlobalBase) - Unsigned(Yap_GlobalBase); - GDiff0 = 0; - LDiff = Unsigned(NewLCL0) - Unsigned(LCL0); - TrDiff = LDiff; - Yap_GlobalBase = (ADDR)NewGlobalBase; + LOCAL_OldASP = ASP; + LOCAL_OldLCL0 = LCL0; + LOCAL_OldGlobalBase = (CELL *)LOCAL_GlobalBase; + LOCAL_OldH = H; + LOCAL_OldTR = TR; + LOCAL_GDiff = Unsigned(NewGlobalBase) - Unsigned(LOCAL_GlobalBase); + LOCAL_GDiff0 = 0; + LOCAL_LDiff = Unsigned(NewLCL0) - Unsigned(LCL0); + LOCAL_TrDiff = LOCAL_LDiff; + LOCAL_GlobalBase = (ADDR)NewGlobalBase; LCL0 = NewLCL0; } return 1; @@ -949,7 +949,7 @@ get_hash(void) static int CopyCode( USES_REGS1 ) { - if (myread(splfild, (char *) Yap_HeapBase, (Unsigned(OldHeapTop) - Unsigned(OldHeapBase))) < 0) { + if (myread(splfild, (char *) Yap_HeapBase, (Unsigned(LOCAL_OldHeapTop) - Unsigned(LOCAL_OldHeapBase))) < 0) { return -1; } return 1; @@ -963,15 +963,15 @@ CopyStacks( USES_REGS1 ) Int j; char *NewASP; - j = Unsigned(OldLCL0) - Unsigned(ASP); - NewASP = (char *) (Unsigned(ASP) + (Unsigned(LCL0) - Unsigned(OldLCL0))); + j = Unsigned(LOCAL_OldLCL0) - Unsigned(ASP); + NewASP = (char *) (Unsigned(ASP) + (Unsigned(LCL0) - Unsigned(LOCAL_OldLCL0))); if (myread(splfild, (char *) NewASP, j) < 0) return -1; - j = Unsigned(H) - Unsigned(OldGlobalBase); - if (myread(splfild, (char *) Yap_GlobalBase, j) < 0) + j = Unsigned(H) - Unsigned(LOCAL_OldGlobalBase); + if (myread(splfild, (char *) LOCAL_GlobalBase, j) < 0) return -1; - j = Unsigned(TR) - Unsigned(OldTrailBase); - if (myread(splfild, Yap_TrailBase, j)) + j = Unsigned(TR) - Unsigned(LOCAL_OldTrailBase); + if (myread(splfild, LOCAL_TrailBase, j)) return -1; return 1; } @@ -983,10 +983,10 @@ CopyTrailEntries( USES_REGS1 ) { CELL entry, *Entries; - Entries = (CELL *)Yap_TrailBase; + Entries = (CELL *)LOCAL_TrailBase; do { *Entries++ = entry = get_cell(); - if (Yap_ErrorMessage) + if (LOCAL_ErrorMessage) return -1; } while ((CODEADDR)entry != NULL); return 1; @@ -1020,7 +1020,7 @@ get_coded(int flag, OPCODE old_ops[] USES_REGS) if (myread(splfild, my_end_msg, 256) < 0) return -1; if (strcmp(end_msg,my_end_msg) != 0) { - Yap_ErrorMessage = "bad trailing CRC in saved state"; + LOCAL_ErrorMessage = "bad trailing CRC in saved state"; return -1; } return 1; @@ -1035,7 +1035,7 @@ restore_heap_regs( USES_REGS1 ) *((YAP_SEG_SIZE *) HeapTop) = InUseFlag; } HeapMax = Yap_heap_regs->heap_used = OldHeapUsed; - HeapLim = Yap_GlobalBase; + HeapLim = LOCAL_GlobalBase; } /* adjust abstract machine registers */ @@ -1061,7 +1061,7 @@ restore_regs(int flag USES_REGS) EX = DBTermAdjust(EX); RestoreDBTerm(EX, TRUE PASS_REGS); } - WokenGoals = AbsAppl(PtoGloAdjust(RepAppl(WokenGoals))); + LOCAL_WokenGoals = AbsAppl(PtoGloAdjust(RepAppl(LOCAL_WokenGoals))); } } @@ -1137,13 +1137,13 @@ rehash(CELL *oldcode, int NOfE, int KindOfEntries USES_REGS) CELL WorkTerm, failplace = 0; CELL *Base = oldcode; - if (HDiff == 0) + if (LOCAL_HDiff == 0) return; basep = H; if (H + (NOfE*2) > ASP) { basep = (CELL *)TR; - if (basep + (NOfE*2) > (CELL *)Yap_TrailTop) { - if (!Yap_growtrail((ADDR)(basep + (NOfE*2))-Yap_TrailTop, TRUE)) { + if (basep + (NOfE*2) > (CELL *)LOCAL_TrailTop) { + if (!Yap_growtrail((ADDR)(basep + (NOfE*2))-LOCAL_TrailTop, TRUE)) { Yap_Error(OUT_OF_TRAIL_ERROR, TermNil, "not enough space to restore hash tables for indexing"); Yap_exit(1); @@ -1216,7 +1216,7 @@ RestoreFreeSpace( USES_REGS1 ) Yap_av = (struct malloc_state *)AddrAdjust((ADDR)Yap_av); Yap_RestoreDLMalloc(); if (AuxSp != NULL) { - if (AuxBase < OldHeapBase || AuxBase > OldHeapTop) { + if (AuxBase < LOCAL_OldHeapBase || AuxBase > LOCAL_OldHeapTop) { AuxSp = NULL; AuxBase = NULL; AuxTop = NULL; @@ -1224,7 +1224,7 @@ RestoreFreeSpace( USES_REGS1 ) AuxSp = PtoHeapCellAdjust(AuxSp); AuxBase = AddrAdjust(AuxBase); AuxTop = AddrAdjust(AuxTop); - ScratchPad.ptr = AddrAdjust(ScratchPad.ptr); + LOCAL_ScratchPad.ptr = AddrAdjust(LOCAL_ScratchPad.ptr); } } #else @@ -1337,7 +1337,7 @@ ShowEntries(pp) PropEntry *pp; { while (!EndOfPAEntr(pp)) { - fprintf(Yap_stderr,"Estou a ver a prop %x em %x\n", pp->KindOfPE, pp); + fprintf(GLOBAL_stderr,"Estou a ver a prop %x em %x\n", pp->KindOfPE, pp); pp = RepProp(pp->NextOfPE); } } @@ -1352,7 +1352,7 @@ ShowAtoms() AtomEntry *at; at = RepAtom(HashPtr->Entry); do { - fprintf(Yap_stderr,"Passei ao %s em %x\n", at->StrOfAE, at); + fprintf(GLOBAL_stderr,"Passei ao %s em %x\n", at->StrOfAE, at); ShowEntries(RepProp(at->PropsOfAE)); } while (!EndOfPAEntr(at = RepAtom(at->NextOfAE))); } @@ -1364,7 +1364,7 @@ ShowAtoms() AtomEntry *at; at = RepAtom(HashPtr->Entry); do { - fprintf(Yap_stderr,"Passei ao %s em %x\n", at->StrOfAE, at); + fprintf(GLOBAL_stderr,"Passei ao %s em %x\n", at->StrOfAE, at); ShowEntries(RepProp(at->PropsOfAE)); } while (!EndOfPAEntr(at = RepAtom(at->NextOfAE))); } @@ -1383,12 +1383,12 @@ commit_to_saved_state(char *s, CELL *Astate, CELL *ATrail, CELL *AStack, CELL *A if ((mode = check_header(Astate,ATrail,AStack,AHeap PASS_REGS)) == FAIL_RESTORE) return(FAIL_RESTORE); - Yap_PrologMode = BootMode; + LOCAL_PrologMode = BootMode; if (Yap_HeapBase) { extern void Scleanup(void); if (!yap_flags[HALT_AFTER_CONSULT_FLAG] && !yap_flags[QUIET_MODE_FLAG]) { - Yap_TrueFileName(s,Yap_FileNameBuf2, YAP_FILENAME_MAX); - fprintf(stderr, "%% Restoring file %s\n", Yap_FileNameBuf2); + Yap_TrueFileName(s,LOCAL_FileNameBuf2, YAP_FILENAME_MAX); + fprintf(stderr, "%% Restoring file %s\n", LOCAL_FileNameBuf2); } Scleanup(); Yap_CloseStreams(TRUE); @@ -1397,7 +1397,7 @@ commit_to_saved_state(char *s, CELL *Astate, CELL *ATrail, CELL *AStack, CELL *A /* * This should be another file, like the log file */ - errout = Yap_stderr; + errout = GLOBAL_stderr; #endif return mode; } @@ -1425,7 +1425,7 @@ static int try_open(char *inpf, CELL *Astate, CELL *ATrail, CELL *AStack, CELL * strncpy(buf, inpf, YAP_FILENAME_MAX); if ((mode = commit_to_saved_state(inpf,Astate,ATrail,AStack,AHeap)) != FAIL_RESTORE) { CACHE_REGS - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; return mode; } return mode; @@ -1437,8 +1437,7 @@ OpenRestore(char *inpf, char *YapLibDir, CELL *Astate, CELL *ATrail, CELL *AStac CACHE_REGS int mode = FAIL_RESTORE; char save_buffer[YAP_FILENAME_MAX+1]; - - // Yap_ErrorMessage = NULL; + // LOCAL_ErrorMessage = NULL; if (inpf == NULL) { #if _MSC_VER || defined(__MINGW32__) if (!(inpf = Yap_RegistryGetString("startup"))) @@ -1449,18 +1448,18 @@ OpenRestore(char *inpf, char *YapLibDir, CELL *Astate, CELL *ATrail, CELL *AStac if (inpf[0] != '/') { #if __simplescalar__ /* does not implement getcwd */ - strncpy(Yap_FileNameBuf,yap_pwd,YAP_FILENAME_MAX); + strncpy(LOCAL_FileNameBuf,GLOBAL_pwd,YAP_FILENAME_MAX); #elif HAVE_GETCWD - if (getcwd (Yap_FileNameBuf, YAP_FILENAME_MAX) == NULL) - Yap_FileNameBuf[0] = '\0'; + if (getcwd (LOCAL_FileNameBuf, YAP_FILENAME_MAX) == NULL) + LOCAL_FileNameBuf[0] = '\0'; #else - if (getwd (Yap_FileNameBuf) == NULL) - Yap_FileNameBuf[0] = '\0'; + if (getwd (LOCAL_FileNameBuf) == NULL) + LOCAL_FileNameBuf[0] = '\0'; #endif - strncat(Yap_FileNameBuf, "/", YAP_FILENAME_MAX-1); - strncat(Yap_FileNameBuf, inpf, YAP_FILENAME_MAX-1); + strncat(LOCAL_FileNameBuf, "/", YAP_FILENAME_MAX-1); + strncat(LOCAL_FileNameBuf, inpf, YAP_FILENAME_MAX-1); } else { - strncat(Yap_FileNameBuf, inpf, YAP_FILENAME_MAX-1); + strncat(LOCAL_FileNameBuf, inpf, YAP_FILENAME_MAX-1); } if (inpf != NULL && (splfild = open_file(inpf, O_RDONLY)) > 0) { if ((mode = try_open(inpf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { @@ -1473,12 +1472,12 @@ OpenRestore(char *inpf, char *YapLibDir, CELL *Astate, CELL *ATrail, CELL *AStac using YAPLIBDIR or friends. */ if (YapLibDir != NULL) { - cat_file_name(Yap_FileNameBuf, Yap_LibDir, inpf, YAP_FILENAME_MAX); - if ((mode = try_open(Yap_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { + cat_file_name(LOCAL_FileNameBuf, Yap_LibDir, inpf, YAP_FILENAME_MAX); + if ((mode = try_open(LOCAL_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { return mode; } } else { - if ((mode = try_open(Yap_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { + if ((mode = try_open(LOCAL_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { return mode; } } @@ -1486,17 +1485,17 @@ OpenRestore(char *inpf, char *YapLibDir, CELL *Astate, CELL *ATrail, CELL *AStac { char *yap_env = getenv("YAPLIBDIR"); if (yap_env != NULL) { - cat_file_name(Yap_FileNameBuf, yap_env, inpf, YAP_FILENAME_MAX); - if ((mode = try_open(Yap_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { + cat_file_name(LOCAL_FileNameBuf, yap_env, inpf, YAP_FILENAME_MAX); + if ((mode = try_open(LOCAL_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { return mode; } } } #endif if (YAP_LIBDIR != NULL) { - cat_file_name(Yap_FileNameBuf, YAP_LIBDIR, inpf, YAP_FILENAME_MAX); - if ((splfild = open_file(Yap_FileNameBuf, O_RDONLY)) > 0) { - if ((mode = try_open(Yap_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { + cat_file_name(LOCAL_FileNameBuf, YAP_LIBDIR, inpf, YAP_FILENAME_MAX); + if ((splfild = open_file(LOCAL_FileNameBuf, O_RDONLY)) > 0) { + if ((mode = try_open(LOCAL_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { return mode; } } @@ -1509,34 +1508,34 @@ OpenRestore(char *inpf, char *YapLibDir, CELL *Astate, CELL *ATrail, CELL *AStac char *pt; /* try to get it from current executable */ - if ((fatts = GetFileAttributes(Yap_FileNameBuf)) == 0xFFFFFFFFL || + if ((fatts = GetFileAttributes(LOCAL_FileNameBuf)) == 0xFFFFFFFFL || !(fatts & FILE_ATTRIBUTE_DIRECTORY)) { /* couldn't find it where it was supposed to be, let's try using the executable */ - if (!GetModuleFileNameEx( GetCurrentProcess(), NULL, Yap_FileNameBuf, YAP_FILENAME_MAX)) { + if (!GetModuleFileNameEx( GetCurrentProcess(), NULL, LOCAL_FileNameBuf, YAP_FILENAME_MAX)) { /* do nothing */ goto end; } - buflen = strlen(Yap_FileNameBuf); - pt = Yap_FileNameBuf+strlen(Yap_FileNameBuf); + buflen = strlen(LOCAL_FileNameBuf); + pt = LOCAL_FileNameBuf+strlen(LOCAL_FileNameBuf); while (*--pt != '\\') { /* skip executable */ - if (pt == Yap_FileNameBuf) { + if (pt == LOCAL_FileNameBuf) { /* do nothing */ goto end; } } while (*--pt != '\\') { /* skip parent directory "bin\\" */ - if (pt == Yap_FileNameBuf) { + if (pt == LOCAL_FileNameBuf) { goto end; } } /* now, this is a possible location for the ROOT_DIR, let's look for a share directory here */ pt[1] = '\0'; - strncat(Yap_FileNameBuf,"lib/Yap/startup.yss",YAP_FILENAME_MAX); + strncat(LOCAL_FileNameBuf,"lib/Yap/startup.yss",YAP_FILENAME_MAX); } - if ((mode = try_open(Yap_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { + if ((mode = try_open(LOCAL_FileNameBuf,Astate,ATrail,AStack,AHeap,save_buffer)) != FAIL_RESTORE) { return mode; } } @@ -1544,12 +1543,12 @@ OpenRestore(char *inpf, char *YapLibDir, CELL *Astate, CELL *ATrail, CELL *AStac #endif /* try to open from current directory */ /* could not open file */ - if (Yap_ErrorMessage == NULL) { + if (LOCAL_ErrorMessage == NULL) { if (save_buffer[0]) { - strncpy(Yap_FileNameBuf, save_buffer, YAP_FILENAME_MAX-1); + strncpy(LOCAL_FileNameBuf, save_buffer, YAP_FILENAME_MAX-1); do_system_error(PERMISSION_ERROR_OPEN_SOURCE_SINK,"incorrect saved state"); } else { - strncpy(Yap_FileNameBuf, inpf, YAP_FILENAME_MAX-1); + strncpy(LOCAL_FileNameBuf, inpf, YAP_FILENAME_MAX-1); do_system_error(PERMISSION_ERROR_OPEN_SOURCE_SINK,"could not open saved state"); } } @@ -1559,11 +1558,12 @@ OpenRestore(char *inpf, char *YapLibDir, CELL *Astate, CELL *ATrail, CELL *AStac static void CloseRestore(void) { + CACHE_REGS #ifdef DEBUG_RESTORE3 ShowAtoms(); #endif close_file(); - Yap_PrologMode = UserMode; + LOCAL_PrologMode = UserMode; } #if !defined(_WIN32) @@ -1590,8 +1590,8 @@ check_opcodes(OPCODE old_ops[]) static void RestoreHeap(OPCODE old_ops[] USES_REGS) { - int heap_moved = (OldHeapBase != Yap_HeapBase || - XDiff), opcodes_moved; + int heap_moved = (LOCAL_OldHeapBase != Yap_HeapBase || + LOCAL_XDiff), opcodes_moved; Term mod = CurrentModule; CurrentModule = PROLOG_MODULE; @@ -1660,7 +1660,7 @@ UnmarkTrEntries( USES_REGS1 ) B = (choiceptr)LCL0; B--; B->cp_ap = NOCODE; - Entries = (CELL *)Yap_TrailBase; + Entries = (CELL *)LOCAL_TrailBase; while ((entry = *Entries++) != (CELL)NULL) { if (!IsVarTerm(entry)) { if(IsPairTerm(entry)) { @@ -1740,10 +1740,10 @@ Restore(char *s, char *lib_dir USES_REGS) RestoreHeap(old_ops PASS_REGS); switch(restore_mode) { case DO_EVERYTHING: - if (OldHeapBase != Yap_HeapBase || - OldLCL0 != LCL0 || - OldGlobalBase != (CELL *)Yap_GlobalBase || - OldTrailBase != Yap_TrailBase) { + if (LOCAL_OldHeapBase != Yap_HeapBase || + LOCAL_OldLCL0 != LCL0 || + LOCAL_OldGlobalBase != (CELL *)LOCAL_GlobalBase || + LOCAL_OldTrailBase != LOCAL_TrailBase) { Yap_AdjustStacksAndTrail(); if (which_save == 2) { Yap_AdjustRegs(2); @@ -1796,13 +1796,13 @@ p_restore( USES_REGS1 ) Term t1 = Deref(ARG1); #ifdef YAPOR - if (Yap_number_workers != 1) { + if (GLOBAL_number_workers != 1) { Yap_Error(SYSTEM_ERROR,TermNil,"cannot perform save: more than a worker/thread running"); return(FALSE); } #endif /* YAPOR */ #ifdef THREADS - if (Yap_NOfThreads != 1) { + if (GLOBAL_NOfThreads != 1) { Yap_Error(SYSTEM_ERROR,TermNil,"cannot perform save: more than a worker/thread running"); return(FALSE); } @@ -1816,7 +1816,7 @@ p_restore( USES_REGS1 ) restore_absmi_regs(&Yap_standard_regs); #endif /* back to the top level we go */ - siglongjmp(Yap_RestartEnv,3); + siglongjmp(LOCAL_RestartEnv,3); } return(mode != FAIL_RESTORE); } diff --git a/C/scanner.c b/C/scanner.c index 77cb8d6eb..240af48e2 100755 --- a/C/scanner.c +++ b/C/scanner.c @@ -173,18 +173,18 @@ AllocScannerMemory(unsigned int size) CACHE_REGS char *AuxSpScan; - AuxSpScan = ScannerStack; + AuxSpScan = LOCAL_ScannerStack; size = AdjustSize(size); - if (ScannerExtraBlocks) { + if (LOCAL_ScannerExtraBlocks) { struct scanner_extra_alloc *ptr; if (!(ptr = (struct scanner_extra_alloc *)malloc(size+sizeof(ScannerExtraBlock)))) { return NULL; } - ptr->next = ScannerExtraBlocks; - ScannerExtraBlocks = ptr; + ptr->next = LOCAL_ScannerExtraBlocks; + LOCAL_ScannerExtraBlocks = ptr; return (char *)(ptr+1); - } else if (Yap_TrailTop <= AuxSpScan+size) { + } else if (LOCAL_TrailTop <= AuxSpScan+size) { UInt alloc_size = sizeof(CELL) * K16; if (size > alloc_size) @@ -195,12 +195,12 @@ AllocScannerMemory(unsigned int size) if (!(ptr = (struct scanner_extra_alloc *)malloc(size+sizeof(ScannerExtraBlock)))) { return NULL; } - ptr->next = ScannerExtraBlocks; - ScannerExtraBlocks = ptr; + ptr->next = LOCAL_ScannerExtraBlocks; + LOCAL_ScannerExtraBlocks = ptr; return (char *)(ptr+1); } } - ScannerStack = AuxSpScan+size; + LOCAL_ScannerStack = AuxSpScan+size; return AuxSpScan; } @@ -208,12 +208,12 @@ static void PopScannerMemory(char *block, unsigned int size) { CACHE_REGS - if (block == ScannerStack-size) { - ScannerStack -= size; - } else if (block == (char *)(ScannerExtraBlocks+1)) { - struct scanner_extra_alloc *ptr = ScannerExtraBlocks; + if (block == LOCAL_ScannerStack-size) { + LOCAL_ScannerStack -= size; + } else if (block == (char *)(LOCAL_ScannerExtraBlocks+1)) { + struct scanner_extra_alloc *ptr = LOCAL_ScannerExtraBlocks; - ScannerExtraBlocks = ptr->next; + LOCAL_ScannerExtraBlocks = ptr->next; free(ptr); } } @@ -235,7 +235,7 @@ float_send(char *s, int sign) if (yap_flags[LANGUAGE_MODE_FLAG] == 1) { /* iso */ if (!finite(f)) { CACHE_REGS - Yap_ErrorMessage = "Float overflow while scanning"; + LOCAL_ErrorMessage = "Float overflow while scanning"; return(MkEvalFl(0.0)); } } @@ -268,7 +268,7 @@ static int send_error_message(char s[]) { CACHE_REGS - Yap_ErrorMessage = s; + LOCAL_ErrorMessage = s; return 0; } @@ -502,7 +502,7 @@ static int num_send_error_message(char s[]) { CACHE_REGS - Yap_ErrorMessage = s; + LOCAL_ErrorMessage = s; return TermNil; } @@ -727,12 +727,12 @@ Yap_scan_num(IOSTREAM *inp) int ch, cherr; char *ptr; - Yap_ErrorMessage = NULL; - ScannerStack = (char *)TR; - ScannerExtraBlocks = NULL; + LOCAL_ErrorMessage = NULL; + LOCAL_ScannerStack = (char *)TR; + LOCAL_ScannerExtraBlocks = NULL; if (!(ptr = AllocScannerMemory(4096))) { - Yap_ErrorMessage = "Trail Overflow"; - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_ErrorMessage = "Trail Overflow"; + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; return TermNil; } ch = getchr(inp); @@ -755,7 +755,7 @@ Yap_scan_num(IOSTREAM *inp) out = get_num(&ch, &cherr, inp, ptr, 4096, sign); /* */ PopScannerMemory(ptr, 4096); Yap_clean_tokenizer(NULL, NULL, NULL); - if (Yap_ErrorMessage != NULL || ch != -1 || cherr) + if (LOCAL_ErrorMessage != NULL || ch != -1 || cherr) return TermNil; return out; } @@ -769,8 +769,8 @@ ch_to_wide(char *base, char *charp) wchar_t *nb = (wchar_t *)base; if ((nb+n) + 1024 > (wchar_t *)AuxSp) { - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; - Yap_ErrorMessage = "Heap Overflow While Scanning: please increase code space (-h)"; + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_ErrorMessage = "Heap Overflow While Scanning: please increase code space (-h)"; return NULL; } for (i=n; i > 0; i--) { @@ -800,13 +800,12 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) int ch; wchar_t *wcharp; - Yap_ErrorMessage = NULL; - Yap_Error_Size = 0; - Yap_VarTable = NULL; - Yap_AnonVarTable = NULL; - Yap_eot_before_eof = FALSE; - ScannerStack = (char *)TR; - ScannerExtraBlocks = NULL; + LOCAL_ErrorMessage = NULL; + LOCAL_Error_Size = 0; + LOCAL_VarTable = NULL; + LOCAL_AnonVarTable = NULL; + LOCAL_ScannerStack = (char *)TR; + LOCAL_ScannerExtraBlocks = NULL; l = NULL; p = NULL; /* Just to make lint happy */ ch = getchr(inp_stream); @@ -814,7 +813,7 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) ch = getchr(inp_stream); } *tposp = Yap_StreamPosition(inp_stream); - StartLine = inp_stream->posbuf.lineno; + LOCAL_StartLine = inp_stream->posbuf.lineno; do { wchar_t och; int quote, isvar; @@ -826,8 +825,8 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) t = (TokEntry *) AllocScannerMemory(sizeof(TokEntry)); t->TokNext = NULL; if (t == NULL) { - Yap_ErrorMessage = "Trail Overflow"; - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_ErrorMessage = "Trail Overflow"; + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; if (p) p->Tok = Ord(kind = eot_tok); /* serious error now */ @@ -855,6 +854,15 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) while (chtype(ch) == BS) { ch = getchr(inp_stream); } + if (ASP-H < 1024) { + LOCAL_ErrorMessage = "Stack Overflow"; + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Size = 0L; + if (p) + p->Tok = Ord(kind = eot_tok); + /* serious error now */ + return l; + } *tposp = Yap_StreamPosition(inp_stream); } goto restart; @@ -878,8 +886,8 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) if (charp == (char *)AuxSp-1024) { huge_var_error: /* huge atom or variable, we are in trouble */ - Yap_ErrorMessage = "Code Space Overflow due to huge atom"; - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_ErrorMessage = "Code Space Overflow due to huge atom"; + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; Yap_ReleasePreAllocCodeSpace((CODEADDR)TokImage); if (p) p->Tok = Ord(kind = eot_tok); @@ -905,8 +913,8 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) ae = Yap_LookupAtom(TokImage); } if (ae == NIL) { - Yap_Error_TYPE = OUT_OF_HEAP_ERROR; - Yap_ErrorMessage = "Code Space Overflow"; + LOCAL_Error_TYPE = OUT_OF_HEAP_ERROR; + LOCAL_ErrorMessage = "Code Space Overflow"; if (p) t->Tok = Ord(kind = eot_tok); /* serious error now */ @@ -932,17 +940,17 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) cherr = 0; if (!(ptr = AllocScannerMemory(4096))) { - Yap_ErrorMessage = "Trail Overflow"; - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_ErrorMessage = "Trail Overflow"; + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; if (p) t->Tok = Ord(kind = eot_tok); /* serious error now */ return l; } if (ASP-H < 1024) { - Yap_ErrorMessage = "Stack Overflow"; - Yap_Error_TYPE = OUT_OF_STACK_ERROR; - Yap_Error_Size = 0L; + LOCAL_ErrorMessage = "Stack Overflow"; + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Size = 0L; if (p) p->Tok = Ord(kind = eot_tok); /* serious error now */ @@ -962,8 +970,8 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) t->TokPos = GetCurInpPos(inp_stream); e = (TokEntry *) AllocScannerMemory(sizeof(TokEntry)); if (e == NULL) { - Yap_ErrorMessage = "Trail Overflow"; - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_ErrorMessage = "Trail Overflow"; + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; if (p) p->Tok = Ord(kind = eot_tok); /* serious error now */ @@ -991,8 +999,8 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) t->TokPos = GetCurInpPos(inp_stream); e2 = (TokEntry *) AllocScannerMemory(sizeof(TokEntry)); if (e2 == NULL) { - Yap_ErrorMessage = "Trail Overflow"; - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_ErrorMessage = "Trail Overflow"; + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; if (p) p->Tok = Ord(kind = eot_tok); /* serious error now */ @@ -1022,8 +1030,8 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) t->TokPos = GetCurInpPos(inp_stream); e2 = (TokEntry *) AllocScannerMemory(sizeof(TokEntry)); if (e2 == NULL) { - Yap_ErrorMessage = "Trail Overflow"; - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_ErrorMessage = "Trail Overflow"; + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; t->Tok = Ord(kind = eot_tok); /* serious error now */ return l; @@ -1055,13 +1063,13 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) while (TRUE) { if (charp + 1024 > (char *)AuxSp) { - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; - Yap_ErrorMessage = "Heap Overflow While Scanning: please increase code space (-h)"; + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_ErrorMessage = "Heap Overflow While Scanning: please increase code space (-h)"; break; } if (ch == 10 && yap_flags[CHARACTER_ESCAPE_FLAG] == ISO_CHARACTER_ESCAPES) { /* in ISO a new line terminates a string */ - Yap_ErrorMessage = "layout character \n inside quotes"; + LOCAL_ErrorMessage = "layout character \n inside quotes"; break; } if (ch == quote) { @@ -1088,8 +1096,8 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) ++len; if (charp > (char *)AuxSp - 1024) { /* Not enough space to read in the string. */ - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; - Yap_ErrorMessage = "not enough space to read in string or quoted atom"; + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_ErrorMessage = "not enough space to read in string or quoted atom"; /* serious error now */ Yap_ReleasePreAllocCodeSpace((CODEADDR)TokImage); t->Tok = Ord(kind = eot_tok); @@ -1108,7 +1116,7 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) mp = AllocScannerMemory(len + 1); } if (mp == NULL) { - Yap_ErrorMessage = "not enough heap space to read in string or quoted atom"; + LOCAL_ErrorMessage = "not enough heap space to read in string or quoted atom"; Yap_ReleasePreAllocCodeSpace((CODEADDR)TokImage); t->Tok = Ord(kind = eot_tok); return l; @@ -1131,8 +1139,8 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) t->TokInfo = Unsigned(Yap_LookupAtom(TokImage)); } if (!(t->TokInfo)) { - Yap_Error_TYPE = OUT_OF_HEAP_ERROR; - Yap_ErrorMessage = "Code Space Overflow"; + LOCAL_Error_TYPE = OUT_OF_HEAP_ERROR; + LOCAL_ErrorMessage = "Code Space Overflow"; if (p) t->Tok = Ord(kind = eot_tok); /* serious error now */ @@ -1162,6 +1170,15 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) while (chtype(ch) == BS) { ch = getchr(inp_stream); } + if (ASP-H < 1024) { + LOCAL_ErrorMessage = "Stack Overflow"; + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Size = 0L; + if (p) + p->Tok = Ord(kind = eot_tok); + /* serious error now */ + return l; + } *tposp = Yap_StreamPosition(inp_stream); } goto restart; @@ -1169,7 +1186,6 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) enter_symbol: if (och == '.' && (chtype(ch) == BS || chtype(ch) == EF || chtype(ch) == CC)) { - Yap_eot_before_eof = TRUE; if (chtype(ch) == CC) while ((ch = getchr(inp_stream)) != 10 && chtype(ch) != EF); t->Tok = Ord(kind = eot_tok); @@ -1183,8 +1199,8 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) *charp = '\0'; t->TokInfo = Unsigned(Yap_LookupAtom(TokImage)); if (t->TokInfo == (CELL)NIL) { - Yap_Error_TYPE = OUT_OF_HEAP_ERROR; - Yap_ErrorMessage = "Code Space Overflow"; + LOCAL_Error_TYPE = OUT_OF_HEAP_ERROR; + LOCAL_ErrorMessage = "Code Space Overflow"; if (p) t->Tok = Ord(kind = eot_tok); /* serious error now */ @@ -1247,29 +1263,29 @@ Yap_tokenizer(IOSTREAM *inp_stream, Term *tposp) default: #ifdef DEBUG - fprintf(Yap_stderr, "\n++++ token: wrong char type %c %d\n", ch, chtype(ch)); + fprintf(GLOBAL_stderr, "\n++++ token: wrong char type %c %d\n", ch, chtype(ch)); #endif t->Tok = Ord(kind = eot_tok); } #ifdef DEBUG - if(Yap_Option[2]) fprintf(Yap_stderr,"[Token %d %ld]",Ord(kind),(unsigned long int)t->TokInfo); + if(GLOBAL_Option[2]) fprintf(GLOBAL_stderr,"[Token %d %ld]",Ord(kind),(unsigned long int)t->TokInfo); #endif - if (Yap_ErrorMessage) { + if (LOCAL_ErrorMessage) { /* insert an error token to inform the system of what happened */ TokEntry *e = (TokEntry *) AllocScannerMemory(sizeof(TokEntry)); if (e == NULL) { - Yap_ErrorMessage = "Trail Overflow"; - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_ErrorMessage = "Trail Overflow"; + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; p->Tok = Ord(kind = eot_tok); /* serious error now */ return l; } p->TokNext = e; e->Tok = Error_tok; - e->TokInfo = MkAtomTerm(Yap_LookupAtom(Yap_ErrorMessage)); + e->TokInfo = MkAtomTerm(Yap_LookupAtom(LOCAL_ErrorMessage)); e->TokPos = GetCurInpPos(inp_stream); e->TokNext = NULL; - Yap_ErrorMessage = NULL; + LOCAL_ErrorMessage = NULL; p = e; } } while (kind != eot_tok); @@ -1280,7 +1296,7 @@ void Yap_clean_tokenizer(TokEntry *tokstart, VarEntry *vartable, VarEntry *anonvartable) { CACHE_REGS - struct scanner_extra_alloc *ptr = ScannerExtraBlocks; + struct scanner_extra_alloc *ptr = LOCAL_ScannerExtraBlocks; while (ptr) { struct scanner_extra_alloc *next = ptr->next; free(ptr); diff --git a/C/sort.c b/C/sort.c index 8d5f18133..0f78c6fa5 100644 --- a/C/sort.c +++ b/C/sort.c @@ -59,7 +59,7 @@ build_new_list(CELL *pt, Term t USES_REGS) pt += 2; if (pt > ASP - 4096) { if (!Yap_gcl((ASP-H)*sizeof(CELL), 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return(FALSE); } t = Deref(ARG1); diff --git a/C/stdpreds.c b/C/stdpreds.c index f80d7059f..9937d4f9b 100755 --- a/C/stdpreds.c +++ b/C/stdpreds.c @@ -477,22 +477,22 @@ p_values( USES_REGS1 ) inline static void do_signal(yap_signals sig USES_REGS) { - LOCK(SignalLock); - if (!Yap_InterruptsDisabled) + LOCK(LOCAL_SignalLock); + if (!LOCAL_InterruptsDisabled) CreepFlag = Unsigned(LCL0); - ActiveSignals |= sig; - UNLOCK(SignalLock); + LOCAL_ActiveSignals |= sig; + UNLOCK(LOCAL_SignalLock); } inline static void undo_signal(yap_signals sig USES_REGS) { - LOCK(SignalLock); - if (ActiveSignals == sig) { + LOCK(LOCAL_SignalLock); + if (LOCAL_ActiveSignals == sig) { CreepFlag = CalculateStackGap(); } - ActiveSignals &= ~sig; - UNLOCK(SignalLock); + LOCAL_ActiveSignals &= ~sig; + UNLOCK(LOCAL_SignalLock); } @@ -518,24 +518,24 @@ p_signal_creep( USES_REGS1 ) at = AtomCreep; pred = RepPredProp(PredPropByFunc(Yap_MkFunctor(at, 1),0)); CreepCode = pred; - LOCK(SignalLock); - ActiveSignals |= YAP_CREEP_SIGNAL; - UNLOCK(SignalLock); + LOCK(LOCAL_SignalLock); + LOCAL_ActiveSignals |= YAP_CREEP_SIGNAL; + UNLOCK(LOCAL_SignalLock); return TRUE; } static Int p_disable_creep( USES_REGS1 ) { - LOCK(SignalLock); - if (ActiveSignals & YAP_CREEP_SIGNAL) { - ActiveSignals &= ~YAP_CREEP_SIGNAL; - if (!ActiveSignals) + LOCK(LOCAL_SignalLock); + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_CREEP_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return TRUE; } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return FALSE; } @@ -543,14 +543,14 @@ p_disable_creep( USES_REGS1 ) static Int p_disable_docreep( USES_REGS1 ) { - LOCK(SignalLock); - if (ActiveSignals & YAP_CREEP_SIGNAL) { - ActiveSignals &= ~YAP_CREEP_SIGNAL; - if (!ActiveSignals) + LOCK(LOCAL_SignalLock); + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_CREEP_SIGNAL; + if (!LOCAL_ActiveSignals) CreepFlag = CalculateStackGap(); - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); } else { - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); } return TRUE; } @@ -558,12 +558,12 @@ p_disable_docreep( USES_REGS1 ) static Int p_stop_creep( USES_REGS1 ) { - LOCK(SignalLock); - ActiveSignals &= ~YAP_CREEP_SIGNAL; - if (!ActiveSignals) { + LOCK(LOCAL_SignalLock); + LOCAL_ActiveSignals &= ~YAP_CREEP_SIGNAL; + if (!LOCAL_ActiveSignals) { CreepFlag = CalculateStackGap(); } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return TRUE; } @@ -797,9 +797,9 @@ p_runtime( USES_REGS1 ) now -= gc_time; ss_time = Yap_total_stack_shift_time(); now -= ss_time; - interval -= (gc_time-LastGcTime)+(ss_time-LastSSTime); - LastGcTime = gc_time; - LastSSTime = ss_time; + interval -= (gc_time-LOCAL_LastGcTime)+(ss_time-LOCAL_LastSSTime); + LOCAL_LastGcTime = gc_time; + LOCAL_LastSSTime = ss_time; tnow = MkIntegerTerm(now); tinterval = MkIntegerTerm(interval); return( Yap_unify_constant(ARG1, tnow) && @@ -904,8 +904,8 @@ ch_to_wide(char *base, char *charp USES_REGS) wchar_t *nb = (wchar_t *)base; if ((nb+n) + 1024 > (wchar_t *)AuxSp) { - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; - Yap_ErrorMessage = "Heap Overflow While Scanning: please increase code space (-h)"; + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_ErrorMessage = "Heap Overflow While Scanning: please increase code space (-h)"; return NULL; } for (i=n; i > 0; i--) { @@ -1241,7 +1241,7 @@ p_atom_chars( USES_REGS1 ) *ws++ = '\0'; while ((at = Yap_LookupWideAtom((wchar_t *)String)) == NIL) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1249,7 +1249,7 @@ p_atom_chars( USES_REGS1 ) *s++ = '\0'; while ((at = Yap_LookupAtom(String)) == NIL) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1313,7 +1313,7 @@ p_atom_concat( USES_REGS1 ) if (cptr+sz >= top-1024) { Yap_ReleasePreAllocCodeSpace((ADDR)cpt0); if (!Yap_growheap(FALSE, sz+1024, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } goto restart; @@ -1340,7 +1340,7 @@ p_atom_concat( USES_REGS1 ) cptr[0] = '\0'; while ((at = Yap_LookupWideAtom(cpt0)) == NIL) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1376,7 +1376,7 @@ p_atom_concat( USES_REGS1 ) if (cptr+sz >= top-1024) { Yap_ReleasePreAllocCodeSpace((ADDR)cpt0); if (!Yap_growheap(FALSE, sz+1024, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } goto restart; @@ -1396,7 +1396,7 @@ p_atom_concat( USES_REGS1 ) cptr[0] = '\0'; while ((at = Yap_LookupAtom(cpt0)) == NIL) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1460,7 +1460,7 @@ p_atomic_concat( USES_REGS1 ) if (wcptr+sz >= wtop-1024) { Yap_ReleasePreAllocCodeSpace((ADDR)cpt0); if (!Yap_growheap(FALSE, sz+1024, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } goto restart; @@ -1474,7 +1474,7 @@ p_atomic_concat( USES_REGS1 ) if (wcptr+sz >= wtop-1024) { Yap_ReleasePreAllocCodeSpace((ADDR)cpt0); if (!Yap_growheap(FALSE, sz+1024, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } goto restart; @@ -1517,7 +1517,7 @@ p_atomic_concat( USES_REGS1 ) if (!Yap_gmp_to_string(thead, tmp, (wtop-wcptr)-1024, 10 )) { Yap_ReleasePreAllocCodeSpace((ADDR)cpt0); if (!Yap_growheap(FALSE, sz+1024, NULL)) { - Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, LOCAL_ErrorMessage); return(FALSE); } goto restart; @@ -1541,7 +1541,7 @@ p_atomic_concat( USES_REGS1 ) wcptr[0] = '\0'; while ((at = Yap_LookupWideAtom(wcpt0)) == NIL) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1580,7 +1580,7 @@ p_atomic_concat( USES_REGS1 ) if (cptr+sz >= top-1024) { Yap_ReleasePreAllocCodeSpace((ADDR)cpt0); if (!Yap_growheap(FALSE, sz+1024, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return(FALSE); } goto restart; @@ -1607,7 +1607,7 @@ p_atomic_concat( USES_REGS1 ) size_t sz = Yap_gmp_to_size(thead, 10); Yap_ReleasePreAllocCodeSpace((ADDR)cpt0); if (!Yap_growheap(FALSE, sz+1024, NULL)) { - Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, LOCAL_ErrorMessage); return(FALSE); } goto restart; @@ -1628,7 +1628,7 @@ p_atomic_concat( USES_REGS1 ) cptr[0] = '\0'; while ((at = Yap_LookupAtom(cpt0)) == NIL) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -2001,7 +2001,7 @@ p_number_chars( USES_REGS1 ) size_t sz = Yap_gmp_to_size(t1, 10); Yap_ReleasePreAllocCodeSpace((ADDR)String); if (!Yap_ExpandPreAllocCodeSpace(sz, NULL, TRUE)) { - Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } goto restart_aux; @@ -2159,7 +2159,7 @@ p_number_atom( USES_REGS1 ) while (!Yap_gmp_to_string(t1, String, ((char *)AuxSp-String)-1024, 10 )) { size_t sz = Yap_gmp_to_size(t1, 10); if (!(String = Yap_ExpandPreAllocCodeSpace(sz, NULL, TRUE))) { - Yap_Error(OUT_OF_AUXSPACE_ERROR, t1, Yap_ErrorMessage); + Yap_Error(OUT_OF_AUXSPACE_ERROR, t1, LOCAL_ErrorMessage); return FALSE; } } @@ -2170,7 +2170,7 @@ p_number_atom( USES_REGS1 ) } while ((at = Yap_LookupAtom(String)) == NIL) { if (!Yap_growheap(FALSE, 0, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -2221,7 +2221,7 @@ p_number_codes( USES_REGS1 ) while (!Yap_gmp_to_string(t1, String, ((char *)AuxSp-String)-1024, 10 )) { size_t sz = Yap_gmp_to_size(t1, 10); if (!(String = Yap_ExpandPreAllocCodeSpace(sz, NULL, TRUE))) { - Yap_Error(OUT_OF_AUXSPACE_ERROR, t1, Yap_ErrorMessage); + Yap_Error(OUT_OF_AUXSPACE_ERROR, t1, LOCAL_ErrorMessage); return FALSE; } } @@ -2318,7 +2318,7 @@ p_atom_number( USES_REGS1 ) while (!Yap_gmp_to_string(t2, String, ((char *)AuxSp-String)-1024, 10 )) { size_t sz = Yap_gmp_to_size(t2, 10); if (!(String = Yap_ExpandPreAllocCodeSpace(sz, NULL, TRUE))) { - Yap_Error(OUT_OF_AUXSPACE_ERROR, t2, Yap_ErrorMessage); + Yap_Error(OUT_OF_AUXSPACE_ERROR, t2, LOCAL_ErrorMessage); return FALSE; } } @@ -2415,7 +2415,7 @@ p_univ( USES_REGS1 ) /* restore space */ H = Ar; if (!Yap_gcl((ASP-H)*sizeof(CELL), 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } twork = TailOfTerm(Deref(ARG2)); @@ -2480,7 +2480,7 @@ p_univ( USES_REGS1 ) twork = Yap_ArrayToList(CellPtr(TR), argno - 1); while (IsIntTerm(twork)) { if (!Yap_gc(2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return(FALSE); } twork = Yap_ArrayToList(CellPtr(TR), argno - 1); @@ -2490,7 +2490,7 @@ p_univ( USES_REGS1 ) { while (H+arity*2 > ASP-1024) { if (!Yap_gcl((arity*2)*sizeof(CELL), 2, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return(FALSE); } tin = Deref(ARG1); @@ -3135,7 +3135,7 @@ p_debug( USES_REGS1 ) int i = IntOfTerm(Deref(ARG1)); if (i >= 'a' && i <= 'z') - Yap_Option[i - 96] = !Yap_Option[i - 96]; + GLOBAL_Option[i - 96] = !GLOBAL_Option[i - 96]; return (1); } #endif @@ -3329,21 +3329,21 @@ Yap_show_statistics(void) #endif frag = (100.0*(heap_space_taken-HeapUsed))/heap_space_taken; - fprintf(Yap_stderr, "Code Space: %ld (%ld bytes needed, %ld bytes used, fragmentation %.3f%%).\n", + fprintf(GLOBAL_stderr, "Code Space: %ld (%ld bytes needed, %ld bytes used, fragmentation %.3f%%).\n", (unsigned long int)(Unsigned (H0) - Unsigned (Yap_HeapBase)), (unsigned long int)(Unsigned(HeapTop)-Unsigned(Yap_HeapBase)), (unsigned long int)(HeapUsed), frag); - fprintf(Yap_stderr, "Stack Space: %ld (%ld for Global, %ld for local).\n", + fprintf(GLOBAL_stderr, "Stack Space: %ld (%ld for Global, %ld for local).\n", (unsigned long int)(sizeof(CELL)*(LCL0-H0)), (unsigned long int)(sizeof(CELL)*(H-H0)), (unsigned long int)(sizeof(CELL)*(LCL0-ASP))); - fprintf(Yap_stderr, "Trail Space: %ld (%ld used).\n", - (unsigned long int)(sizeof(tr_fr_ptr)*(Unsigned(Yap_TrailTop)-Unsigned(Yap_TrailBase))), - (unsigned long int)(sizeof(tr_fr_ptr)*(Unsigned(TR)-Unsigned(Yap_TrailBase)))); - fprintf(Yap_stderr, "Runtime: %lds.\n", (unsigned long int)(runtime ( PASS_REGS1 ))); - fprintf(Yap_stderr, "Cputime: %lds.\n", (unsigned long int)(Yap_cputime ())); - fprintf(Yap_stderr, "Walltime: %lds.\n", (unsigned long int)(Yap_walltime ())); + fprintf(GLOBAL_stderr, "Trail Space: %ld (%ld used).\n", + (unsigned long int)(sizeof(tr_fr_ptr)*(Unsigned(LOCAL_TrailTop)-Unsigned(LOCAL_TrailBase))), + (unsigned long int)(sizeof(tr_fr_ptr)*(Unsigned(TR)-Unsigned(LOCAL_TrailBase)))); + fprintf(GLOBAL_stderr, "Runtime: %lds.\n", (unsigned long int)(runtime ( PASS_REGS1 ))); + fprintf(GLOBAL_stderr, "Cputime: %lds.\n", (unsigned long int)(Yap_cputime ())); + fprintf(GLOBAL_stderr, "Walltime: %lds.\n", (unsigned long int)(Yap_walltime ())); } static Int @@ -3366,12 +3366,12 @@ TrailMax(void) { CACHE_REGS Int i; - Int TrWidth = Unsigned(Yap_TrailTop) - Unsigned(Yap_TrailBase); + Int TrWidth = Unsigned(LOCAL_TrailTop) - Unsigned(LOCAL_TrailBase); CELL *pt; if (TrailTide != TrWidth) { pt = (CELL *)TR; - while (pt+2 < (CELL *)Yap_TrailTop) { + while (pt+2 < (CELL *)LOCAL_TrailTop) { if (pt[0] == 0 && pt[1] == 0 && pt[2] == 0) @@ -3379,8 +3379,8 @@ TrailMax(void) else pt++; } - if (pt+2 < (CELL *)Yap_TrailTop) - i = Unsigned(pt) - Unsigned(Yap_TrailBase); + if (pt+2 < (CELL *)LOCAL_TrailTop) + i = Unsigned(pt) - Unsigned(LOCAL_TrailBase); else i = TrWidth; } else @@ -3495,12 +3495,12 @@ p_statistics_heap_info( USES_REGS1 ) #if USE_SYSTEM_MALLOC && HAVE_MALLINFO struct mallinfo mi = mallinfo(); - UInt sstack = Yap_HoleSize+(Yap_TrailTop-Yap_GlobalBase); + UInt sstack = Yap_HoleSize+(LOCAL_TrailTop-LOCAL_GlobalBase); UInt mmax = (mi.arena+mi.hblkhd); Term tmax = MkIntegerTerm(mmax-sstack); tusage = MkIntegerTerm(mmax-(mi.fordblks+sstack)); #else - Term tmax = MkIntegerTerm((Yap_GlobalBase - Yap_HeapBase)-Yap_HoleSize); + Term tmax = MkIntegerTerm((LOCAL_GlobalBase - Yap_HeapBase)-Yap_HoleSize); #endif return(Yap_unify(tmax, ARG1) && Yap_unify(tusage,ARG2)); @@ -3524,8 +3524,8 @@ p_statistics_stacks_info( USES_REGS1 ) static Int p_statistics_trail_info( USES_REGS1 ) { - Term tmax = MkIntegerTerm(Unsigned(Yap_TrailTop) - Unsigned(Yap_TrailBase)); - Term tusage = MkIntegerTerm(Unsigned(TR) - Unsigned(Yap_TrailBase)); + Term tmax = MkIntegerTerm(Unsigned(LOCAL_TrailTop) - Unsigned(LOCAL_TrailBase)); + Term tusage = MkIntegerTerm(Unsigned(TR) - Unsigned(LOCAL_TrailBase)); return(Yap_unify(tmax, ARG1) && Yap_unify(tusage,ARG2)); @@ -3623,8 +3623,8 @@ mk_argc_list( USES_REGS1 ) { int i =0; Term t = TermNil; - while (i < Yap_argc) { - char *arg = Yap_argv[i]; + while (i < GLOBAL_argc) { + char *arg = GLOBAL_argv[i]; /* check for -L -- */ if (arg[0] == '-' && arg[1] == 'L') { arg += 2; @@ -3633,15 +3633,15 @@ mk_argc_list( USES_REGS1 ) if (*arg == '-' && arg[1] == '-' && arg[2] == '\0') { /* we found the separator */ int j; - for (j = Yap_argc-1; j > i+1; --j) { - t = MkPairTerm(MkAtomTerm(Yap_LookupAtom(Yap_argv[j])),t); + for (j = GLOBAL_argc-1; j > i+1; --j) { + t = MkPairTerm(MkAtomTerm(Yap_LookupAtom(GLOBAL_argv[j])),t); } return t; - } else if (Yap_argv[i+1] && Yap_argv[i+1][0] == '-' && Yap_argv[i+1][1] == '-' && Yap_argv[i+1][2] == '\0') { + } else if (GLOBAL_argv[i+1] && GLOBAL_argv[i+1][0] == '-' && GLOBAL_argv[i+1][1] == '-' && GLOBAL_argv[i+1][2] == '\0') { /* we found the separator */ int j; - for (j = Yap_argc-1; j > i+2; --j) { - t = MkPairTerm(MkAtomTerm(Yap_LookupAtom(Yap_argv[j])),t); + for (j = GLOBAL_argc-1; j > i+2; --j) { + t = MkPairTerm(MkAtomTerm(Yap_LookupAtom(GLOBAL_argv[j])),t); } return t; } @@ -3649,8 +3649,8 @@ mk_argc_list( USES_REGS1 ) if (arg[0] == '-' && arg[1] == '-' && arg[2] == '\0') { /* we found the separator */ int j; - for (j = Yap_argc-1; j > i; --j) { - t = MkPairTerm(MkAtomTerm(Yap_LookupAtom(Yap_argv[j])),t); + for (j = GLOBAL_argc-1; j > i; --j) { + t = MkPairTerm(MkAtomTerm(Yap_LookupAtom(GLOBAL_argv[j])),t); } return(t); } @@ -3670,8 +3670,8 @@ static Int p_executable( USES_REGS1 ) { - Yap_TrueFileName (Yap_argv[0], Yap_FileNameBuf, FALSE); - return Yap_unify(MkAtomTerm(Yap_LookupAtom(Yap_FileNameBuf)),ARG1); + Yap_TrueFileName (GLOBAL_argv[0], LOCAL_FileNameBuf, FALSE); + return Yap_unify(MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf)),ARG1); } static Int @@ -3832,49 +3832,49 @@ p_set_yap_flags( USES_REGS1 ) #ifdef TABLING case TABLING_MODE_FLAG: if (value == 0) { /* default */ - tab_ent_ptr tab_ent = Yap_root_tab_ent; + tab_ent_ptr tab_ent = GLOBAL_root_tab_ent; while(tab_ent) { TabEnt_mode(tab_ent) = TabEnt_flags(tab_ent); tab_ent = TabEnt_next(tab_ent); } yap_flags[TABLING_MODE_FLAG] = 0; } else if (value == 1) { /* batched */ - tab_ent_ptr tab_ent = Yap_root_tab_ent; + tab_ent_ptr tab_ent = GLOBAL_root_tab_ent; while(tab_ent) { SetMode_Batched(TabEnt_mode(tab_ent)); tab_ent = TabEnt_next(tab_ent); } SetMode_Batched(yap_flags[TABLING_MODE_FLAG]); } else if (value == 2) { /* local */ - tab_ent_ptr tab_ent = Yap_root_tab_ent; + tab_ent_ptr tab_ent = GLOBAL_root_tab_ent; while(tab_ent) { SetMode_Local(TabEnt_mode(tab_ent)); tab_ent = TabEnt_next(tab_ent); } SetMode_Local(yap_flags[TABLING_MODE_FLAG]); } else if (value == 3) { /* exec_answers */ - tab_ent_ptr tab_ent = Yap_root_tab_ent; + tab_ent_ptr tab_ent = GLOBAL_root_tab_ent; while(tab_ent) { SetMode_ExecAnswers(TabEnt_mode(tab_ent)); tab_ent = TabEnt_next(tab_ent); } SetMode_ExecAnswers(yap_flags[TABLING_MODE_FLAG]); } else if (value == 4) { /* load_answers */ - tab_ent_ptr tab_ent = Yap_root_tab_ent; + tab_ent_ptr tab_ent = GLOBAL_root_tab_ent; while(tab_ent) { SetMode_LoadAnswers(TabEnt_mode(tab_ent)); tab_ent = TabEnt_next(tab_ent); } SetMode_LoadAnswers(yap_flags[TABLING_MODE_FLAG]); } else if (value == 5) { /* local_trie */ - tab_ent_ptr tab_ent = Yap_root_tab_ent; + tab_ent_ptr tab_ent = GLOBAL_root_tab_ent; while(tab_ent) { SetMode_LocalTrie(TabEnt_mode(tab_ent)); tab_ent = TabEnt_next(tab_ent); } SetMode_LocalTrie(yap_flags[TABLING_MODE_FLAG]); } else if (value == 6) { /* global_trie */ - tab_ent_ptr tab_ent = Yap_root_tab_ent; + tab_ent_ptr tab_ent = GLOBAL_root_tab_ent; while(tab_ent) { SetMode_GlobalTrie(TabEnt_mode(tab_ent)); tab_ent = TabEnt_next(tab_ent); @@ -3904,41 +3904,41 @@ p_system_mode( USES_REGS1 ) { Int i = IntegerOfTerm(Deref(ARG1)); if (i == 0) - Yap_PrologMode &= ~SystemMode; + LOCAL_PrologMode &= ~SystemMode; else - Yap_PrologMode |= SystemMode; + LOCAL_PrologMode |= SystemMode; return TRUE; } static Int p_lock_system( USES_REGS1 ) { - LOCK(Yap_BGL); + LOCK(GLOBAL_BGL); return TRUE; } static Int p_unlock_system( USES_REGS1 ) { - UNLOCK(Yap_BGL); + UNLOCK(GLOBAL_BGL); return TRUE; } static Int p_enterundefp( USES_REGS1 ) { - if (DoingUndefp) { + if (LOCAL_DoingUndefp) { return FALSE; } - DoingUndefp = TRUE; + LOCAL_DoingUndefp = TRUE; return TRUE; } static Int p_exitundefp( USES_REGS1 ) { - if (DoingUndefp) { - DoingUndefp = FALSE; + if (LOCAL_DoingUndefp) { + LOCAL_DoingUndefp = FALSE; return TRUE; } return FALSE; @@ -4110,7 +4110,7 @@ Proc E_Modules[]= {/* init_fc,*/ (Proc) 0 }; #ifndef YAPOR static -Int p_yapor_threads(void) { +Int p_yapor_threads( USES_REGS1 ) { return FALSE; } #endif diff --git a/C/sysbits.c b/C/sysbits.c index 08e40adea..0912cd079 100755 --- a/C/sysbits.c +++ b/C/sysbits.c @@ -88,7 +88,7 @@ static char SccsId[] = "%W% %G%"; #include #endif -STATIC_PROTO (void InitPageSize, (void)); + STATIC_PROTO (void InitTime, (void)); STATIC_PROTO (void InitWTime, (void)); STATIC_PROTO (Int p_sh, ( USES_REGS1 )); @@ -107,9 +107,6 @@ STATIC_PROTO (int chdir, (char *)); /* #define signal skel_signal */ #endif /* MACYAP */ -#if __simplescalar__ -char yap_pwd[YAP_FILENAME_MAX]; -#endif STD_PROTO (void exit, (int)); @@ -202,27 +199,27 @@ Yap_InitSysPath(void) { if (dir_done && commons_done) return; #endif - strncpy(Yap_FileNameBuf, YAP_SHAREDIR, YAP_FILENAME_MAX); + strncpy(LOCAL_FileNameBuf, YAP_SHAREDIR, YAP_FILENAME_MAX); #if _MSC_VER || defined(__MINGW32__) { DWORD fatts; int buflen; char *pt; - if ((fatts = GetFileAttributes(Yap_FileNameBuf)) == 0xFFFFFFFFL || + if ((fatts = GetFileAttributes(LOCAL_FileNameBuf)) == 0xFFFFFFFFL || !(fatts & FILE_ATTRIBUTE_DIRECTORY)) { /* couldn't find it where it was supposed to be, let's try using the executable */ - if (!GetModuleFileNameEx( GetCurrentProcess(), NULL, Yap_FileNameBuf, YAP_FILENAME_MAX)) { + if (!GetModuleFileNameEx( GetCurrentProcess(), NULL, LOCAL_FileNameBuf, YAP_FILENAME_MAX)) { Yap_Error(OPERATING_SYSTEM_ERROR, TermNil, "could not find executable name"); /* do nothing */ return; } - buflen = strlen(Yap_FileNameBuf); - pt = Yap_FileNameBuf+strlen(Yap_FileNameBuf); + buflen = strlen(LOCAL_FileNameBuf); + pt = LOCAL_FileNameBuf+strlen(LOCAL_FileNameBuf); while (*--pt != '\\') { /* skip executable */ - if (pt == Yap_FileNameBuf) { + if (pt == LOCAL_FileNameBuf) { Yap_Error(OPERATING_SYSTEM_ERROR, TermNil, "could not find executable name"); /* do nothing */ return; @@ -230,7 +227,7 @@ Yap_InitSysPath(void) { } while (*--pt != '\\') { /* skip parent directory "bin\\" */ - if (pt == Yap_FileNameBuf) { + if (pt == LOCAL_FileNameBuf) { Yap_Error(OPERATING_SYSTEM_ERROR, TermNil, "could not find executable name"); /* do nothing */ } @@ -238,34 +235,34 @@ Yap_InitSysPath(void) { /* now, this is a possible location for the ROOT_DIR, let's look for a share directory here */ pt[1] = '\0'; /* grosse */ - strncat(Yap_FileNameBuf,"lib\\Yap",YAP_FILENAME_MAX); - libdir = Yap_AllocCodeSpace(strlen(Yap_FileNameBuf)+1); - strncpy(libdir, Yap_FileNameBuf, strlen(Yap_FileNameBuf)+1); + strncat(LOCAL_FileNameBuf,"lib\\Yap",YAP_FILENAME_MAX); + libdir = Yap_AllocCodeSpace(strlen(LOCAL_FileNameBuf)+1); + strncpy(libdir, LOCAL_FileNameBuf, strlen(LOCAL_FileNameBuf)+1); pt[1] = '\0'; - strncat(Yap_FileNameBuf,"share",YAP_FILENAME_MAX); + strncat(LOCAL_FileNameBuf,"share",YAP_FILENAME_MAX); } } - strncat(Yap_FileNameBuf,"\\", YAP_FILENAME_MAX); + strncat(LOCAL_FileNameBuf,"\\", YAP_FILENAME_MAX); #else - strncat(Yap_FileNameBuf,"/", YAP_FILENAME_MAX); + strncat(LOCAL_FileNameBuf,"/", YAP_FILENAME_MAX); #endif - len = strlen(Yap_FileNameBuf); - strncat(Yap_FileNameBuf, "Yap", YAP_FILENAME_MAX); + len = strlen(LOCAL_FileNameBuf); + strncat(LOCAL_FileNameBuf, "Yap", YAP_FILENAME_MAX); #if _MSC_VER || defined(__MINGW32__) if (!dir_done) #endif { Yap_PutValue(AtomSystemLibraryDir, - MkAtomTerm(Yap_LookupAtom(Yap_FileNameBuf))); + MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf))); } #if _MSC_VER || defined(__MINGW32__) if (!commons_done) #endif { - Yap_FileNameBuf[len] = '\0'; - strncat(Yap_FileNameBuf, "PrologCommons", YAP_FILENAME_MAX); + LOCAL_FileNameBuf[len] = '\0'; + strncat(LOCAL_FileNameBuf, "PrologCommons", YAP_FILENAME_MAX); Yap_PutValue(AtomPrologCommonsDir, - MkAtomTerm(Yap_LookupAtom(Yap_FileNameBuf))); + MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf))); } } @@ -287,8 +284,8 @@ p_dir_sp ( USES_REGS1 ) } -static void -InitPageSize(void) +void +Yap_InitPageSize(void) { #ifdef _WIN32 SYSTEM_INFO si; @@ -334,8 +331,8 @@ bla bla #endif #if THREADS -#define StartOfTimes (*(MY_ThreadHandle.start_of_timesp)) -#define last_time (*(MY_ThreadHandle.last_timep)) +#define StartOfTimes (*(LOCAL_ThreadHandle.start_of_timesp)) +#define last_time (*(LOCAL_ThreadHandle.last_timep)) #else /* since the point YAP was started */ @@ -355,8 +352,8 @@ InitTime (void) struct rusage rusage; #if THREADS - MY_ThreadHandle.start_of_timesp = (struct timeval *)malloc(sizeof(struct timeval)); - MY_ThreadHandle.last_timep = (struct timeval *)malloc(sizeof(struct timeval)); + LOCAL_ThreadHandle.start_of_timesp = (struct timeval *)malloc(sizeof(struct timeval)); + LOCAL_ThreadHandle.last_timep = (struct timeval *)malloc(sizeof(struct timeval)); #endif getrusage(RUSAGE_SELF, &rusage); last_time.tv_sec = StartOfTimes.tv_sec = rusage.ru_utime.tv_sec; @@ -1197,7 +1194,7 @@ HandleSIGSEGV(int sig, siginfo_t *sip, ucontext_t *uap) sip->si_code != SI_NOINFO && sip->si_code == SEGV_MAPERR && (void *)(sip->si_addr) > (void *)(Yap_HeapBase) && - (void *)(sip->si_addr) < (void *)(Yap_TrailTop+K64)) { + (void *)(sip->si_addr) < (void *)(LOCAL_TrailTop+K64)) { Yap_growtrail(K64, TRUE); } else #endif @@ -1211,6 +1208,7 @@ HandleSIGSEGV(int sig, siginfo_t *sip, ucontext_t *uap) static void HandleMatherr(int sig, siginfo_t *sip, ucontext_t *uap) { + CACHE_REGS yap_error_number error_no; /* reset the registers so that we don't have trash in abstract machine */ @@ -1308,6 +1306,7 @@ STATIC_PROTO (void my_signal, (int, void (*)(int))); static RETSIGTYPE HandleMatherr(int sig) { + CACHE_REGS #if HAVE_FETESTEXCEPT /* This should work in Linux, but it doesn't seem to. */ @@ -1315,19 +1314,19 @@ HandleMatherr(int sig) int raised = fetestexcept(FE_ALL_EXCEPT); if (raised & FE_OVERFLOW) { - Yap_matherror = EVALUATION_ERROR_FLOAT_OVERFLOW; + LOCAL_matherror = EVALUATION_ERROR_FLOAT_OVERFLOW; } else if (raised & (FE_INVALID|FE_INEXACT)) { - Yap_matherror = EVALUATION_ERROR_UNDEFINED; + LOCAL_matherror = EVALUATION_ERROR_UNDEFINED; } else if (raised & FE_DIVBYZERO) { - Yap_matherror = EVALUATION_ERROR_ZERO_DIVISOR; + LOCAL_matherror = EVALUATION_ERROR_ZERO_DIVISOR; } else if (raised & FE_UNDERFLOW) { - Yap_matherror = EVALUATION_ERROR_FLOAT_UNDERFLOW; + LOCAL_matherror = EVALUATION_ERROR_FLOAT_UNDERFLOW; } else #endif - Yap_matherror = EVALUATION_ERROR_UNDEFINED; + LOCAL_matherror = EVALUATION_ERROR_UNDEFINED; /* something very bad happened on the way to the forum */ set_fpu_exceptions(FALSE); - Yap_Error(Yap_matherror, TermNil, ""); + Yap_Error(LOCAL_matherror , TermNil, ""); } #if HAVE_SIGSEGV && !defined(THREADS) @@ -1358,8 +1357,8 @@ SearchForTrailFault(siginfo_t *siginfo) crash again */ #if OS_HANDLES_TR_OVERFLOW && !USE_SYSTEM_MALLOC - if ((ptr > (void *)Yap_TrailTop-1024 && - TR < (tr_fr_ptr) Yap_TrailTop+(64*1024))) { + if ((ptr > (void *)LOCAL_TrailTop-1024 && + TR < (tr_fr_ptr) LOCAL_TrailTop+(64*1024))) { if (!Yap_growtrail(64*1024, TRUE)) { Yap_Error(OUT_OF_TRAIL_ERROR, TermNil, "YAP failed to reserve %ld bytes in growtrail", K64); } @@ -1376,8 +1375,8 @@ SearchForTrailFault(siginfo_t *siginfo) static RETSIGTYPE HandleSIGSEGV(int sig, siginfo_t *siginfo, void *context) { - if (Yap_PrologMode & ExtendStackMode) { - Yap_Error(FATAL_ERROR, TermNil, "OS memory allocation crashed at address %p, bailing out\n",Yap_TrailTop); + if (LOCAL_PrologMode & ExtendStackMode) { + Yap_Error(FATAL_ERROR, TermNil, "OS memory allocation crashed at address %p, bailing out\n",LOCAL_TrailTop); } SearchForTrailFault(siginfo); } @@ -1445,19 +1444,19 @@ HandleMatherr(int sig) int raised = fetestexcept(FE_ALL_EXCEPT); if (raised & FE_OVERFLOW) { - Yap_matherror = EVALUATION_ERROR_FLOAT_OVERFLOW; + LOCAL_matherror = EVALUATION_ERROR_FLOAT_OVERFLOW; } else if (raised & (FE_INVALID|FE_INEXACT)) { - Yap_matherror = EVALUATION_ERROR_UNDEFINED; + LOCAL_matherror = EVALUATION_ERROR_UNDEFINED; } else if (raised & FE_DIVBYZERO) { - Yap_matherror = EVALUATION_ERROR_ZERO_DIVISOR; + LOCAL_matherror = EVALUATION_ERROR_ZERO_DIVISOR; } else if (raised & FE_UNDERFLOW) { - Yap_matherror = EVALUATION_ERROR_FLOAT_UNDERFLOW; + LOCAL_matherror = EVALUATION_ERROR_FLOAT_UNDERFLOW; } else #endif - Yap_matherror = EVALUATION_ERROR_UNDEFINED; + LOCAL_matherror = EVALUATION_ERROR_UNDEFINED; /* something very bad happened on the way to the forum */ set_fpu_exceptions(FALSE); - Yap_Error(Yap_matherror, TermNil, ""); + Yap_Error(LOCAL_matherror , TermNil, ""); } static void @@ -1472,11 +1471,11 @@ SearchForTrailFault(void) /* fprintf(stderr,"Catching a sigsegv at %p with %p\n", TR, TrailTop); */ #endif #if OS_HANDLES_TR_OVERFLOW && !USE_SYSTEM_MALLOC - if ((TR > (tr_fr_ptr)Yap_TrailTop-1024 && - TR < (tr_fr_ptr)Yap_TrailTop+(64*1024))|| Yap_DBTrailOverflow()) { + if ((TR > (tr_fr_ptr)LOCAL_TrailTop-1024 && + TR < (tr_fr_ptr)LOCAL_TrailTop+(64*1024))|| Yap_DBTrailOverflow()) { long trsize = K64; - while ((CELL)TR > (CELL)Yap_TrailTop+trsize) { + while ((CELL)TR > (CELL)LOCAL_TrailTop+trsize) { trsize += K64; } if (!Yap_growtrail(trsize, TRUE)) { @@ -1493,9 +1492,9 @@ SearchForTrailFault(void) static RETSIGTYPE HandleSIGSEGV(int sig) { - if (Yap_PrologMode & ExtendStackMode) { + if (LOCAL_PrologMode & ExtendStackMode) { CACHE_REGS - Yap_Error(FATAL_ERROR, TermNil, "OS memory allocation crashed at address %p, bailing out\n",Yap_TrailTop); + Yap_Error(FATAL_ERROR, TermNil, "OS memory allocation crashed at address %p, bailing out\n",LOCAL_TrailTop); } SearchForTrailFault(); } @@ -1554,71 +1553,71 @@ void (*handler)(int); static int InteractSIGINT(int ch) { CACHE_REGS - Yap_PrologMode |= AsyncIntMode; + LOCAL_PrologMode |= AsyncIntMode; switch (ch) { case 'a': /* abort computation */ - if (Yap_PrologMode & (GCMode|ConsoleGetcMode|GrowStackMode|GrowHeapMode)) { - Yap_PrologMode |= AbortMode; + if (LOCAL_PrologMode & (GCMode|ConsoleGetcMode|GrowStackMode|GrowHeapMode)) { + LOCAL_PrologMode |= AbortMode; } else { Yap_Error(PURE_ABORT, TermNil, "abort from console"); /* in case someone mangles the P register */ } - Yap_PrologMode &= ~AsyncIntMode; - siglongjmp(Yap_RestartEnv,1); + LOCAL_PrologMode &= ~AsyncIntMode; + siglongjmp(LOCAL_RestartEnv,1); return -1; case 'b': /* continue */ Yap_signal (YAP_BREAK_SIGNAL); - Yap_PrologMode &= ~AsyncIntMode; + LOCAL_PrologMode &= ~AsyncIntMode; return 1; case 'c': /* continue */ return 1; case 'd': Yap_signal (YAP_DEBUG_SIGNAL); - Yap_PrologMode &= ~AsyncIntMode; + LOCAL_PrologMode &= ~AsyncIntMode; /* enter debug mode */ return 1; case 'e': /* exit */ - Yap_PrologMode &= ~AsyncIntMode; + LOCAL_PrologMode &= ~AsyncIntMode; Yap_exit(0); return -1; case 'g': /* exit */ Yap_signal (YAP_STACK_DUMP_SIGNAL); - Yap_PrologMode &= ~AsyncIntMode; + LOCAL_PrologMode &= ~AsyncIntMode; return -1; case 't': /* start tracing */ Yap_signal (YAP_TRACE_SIGNAL); - Yap_PrologMode &= ~AsyncIntMode; + LOCAL_PrologMode &= ~AsyncIntMode; return 1; #ifdef LOW_LEVEL_TRACER case 'T': toggle_low_level_trace(); - Yap_PrologMode &= ~AsyncIntMode; + LOCAL_PrologMode &= ~AsyncIntMode; return 1; #endif case 's': /* show some statistics */ Yap_signal (YAP_STATISTICS_SIGNAL); - Yap_PrologMode &= ~AsyncIntMode; + LOCAL_PrologMode &= ~AsyncIntMode; return 1; case EOF: - Yap_PrologMode &= ~AsyncIntMode; + LOCAL_PrologMode &= ~AsyncIntMode; return(0); break; case 'h': case '?': default: /* show an helpful message */ - fprintf(Yap_stderr, "Please press one of:\n"); - fprintf(Yap_stderr, " a for abort\n c for continue\n d for debug\n"); - fprintf(Yap_stderr, " e for exit\n g for stack dump\n s for statistics\n t for trace\n"); - fprintf(Yap_stderr, " b for break\n"); - Yap_PrologMode &= ~AsyncIntMode; + fprintf(GLOBAL_stderr, "Please press one of:\n"); + fprintf(GLOBAL_stderr, " a for abort\n c for continue\n d for debug\n"); + fprintf(GLOBAL_stderr, " e for exit\n g for stack dump\n s for statistics\n t for trace\n"); + fprintf(GLOBAL_stderr, " b for break\n"); + LOCAL_PrologMode &= ~AsyncIntMode; return(0); } } @@ -1666,16 +1665,16 @@ HandleSIGINT (int sig) my_signal(SIGINT, HandleSIGINT); /* do this before we act */ #if HAVE_ISATTY - if (!isatty(0) && !Yap_sockets_io) { + if (!isatty(0)) { Yap_Error(INTERRUPT_ERROR,MkIntTerm(SIGINT),NULL); return; } #endif - if (Yap_InterruptsDisabled) { + if (LOCAL_InterruptsDisabled) { return; } - if (Yap_PrologMode & (CritMode|ConsoleGetcMode)) { - Yap_PrologMode |= InterruptMode; + if (LOCAL_PrologMode & (CritMode|ConsoleGetcMode)) { + LOCAL_PrologMode |= InterruptMode; } #ifdef HAVE_SETBUF /* make sure we are not waiting for the end of line */ @@ -1777,7 +1776,7 @@ ReceiveSignal (int s) break; #endif /* defined(SIGHUP) */ default: - fprintf(Yap_stderr, "\n[ Unexpected signal ]\n"); + fprintf(GLOBAL_stderr, "\n[ Unexpected signal ]\n"); exit (EXIT_FAILURE); } } @@ -1786,14 +1785,14 @@ ReceiveSignal (int s) #if (_MSC_VER || defined(__MINGW32__)) static BOOL WINAPI MSCHandleSignal(DWORD dwCtrlType) { - if (Yap_InterruptsDisabled) { + if (LOCAL_InterruptsDisabled) { return FALSE; } switch(dwCtrlType) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: Yap_signal(YAP_ALARM_SIGNAL); - Yap_PrologMode |= InterruptMode; + LOCAL_PrologMode |= InterruptMode; return(TRUE); default: return(FALSE); @@ -1805,7 +1804,7 @@ MSCHandleSignal(DWORD dwCtrlType) { static void InitSignals (void) { - if (Yap_PrologShouldHandleInterrupts) { + if (GLOBAL_PrologShouldHandleInterrupts) { #if !defined(LIGHT) && !_MSC_VER && !defined(__MINGW32__) && !defined(LIGHT) my_signal (SIGQUIT, ReceiveSignal); my_signal (SIGKILL, ReceiveSignal); @@ -1878,7 +1877,7 @@ int Yap_getcwd(const char *buf, int len) CACHE_REGS #if __simplescalar__ /* does not implement getcwd */ - strncpy(Yap_buf,yap_pwd,len); + strncpy(Yap_buf,GLOBAL_pwd,len); #elif HAVE_GETCWD if (getcwd ((char *)buf, len) == NULL) { #if HAVE_STRERROR @@ -2007,7 +2006,7 @@ TrueFileName (char *source, char *root, char *result, int in_lib) if ((tmpf = open(ares1, O_RDONLY)) < 0) { /* not in current directory, let us try the library */ if (Yap_LibDir != NULL) { - strncpy(Yap_FileNameBuf, Yap_LibDir, YAP_FILENAME_MAX); + strncpy(LOCAL_FileNameBuf, Yap_LibDir, YAP_FILENAME_MAX); #if HAVE_GETENV } else { char *yap_env = getenv("YAPLIBDIR"); @@ -2105,8 +2104,8 @@ p_true_file_name ( USES_REGS1 ) Yap_Error(TYPE_ERROR_ATOM,t,"argument to true_file_name"); return FALSE; } - TrueFileName (RepAtom(AtomOfTerm(t))->StrOfAE, NULL, Yap_FileNameBuf, FALSE); - return Yap_unify(ARG2, MkAtomTerm(Yap_LookupAtom(Yap_FileNameBuf))); + TrueFileName (RepAtom(AtomOfTerm(t))->StrOfAE, NULL, LOCAL_FileNameBuf, FALSE); + return Yap_unify(ARG2, MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf))); } static Int @@ -2130,8 +2129,8 @@ p_true_file_name3 ( USES_REGS1 ) } root = RepAtom(AtomOfTerm(t2))->StrOfAE; } - TrueFileName (RepAtom(AtomOfTerm(t))->StrOfAE, root, Yap_FileNameBuf, FALSE); - return Yap_unify(ARG3, MkAtomTerm(Yap_LookupAtom(Yap_FileNameBuf))); + TrueFileName (RepAtom(AtomOfTerm(t))->StrOfAE, root, LOCAL_FileNameBuf, FALSE); + return Yap_unify(ARG3, MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf))); } /* Executes $SHELL under Prolog */ @@ -2239,11 +2238,11 @@ p_system ( USES_REGS1 ) } else if (IsAtomTerm(t1)) { s = RepAtom(AtomOfTerm(t1))->StrOfAE; } else { - if (!Yap_GetName (Yap_FileNameBuf, YAP_FILENAME_MAX, t1)) { + if (!Yap_GetName (LOCAL_FileNameBuf, YAP_FILENAME_MAX, t1)) { Yap_Error(TYPE_ERROR_ATOM,t1,"argument to system/1"); return FALSE; } - s = Yap_FileNameBuf; + s = LOCAL_FileNameBuf; } /* Yap_CloseStreams(TRUE); */ #if _MSC_VER @@ -2397,7 +2396,7 @@ static Int p_putenv( USES_REGS1 ) } else s2 = RepAtom(AtomOfTerm(t2))->StrOfAE; while (!(p0 = p = Yap_AllocAtomSpace(strlen(s)+strlen(s2)+3))) { if (!Yap_growheap(FALSE, MinHeapGap, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -2478,14 +2477,14 @@ p_alarm( USES_REGS1 ) i1 = IntegerOfTerm(t); i2 = IntegerOfTerm(t2); if (i1 == 0 && i2 == 0) { - LOCK(SignalLock); - if (ActiveSignals & YAP_ALARM_SIGNAL) { - ActiveSignals &= ~YAP_ALARM_SIGNAL; - if (!ActiveSignals) { + LOCK(LOCAL_SignalLock); + if (LOCAL_ActiveSignals & YAP_ALARM_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_ALARM_SIGNAL; + if (!LOCAL_ActiveSignals) { CreepFlag = CalculateStackGap(); } } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); } #if _MSC_VER || defined(__MINGW32__) { @@ -2730,10 +2729,9 @@ Yap_InitSysbits (void) #if __simplescalar__ { char *pwd = getenv("PWD"); - strncpy(yap_pwd,pwd,YAP_FILENAME_MAX); + strncpy(GLOBAL_pwd,pwd,YAP_FILENAME_MAX); } #endif - InitPageSize(); InitWTime (); InitRandom (); /* let the caller control signals as it sees fit */ @@ -2758,146 +2756,146 @@ Yap_ReInitWallTime (void) static Int p_first_signal( USES_REGS1 ) { - LOCK(SignalLock); + LOCK(LOCAL_SignalLock); #ifdef THREADS - pthread_mutex_lock(&(MY_ThreadHandle.tlock)); + pthread_mutex_lock(&(LOCAL_ThreadHandle.tlock)); #endif /* always do wakeups first, because you don't want to keep the non-backtrackable variable bad */ - if (ActiveSignals & YAP_WAKEUP_SIGNAL) { - ActiveSignals &= ~YAP_WAKEUP_SIGNAL; + if (LOCAL_ActiveSignals & YAP_WAKEUP_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_WAKEUP_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigWakeUp)); } - if (ActiveSignals & YAP_ITI_SIGNAL) { - ActiveSignals &= ~YAP_ITI_SIGNAL; + if (LOCAL_ActiveSignals & YAP_ITI_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_ITI_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigIti)); } - if (ActiveSignals & YAP_INT_SIGNAL) { - ActiveSignals &= ~YAP_INT_SIGNAL; + if (LOCAL_ActiveSignals & YAP_INT_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_INT_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigInt)); } - if (ActiveSignals & YAP_USR2_SIGNAL) { - ActiveSignals &= ~YAP_USR2_SIGNAL; + if (LOCAL_ActiveSignals & YAP_USR2_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_USR2_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigUsr2)); } - if (ActiveSignals & YAP_USR1_SIGNAL) { - ActiveSignals &= ~YAP_USR1_SIGNAL; + if (LOCAL_ActiveSignals & YAP_USR1_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_USR1_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigUsr1)); } - if (ActiveSignals & YAP_PIPE_SIGNAL) { - ActiveSignals &= ~YAP_PIPE_SIGNAL; + if (LOCAL_ActiveSignals & YAP_PIPE_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_PIPE_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigPipe)); } - if (ActiveSignals & YAP_HUP_SIGNAL) { - ActiveSignals &= ~YAP_HUP_SIGNAL; + if (LOCAL_ActiveSignals & YAP_HUP_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_HUP_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigHup)); } - if (ActiveSignals & YAP_ALARM_SIGNAL) { - ActiveSignals &= ~YAP_ALARM_SIGNAL; - UNLOCK(SignalLock); + if (LOCAL_ActiveSignals & YAP_ALARM_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_ALARM_SIGNAL; + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigAlarm)); } - if (ActiveSignals & YAP_VTALARM_SIGNAL) { - ActiveSignals &= ~YAP_VTALARM_SIGNAL; - UNLOCK(SignalLock); + if (LOCAL_ActiveSignals & YAP_VTALARM_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_VTALARM_SIGNAL; + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigVTAlarm)); } - if (ActiveSignals & YAP_DELAY_CREEP_SIGNAL) { - ActiveSignals &= ~(YAP_CREEP_SIGNAL|YAP_DELAY_CREEP_SIGNAL); + if (LOCAL_ActiveSignals & YAP_DELAY_CREEP_SIGNAL) { + LOCAL_ActiveSignals &= ~(YAP_CREEP_SIGNAL|YAP_DELAY_CREEP_SIGNAL); #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigDelayCreep)); } - if (ActiveSignals & YAP_CREEP_SIGNAL) { - ActiveSignals &= ~YAP_CREEP_SIGNAL; + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_CREEP_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigCreep)); } - if (ActiveSignals & YAP_TRACE_SIGNAL) { - ActiveSignals &= ~YAP_TRACE_SIGNAL; + if (LOCAL_ActiveSignals & YAP_TRACE_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_TRACE_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigTrace)); } - if (ActiveSignals & YAP_DEBUG_SIGNAL) { - ActiveSignals &= ~YAP_DEBUG_SIGNAL; + if (LOCAL_ActiveSignals & YAP_DEBUG_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_DEBUG_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigDebug)); } - if (ActiveSignals & YAP_BREAK_SIGNAL) { - ActiveSignals &= ~YAP_BREAK_SIGNAL; + if (LOCAL_ActiveSignals & YAP_BREAK_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_BREAK_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigBreak)); } - if (ActiveSignals & YAP_STACK_DUMP_SIGNAL) { - ActiveSignals &= ~YAP_STACK_DUMP_SIGNAL; + if (LOCAL_ActiveSignals & YAP_STACK_DUMP_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_STACK_DUMP_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigStackDump)); } - if (ActiveSignals & YAP_STATISTICS_SIGNAL) { - ActiveSignals &= ~YAP_STATISTICS_SIGNAL; + if (LOCAL_ActiveSignals & YAP_STATISTICS_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_STATISTICS_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomSigStatistics)); } - if (ActiveSignals & YAP_FAIL_SIGNAL) { - ActiveSignals &= ~YAP_FAIL_SIGNAL; + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { + LOCAL_ActiveSignals &= ~YAP_FAIL_SIGNAL; #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return Yap_unify(ARG1, MkAtomTerm(AtomFail)); } #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return FALSE; } @@ -2905,53 +2903,53 @@ static Int p_continue_signals( USES_REGS1 ) { /* hack to force the signal anew */ - if (ActiveSignals & YAP_ITI_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_ITI_SIGNAL) { Yap_signal(YAP_ITI_SIGNAL); } - if (ActiveSignals & YAP_INT_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_INT_SIGNAL) { Yap_signal(YAP_INT_SIGNAL); } - if (ActiveSignals & YAP_USR2_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_USR2_SIGNAL) { Yap_signal(YAP_USR2_SIGNAL); } - if (ActiveSignals & YAP_USR1_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_USR1_SIGNAL) { Yap_signal(YAP_USR1_SIGNAL); } - if (ActiveSignals & YAP_HUP_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_HUP_SIGNAL) { Yap_signal(YAP_HUP_SIGNAL); } - if (ActiveSignals & YAP_ALARM_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_ALARM_SIGNAL) { Yap_signal(YAP_ALARM_SIGNAL); } - if (ActiveSignals & YAP_VTALARM_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_VTALARM_SIGNAL) { Yap_signal(YAP_VTALARM_SIGNAL); } - if (ActiveSignals & YAP_CREEP_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_CREEP_SIGNAL) { Yap_signal(YAP_CREEP_SIGNAL); } - if (ActiveSignals & YAP_DELAY_CREEP_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_DELAY_CREEP_SIGNAL) { Yap_signal(YAP_DELAY_CREEP_SIGNAL|YAP_CREEP_SIGNAL); } - if (ActiveSignals & YAP_TRACE_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_TRACE_SIGNAL) { Yap_signal(YAP_TRACE_SIGNAL); } - if (ActiveSignals & YAP_DEBUG_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_DEBUG_SIGNAL) { Yap_signal(YAP_DEBUG_SIGNAL); } - if (ActiveSignals & YAP_BREAK_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_BREAK_SIGNAL) { Yap_signal(YAP_BREAK_SIGNAL); } - if (ActiveSignals & YAP_STACK_DUMP_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_STACK_DUMP_SIGNAL) { Yap_signal(YAP_STACK_DUMP_SIGNAL); } - if (ActiveSignals & YAP_STATISTICS_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_STATISTICS_SIGNAL) { Yap_signal(YAP_STATISTICS_SIGNAL); } - if (ActiveSignals & YAP_FAIL_SIGNAL) { + if (LOCAL_ActiveSignals & YAP_FAIL_SIGNAL) { Yap_signal(YAP_FAIL_SIGNAL); } #ifdef THREADS - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); #endif return TRUE; } @@ -2992,24 +2990,24 @@ p_win32( USES_REGS1 ) static Int p_enable_interrupts( USES_REGS1 ) { - LOCK(SignalLock); - Yap_InterruptsDisabled--; - if (ActiveSignals && !Yap_InterruptsDisabled) { + LOCK(LOCAL_SignalLock); + LOCAL_InterruptsDisabled--; + if (LOCAL_ActiveSignals && !LOCAL_InterruptsDisabled) { CreepFlag = Unsigned(LCL0); } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return TRUE; } static Int p_disable_interrupts( USES_REGS1 ) { - LOCK(SignalLock); - Yap_InterruptsDisabled++; - if (ActiveSignals) { + LOCK(LOCAL_SignalLock); + LOCAL_InterruptsDisabled++; + if (LOCAL_ActiveSignals) { CreepFlag = CalculateStackGap(); } - UNLOCK(SignalLock); + UNLOCK(LOCAL_SignalLock); return TRUE; } diff --git a/C/threads.c b/C/threads.c index 2c66df70d..cd6955685 100755 --- a/C/threads.c +++ b/C/threads.c @@ -1,4 +1,3 @@ - /************************************************************************* * * * YAP Prolog * @@ -51,29 +50,29 @@ static int allocate_new_tid(void) { int new_worker_id = 0; - LOCK(Yap_ThreadHandlesLock); + LOCK(GLOBAL_ThreadHandlesLock); while(new_worker_id < MAX_THREADS && - Yap_WLocal[new_worker_id] && - (FOREIGN_ThreadHandle(new_worker_id).in_use == TRUE || - FOREIGN_ThreadHandle(new_worker_id).zombie == TRUE) ) + Yap_local[new_worker_id] && + (REMOTE_ThreadHandle(new_worker_id).in_use == TRUE || + REMOTE_ThreadHandle(new_worker_id).zombie == TRUE) ) new_worker_id++; if (new_worker_id >= MAX_THREADS) { new_worker_id = -1; - } else if (!Yap_WLocal[new_worker_id]) { + } else if (!Yap_local[new_worker_id]) { DEBUG_TLOCK_ACCESS(new_worker_id, 0); if (!Yap_InitThread(new_worker_id)) { return -1; } - pthread_mutex_lock(&(FOREIGN_ThreadHandle(new_worker_id).tlock)); - FOREIGN_ThreadHandle(new_worker_id).in_use = TRUE; + pthread_mutex_lock(&(REMOTE_ThreadHandle(new_worker_id).tlock)); + REMOTE_ThreadHandle(new_worker_id).in_use = TRUE; } else if (new_worker_id < MAX_THREADS) { DEBUG_TLOCK_ACCESS(new_worker_id, 0); - pthread_mutex_lock(&(FOREIGN_ThreadHandle(new_worker_id).tlock)); - FOREIGN_ThreadHandle(new_worker_id).in_use = TRUE; + pthread_mutex_lock(&(REMOTE_ThreadHandle(new_worker_id).tlock)); + REMOTE_ThreadHandle(new_worker_id).in_use = TRUE; } else { new_worker_id = -1; } - UNLOCK(Yap_ThreadHandlesLock); + UNLOCK(GLOBAL_ThreadHandlesLock); return new_worker_id; } @@ -89,31 +88,31 @@ store_specs(int new_worker_id, UInt ssize, UInt tsize, UInt sysize, Term *tpgoal tsize = MinTrailSpace; if (ssize < MinStackSpace) ssize = MinStackSpace; - FOREIGN_ThreadHandle(new_worker_id).ssize = ssize; - FOREIGN_ThreadHandle(new_worker_id).tsize = tsize; - FOREIGN_ThreadHandle(new_worker_id).sysize = sysize; - FOREIGN(new_worker_id)->c_input_stream = Yap_c_input_stream; - FOREIGN(new_worker_id)->c_output_stream = Yap_c_output_stream; - FOREIGN(new_worker_id)->c_error_stream = Yap_c_error_stream; + REMOTE_ThreadHandle(new_worker_id).ssize = ssize; + REMOTE_ThreadHandle(new_worker_id).tsize = tsize; + REMOTE_ThreadHandle(new_worker_id).sysize = sysize; + REMOTE_c_input_stream(new_worker_id) = LOCAL_c_input_stream; + REMOTE_c_output_stream(new_worker_id) = LOCAL_c_output_stream; + REMOTE_c_error_stream(new_worker_id) = LOCAL_c_error_stream; pm = (ssize + tsize)*1024; - if (!(FOREIGN_ThreadHandle(new_worker_id).stack_address = malloc(pm))) { + if (!(REMOTE_ThreadHandle(new_worker_id).stack_address = malloc(pm))) { return FALSE; } - FOREIGN_ThreadHandle(new_worker_id).tgoal = + REMOTE_ThreadHandle(new_worker_id).tgoal = Yap_StoreTermInDB(Deref(*tpgoal),7); - FOREIGN_ThreadHandle(new_worker_id).cmod = + REMOTE_ThreadHandle(new_worker_id).cmod = CurrentModule; tdetach = Deref(*tpdetach); if (IsVarTerm(tdetach)){ - FOREIGN_ThreadHandle(new_worker_id).tdetach = + REMOTE_ThreadHandle(new_worker_id).tdetach = MkAtomTerm(AtomFalse); } else { - FOREIGN_ThreadHandle(new_worker_id).tdetach = + REMOTE_ThreadHandle(new_worker_id).tdetach = tdetach; } tgoal = Yap_StripModule(Deref(*tpexit), &tmod); - FOREIGN_ThreadHandle(new_worker_id).texit_mod = tmod; - FOREIGN_ThreadHandle(new_worker_id).texit = + REMOTE_ThreadHandle(new_worker_id).texit_mod = tmod; + REMOTE_ThreadHandle(new_worker_id).texit = Yap_StoreTermInDB(tgoal,7); return TRUE; } @@ -123,11 +122,11 @@ static void kill_thread_engine (int wid, int always_die) { CACHE_REGS - Prop p0 = AbsPredProp(FOREIGN_ThreadHandle(wid).local_preds); - GlobalEntry *gl = GlobalVariables; + Prop p0 = AbsPredProp(REMOTE_ThreadHandle(wid).local_preds); + GlobalEntry *gl = LOCAL_GlobalVariables; - FOREIGN_ThreadHandle(wid).local_preds = NIL; - GlobalVariables = NULL; + REMOTE_ThreadHandle(wid).local_preds = NIL; + LOCAL_GlobalVariables = NULL; /* kill all thread local preds */ while(p0) { PredEntry *ap = RepPredProp(p0); @@ -140,22 +139,22 @@ kill_thread_engine (int wid, int always_die) gl = gl->NextGE; } Yap_KillStacks(wid); - FOREIGN(wid)->active_signals = 0L; - free(FOREIGN(wid)->scratchpad.ptr); - free(FOREIGN_ThreadHandle(wid).default_yaam_regs); - FOREIGN_ThreadHandle(wid).current_yaam_regs = NULL; - free(FOREIGN_ThreadHandle(wid).start_of_timesp); - free(FOREIGN_ThreadHandle(wid).last_timep); - Yap_FreeCodeSpace((ADDR)FOREIGN_ThreadHandle(wid).texit); - LOCK(Yap_ThreadHandlesLock); - if (FOREIGN_ThreadHandle(wid).tdetach == MkAtomTerm(AtomTrue) || + REMOTE_ActiveSignals(wid) = 0L; + free(REMOTE_ScratchPad(wid).ptr); + free(REMOTE_ThreadHandle(wid).default_yaam_regs); + REMOTE_ThreadHandle(wid).current_yaam_regs = NULL; + free(REMOTE_ThreadHandle(wid).start_of_timesp); + free(REMOTE_ThreadHandle(wid).last_timep); + Yap_FreeCodeSpace((ADDR)REMOTE_ThreadHandle(wid).texit); + LOCK(GLOBAL_ThreadHandlesLock); + if (REMOTE_ThreadHandle(wid).tdetach == MkAtomTerm(AtomTrue) || always_die) { - FOREIGN_ThreadHandle(wid).zombie = FALSE; - FOREIGN_ThreadHandle(wid).in_use = FALSE; + REMOTE_ThreadHandle(wid).zombie = FALSE; + REMOTE_ThreadHandle(wid).in_use = FALSE; DEBUG_TLOCK_ACCESS(1, wid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(wid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(wid).tlock)); } - UNLOCK(Yap_ThreadHandlesLock); + UNLOCK(GLOBAL_ThreadHandlesLock); } static void @@ -163,7 +162,7 @@ thread_die(int wid, int always_die) { if (!always_die) { /* called by thread itself */ - Yap_ThreadsTotalTime += Yap_cputime(); + GLOBAL_ThreadsTotalTime += Yap_cputime(); } kill_thread_engine(wid, always_die); } @@ -177,26 +176,21 @@ setup_engine(int myworker_id, int init_thread) standard_regs = (REGSTORE *)calloc(1,sizeof(REGSTORE)); regcache = standard_regs; /* create the YAAM descriptor */ - FOREIGN_ThreadHandle(myworker_id).default_yaam_regs = standard_regs; + REMOTE_ThreadHandle(myworker_id).default_yaam_regs = standard_regs; if (init_thread) { - pthread_setspecific(Yap_yaamregs_key, (void *)FOREIGN_ThreadHandle(myworker_id).default_yaam_regs); + pthread_setspecific(Yap_yaamregs_key, (void *)REMOTE_ThreadHandle(myworker_id).default_yaam_regs); } worker_id = myworker_id; - Yap_InitExStacks(FOREIGN_ThreadHandle(myworker_id).tsize, FOREIGN_ThreadHandle(myworker_id).ssize); - CurrentModule = FOREIGN_ThreadHandle(myworker_id).cmod; + LOCAL = REMOTE(worker_id); + Yap_InitExStacks(REMOTE_ThreadHandle(myworker_id).tsize, REMOTE_ThreadHandle(myworker_id).ssize); + CurrentModule = REMOTE_ThreadHandle(myworker_id).cmod; Yap_InitTime(); Yap_InitYaamRegs(); -#ifdef YAPOR - Yap_init_local(); -#endif -#ifdef TABLING - new_dependency_frame(REMOTE_top_dep_fr(myworker_id)), FALSE, NULL, NULL, NULL, NULL, NULL); -#endif Yap_ReleasePreAllocCodeSpace(Yap_PreAllocCodeSpace()); /* I exist */ - Yap_NOfThreadsCreated++; + GLOBAL_NOfThreadsCreated++; DEBUG_TLOCK_ACCESS(2, myworker_id); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(myworker_id).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(myworker_id).tlock)); } static void @@ -216,27 +210,27 @@ thread_run(void *widp) start_thread(myworker_id); regcache = ((REGSTORE *)pthread_getspecific(Yap_yaamregs_key)); do { - t = tgs[0] = Yap_PopTermFromDB(MY_ThreadHandle.tgoal); + t = tgs[0] = Yap_PopTermFromDB(LOCAL_ThreadHandle.tgoal); if (t == 0) { - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); thread_die(worker_id, FALSE); return NULL; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_growstack(MY_ThreadHandle.tgoal->NOfCells*CellSize)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_growstack(LOCAL_ThreadHandle.tgoal->NOfCells*CellSize)) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); thread_die(worker_id, FALSE); return NULL; } } } } while (t == 0); - FOREIGN_ThreadHandle(myworker_id).tgoal = NULL; - tgs[1] = MY_ThreadHandle.tdetach; + REMOTE_ThreadHandle(myworker_id).tgoal = NULL; + tgs[1] = LOCAL_ThreadHandle.tdetach; tgoal = Yap_MkApplTerm(FunctorThreadRun, 2, tgs); Yap_RunTopGoal(tgoal); thread_die(worker_id, FALSE); @@ -287,10 +281,10 @@ p_create_thread( USES_REGS1 ) /* make sure we can proceed */ if (!init_thread_engine(new_worker_id, ssize, tsize, sysize, &ARG1, &ARG5, &ARG6)) return FALSE; - FOREIGN_ThreadHandle(new_worker_id).pthread_handle = 0L; - FOREIGN_ThreadHandle(new_worker_id).id = new_worker_id; - FOREIGN_ThreadHandle(new_worker_id).ref_count = 1; - if ((FOREIGN_ThreadHandle(new_worker_id).ret = pthread_create(&FOREIGN_ThreadHandle(new_worker_id).pthread_handle, NULL, thread_run, (void *)(&(FOREIGN_ThreadHandle(new_worker_id).id)))) == 0) { + REMOTE_ThreadHandle(new_worker_id).pthread_handle = 0L; + REMOTE_ThreadHandle(new_worker_id).id = new_worker_id; + REMOTE_ThreadHandle(new_worker_id).ref_count = 1; + if ((REMOTE_ThreadHandle(new_worker_id).ret = pthread_create(&REMOTE_ThreadHandle(new_worker_id).pthread_handle, NULL, thread_run, (void *)(&(REMOTE_ThreadHandle(new_worker_id).id)))) == 0) { /* wait until the client is initialised */ return TRUE; } @@ -348,15 +342,15 @@ p_thread_zombie_self( USES_REGS1 ) if (pthread_getspecific(Yap_yaamregs_key) == NULL) return Yap_unify(MkIntegerTerm(-1), ARG1); DEBUG_TLOCK_ACCESS(4, worker_id); - pthread_mutex_lock(&(MY_ThreadHandle.tlock)); - if (ActiveSignals &= YAP_ITI_SIGNAL) { + pthread_mutex_lock(&(LOCAL_ThreadHandle.tlock)); + if (LOCAL_ActiveSignals &= YAP_ITI_SIGNAL) { DEBUG_TLOCK_ACCESS(5, worker_id); - pthread_mutex_unlock(&(MY_ThreadHandle.tlock)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock)); return FALSE; } // fprintf(stderr," -- %d\n", worker_id); - MY_ThreadHandle.in_use = FALSE; - MY_ThreadHandle.zombie = TRUE; + LOCAL_ThreadHandle.in_use = FALSE; + LOCAL_ThreadHandle.zombie = TRUE; return Yap_unify(MkIntegerTerm(worker_id), ARG1); } @@ -366,7 +360,7 @@ p_thread_status_lock( USES_REGS1 ) /* make sure the lock is available */ if (pthread_getspecific(Yap_yaamregs_key) == NULL) return FALSE; - pthread_mutex_lock(&(MY_ThreadHandle.tlock_status)); + pthread_mutex_lock(&(LOCAL_ThreadHandle.tlock_status)); return Yap_unify(MkIntegerTerm(worker_id), ARG1); } @@ -376,7 +370,7 @@ p_thread_status_unlock( USES_REGS1 ) /* make sure the lock is available */ if (pthread_getspecific(Yap_yaamregs_key) == NULL) return FALSE; - pthread_mutex_unlock(&(MY_ThreadHandle.tlock_status)); + pthread_mutex_unlock(&(LOCAL_ThreadHandle.tlock_status)); return Yap_unify(MkIntegerTerm(worker_id), ARG1); } @@ -411,20 +405,20 @@ Yap_thread_create_engine(thread_attr *ops) ops->sysize = 0; ops->egoal = t; } - if (pthread_self() != Yap_master_thread) { + if (pthread_self() != GLOBAL_master_thread) { /* we are worker_id 0 for now, lock master thread so that no one messes with us */ pthread_setspecific(Yap_yaamregs_key, (const void *)&Yap_standard_regs); - pthread_mutex_lock(&(FOREIGN_ThreadHandle(0).tlock)); + pthread_mutex_lock(&(REMOTE_ThreadHandle(0).tlock)); } if (!init_thread_engine(new_id, ops->ssize, ops->tsize, ops->sysize, &t, &t, &(ops->egoal))) return -1; - FOREIGN_ThreadHandle(new_id).pthread_handle = 0L; - FOREIGN_ThreadHandle(new_id).id = new_id; - FOREIGN_ThreadHandle(new_id).ref_count = 0; + REMOTE_ThreadHandle(new_id).pthread_handle = 0L; + REMOTE_ThreadHandle(new_id).id = new_id; + REMOTE_ThreadHandle(new_id).ref_count = 0; setup_engine(new_id, FALSE); - if (pthread_self() != Yap_master_thread) { + if (pthread_self() != GLOBAL_master_thread) { pthread_setspecific(Yap_yaamregs_key, NULL); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(0).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(0).tlock)); } return new_id; } @@ -435,21 +429,21 @@ Yap_thread_attach_engine(int wid) CACHE_REGS /* already locked - pthread_mutex_lock(&(FOREIGN_ThreadHandle(wid).tlock)); + pthread_mutex_lock(&(REMOTE_ThreadHandle(wid).tlock)); */ - if (FOREIGN_ThreadHandle(wid).ref_count ) { + if (REMOTE_ThreadHandle(wid).ref_count ) { DEBUG_TLOCK_ACCESS(8, wid); - FOREIGN_ThreadHandle(wid).ref_count++; - FOREIGN_ThreadHandle(wid).pthread_handle = pthread_self(); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(wid).tlock)); + REMOTE_ThreadHandle(wid).ref_count++; + REMOTE_ThreadHandle(wid).pthread_handle = pthread_self(); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(wid).tlock)); return TRUE; } - FOREIGN_ThreadHandle(wid).pthread_handle = pthread_self(); - FOREIGN_ThreadHandle(wid).ref_count++; - pthread_setspecific(Yap_yaamregs_key, (const void *)FOREIGN_ThreadHandle(wid).default_yaam_regs); - worker_id = wid; + REMOTE_ThreadHandle(wid).pthread_handle = pthread_self(); + REMOTE_ThreadHandle(wid).ref_count++; + pthread_setspecific(Yap_yaamregs_key, (const void *)REMOTE_ThreadHandle(wid).default_yaam_regs); + worker_id = wid; /* ricroc: for what I understand, this shouldn't be necessary */ DEBUG_TLOCK_ACCESS(9, wid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(wid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(wid).tlock)); return TRUE; } @@ -457,12 +451,12 @@ Int Yap_thread_detach_engine(int wid) { DEBUG_TLOCK_ACCESS(10, wid); - pthread_mutex_lock(&(FOREIGN_ThreadHandle(wid).tlock)); - FOREIGN_ThreadHandle(wid).pthread_handle = 0; - FOREIGN_ThreadHandle(wid).ref_count--; + pthread_mutex_lock(&(REMOTE_ThreadHandle(wid).tlock)); + REMOTE_ThreadHandle(wid).pthread_handle = 0; + REMOTE_ThreadHandle(wid).ref_count--; pthread_setspecific(Yap_yaamregs_key, NULL); DEBUG_TLOCK_ACCESS(11, wid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(wid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(wid).tlock)); return TRUE; } @@ -470,13 +464,13 @@ Int Yap_thread_destroy_engine(int wid) { DEBUG_TLOCK_ACCESS(10, wid); - pthread_mutex_lock(&(FOREIGN_ThreadHandle(wid).tlock)); - if (FOREIGN_ThreadHandle(wid).ref_count == 0) { + pthread_mutex_lock(&(REMOTE_ThreadHandle(wid).tlock)); + if (REMOTE_ThreadHandle(wid).ref_count == 0) { kill_thread_engine(wid, TRUE); return TRUE; } else { DEBUG_TLOCK_ACCESS(12, wid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(wid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(wid).tlock)); return FALSE; } } @@ -487,19 +481,19 @@ p_thread_join( USES_REGS1 ) { Int tid = IntegerOfTerm(Deref(ARG1)); - LOCK(Yap_ThreadHandlesLock); - if (!FOREIGN_ThreadHandle(tid).in_use && - !FOREIGN_ThreadHandle(tid).zombie) { - UNLOCK(Yap_ThreadHandlesLock); + LOCK(GLOBAL_ThreadHandlesLock); + if (!REMOTE_ThreadHandle(tid).in_use && + !REMOTE_ThreadHandle(tid).zombie) { + UNLOCK(GLOBAL_ThreadHandlesLock); return FALSE; } - if (!FOREIGN_ThreadHandle(tid).tdetach == MkAtomTerm(AtomTrue)) { - UNLOCK(Yap_ThreadHandlesLock); + if (!REMOTE_ThreadHandle(tid).tdetach == MkAtomTerm(AtomTrue)) { + UNLOCK(GLOBAL_ThreadHandlesLock); return FALSE; } - UNLOCK(Yap_ThreadHandlesLock); + UNLOCK(GLOBAL_ThreadHandlesLock); /* make sure this lock is accessible */ - if (pthread_join(FOREIGN_ThreadHandle(tid).pthread_handle, NULL) < 0) { + if (pthread_join(REMOTE_ThreadHandle(tid).pthread_handle, NULL) < 0) { /* ERROR */ return FALSE; } @@ -512,12 +506,12 @@ p_thread_destroy( USES_REGS1 ) { Int tid = IntegerOfTerm(Deref(ARG1)); - LOCK(Yap_ThreadHandlesLock); - FOREIGN_ThreadHandle(tid).zombie = FALSE; - FOREIGN_ThreadHandle(tid).in_use = FALSE; + LOCK(GLOBAL_ThreadHandlesLock); + REMOTE_ThreadHandle(tid).zombie = FALSE; + REMOTE_ThreadHandle(tid).in_use = FALSE; DEBUG_TLOCK_ACCESS(32, tid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(tid).tlock)); - UNLOCK(Yap_ThreadHandlesLock); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(tid).tlock)); + UNLOCK(GLOBAL_ThreadHandlesLock); return TRUE; } @@ -525,26 +519,26 @@ static Int p_thread_detach( USES_REGS1 ) { Int tid = IntegerOfTerm(Deref(ARG1)); - pthread_mutex_lock(&(FOREIGN_ThreadHandle(tid).tlock)); + pthread_mutex_lock(&(REMOTE_ThreadHandle(tid).tlock)); DEBUG_TLOCK_ACCESS(14, tid); - if (pthread_detach(FOREIGN_ThreadHandle(tid).pthread_handle) < 0) { + if (pthread_detach(REMOTE_ThreadHandle(tid).pthread_handle) < 0) { /* ERROR */ DEBUG_TLOCK_ACCESS(15, tid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(tid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(tid).tlock)); return FALSE; } - FOREIGN_ThreadHandle(tid).tdetach = + REMOTE_ThreadHandle(tid).tdetach = MkAtomTerm(AtomTrue); DEBUG_TLOCK_ACCESS(30, tid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(tid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(tid).tlock)); return TRUE; } static Int p_thread_detached( USES_REGS1 ) { - if (MY_ThreadHandle.tdetach) - return Yap_unify(ARG1,MY_ThreadHandle.tdetach); + if (LOCAL_ThreadHandle.tdetach) + return Yap_unify(ARG1,LOCAL_ThreadHandle.tdetach); else return FALSE; } @@ -553,8 +547,8 @@ static Int p_thread_detached2( USES_REGS1 ) { Int tid = IntegerOfTerm(Deref(ARG1)); - if (FOREIGN_ThreadHandle(tid).tdetach) - return Yap_unify(ARG2,FOREIGN_ThreadHandle(tid).tdetach); + if (REMOTE_ThreadHandle(tid).tdetach) + return Yap_unify(ARG2,REMOTE_ThreadHandle(tid).tdetach); else return FALSE; } @@ -602,7 +596,7 @@ static Int p_valid_thread( USES_REGS1 ) { Int i = IntegerOfTerm(Deref(ARG1)); - return FOREIGN_ThreadHandle(i).in_use || FOREIGN_ThreadHandle(i).zombie; + return REMOTE_ThreadHandle(i).in_use || REMOTE_ThreadHandle(i).zombie; } /* Mutex Support */ @@ -753,16 +747,16 @@ p_thread_stacks( USES_REGS1 ) Int tid = IntegerOfTerm(Deref(ARG1)); Int status= TRUE; - LOCK(Yap_ThreadHandlesLock); - if (!FOREIGN_ThreadHandle(tid).in_use && - !FOREIGN_ThreadHandle(tid).zombie) { - UNLOCK(Yap_ThreadHandlesLock); + LOCK(GLOBAL_ThreadHandlesLock); + if (!REMOTE_ThreadHandle(tid).in_use && + !REMOTE_ThreadHandle(tid).zombie) { + UNLOCK(GLOBAL_ThreadHandlesLock); return FALSE; } - status &= Yap_unify(ARG2,MkIntegerTerm(FOREIGN_ThreadHandle(tid).ssize)); - status &= Yap_unify(ARG3,MkIntegerTerm(FOREIGN_ThreadHandle(tid).tsize)); - status &= Yap_unify(ARG4,MkIntegerTerm(FOREIGN_ThreadHandle(tid).sysize)); - UNLOCK(Yap_ThreadHandlesLock); + status &= Yap_unify(ARG2,MkIntegerTerm(REMOTE_ThreadHandle(tid).ssize)); + status &= Yap_unify(ARG3,MkIntegerTerm(REMOTE_ThreadHandle(tid).tsize)); + status &= Yap_unify(ARG4,MkIntegerTerm(REMOTE_ThreadHandle(tid).sysize)); + UNLOCK(GLOBAL_ThreadHandlesLock); return status; } @@ -771,32 +765,32 @@ p_thread_atexit( USES_REGS1 ) { /* '$thread_signal'(+P) */ Term t; - if (!MY_ThreadHandle.texit || - MY_ThreadHandle.texit->Entry == MkAtomTerm(AtomTrue)) { + if (!LOCAL_ThreadHandle.texit || + LOCAL_ThreadHandle.texit->Entry == MkAtomTerm(AtomTrue)) { return FALSE; } do { - t = Yap_PopTermFromDB(MY_ThreadHandle.texit); - MY_ThreadHandle.texit = NULL; + t = Yap_PopTermFromDB(LOCAL_ThreadHandle.texit); + LOCAL_ThreadHandle.texit = NULL; if (t == 0) { - if (Yap_Error_TYPE == OUT_OF_ATTVARS_ERROR) { - Yap_Error_TYPE = YAP_NO_ERROR; + if (LOCAL_Error_TYPE == OUT_OF_ATTVARS_ERROR) { + LOCAL_Error_TYPE = YAP_NO_ERROR; if (!Yap_growglobal(NULL)) { - Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_ATTVARS_ERROR, TermNil, LOCAL_ErrorMessage); thread_die(worker_id, FALSE); return FALSE; } } else { - Yap_Error_TYPE = YAP_NO_ERROR; - if (!Yap_growstack(MY_ThreadHandle.tgoal->NOfCells*CellSize)) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + LOCAL_Error_TYPE = YAP_NO_ERROR; + if (!Yap_growstack(LOCAL_ThreadHandle.tgoal->NOfCells*CellSize)) { + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); thread_die(worker_id, FALSE); return FALSE; } } } } while (t == 0); - return Yap_unify(ARG1, t) && Yap_unify(ARG2, MY_ThreadHandle.texit_mod); + return Yap_unify(ARG1, t) && Yap_unify(ARG2, LOCAL_ThreadHandle.texit_mod); } @@ -806,21 +800,21 @@ p_thread_signal( USES_REGS1 ) { /* '$thread_signal'(+P) */ Int wid = IntegerOfTerm(Deref(ARG1)); /* make sure the lock is available */ - pthread_mutex_lock(&(FOREIGN_ThreadHandle(wid).tlock)); + pthread_mutex_lock(&(REMOTE_ThreadHandle(wid).tlock)); DEBUG_TLOCK_ACCESS(16, wid); - if (!FOREIGN_ThreadHandle(wid).in_use || - !FOREIGN_ThreadHandle(wid).current_yaam_regs) { + if (!REMOTE_ThreadHandle(wid).in_use || + !REMOTE_ThreadHandle(wid).current_yaam_regs) { DEBUG_TLOCK_ACCESS(17, wid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(wid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(wid).tlock)); return TRUE; } - LOCK(FOREIGN(wid)->signal_lock); - FOREIGN_ThreadHandle(wid).current_yaam_regs->CreepFlag_ = - Unsigned(FOREIGN_ThreadHandle(wid).current_yaam_regs->LCL0_); - FOREIGN(wid)->active_signals |= YAP_ITI_SIGNAL; - UNLOCK(FOREIGN(wid)->signal_lock); + LOCK(REMOTE_SignalLock(wid)); + REMOTE_ThreadHandle(wid).current_yaam_regs->CreepFlag_ = + Unsigned(REMOTE_ThreadHandle(wid).current_yaam_regs->LCL0_); + REMOTE_ActiveSignals(wid) |= YAP_ITI_SIGNAL; + UNLOCK(REMOTE_SignalLock(wid)); DEBUG_TLOCK_ACCESS(18, wid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(wid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(wid).tlock)); return TRUE; } @@ -834,13 +828,13 @@ static Int p_nof_threads( USES_REGS1 ) { /* '$nof_threads'(+P) */ int i = 0, wid; - LOCK(Yap_ThreadHandlesLock); + LOCK(GLOBAL_ThreadHandlesLock); for (wid = 0; wid < MAX_THREADS; wid++) { - if (!Yap_WLocal[wid]) break; - if (FOREIGN_ThreadHandle(wid).in_use) + if (!Yap_local[wid]) break; + if (REMOTE_ThreadHandle(wid).in_use) i++; } - UNLOCK(Yap_ThreadHandlesLock); + UNLOCK(GLOBAL_ThreadHandlesLock); return Yap_unify(ARG1,MkIntegerTerm(i)); } @@ -859,19 +853,19 @@ p_max_threads( USES_REGS1 ) static Int p_nof_threads_created( USES_REGS1 ) { /* '$nof_threads'(+P) */ - return Yap_unify(ARG1,MkIntTerm(Yap_NOfThreadsCreated)); + return Yap_unify(ARG1,MkIntTerm(GLOBAL_NOfThreadsCreated)); } static Int p_thread_runtime( USES_REGS1 ) { /* '$thread_runtime'(+P) */ - return Yap_unify(ARG1,MkIntegerTerm(Yap_ThreadsTotalTime)); + return Yap_unify(ARG1,MkIntegerTerm(GLOBAL_ThreadsTotalTime)); } static Int p_thread_self_lock( USES_REGS1 ) { /* '$thread_unlock' */ - pthread_mutex_lock(&(MY_ThreadHandle.tlock)); + pthread_mutex_lock(&(LOCAL_ThreadHandle.tlock)); return Yap_unify(ARG1,MkIntegerTerm(worker_id)); } @@ -880,7 +874,7 @@ p_thread_unlock( USES_REGS1 ) { /* '$thread_unlock' */ Int wid = IntegerOfTerm(Deref(ARG1)); DEBUG_TLOCK_ACCESS(19, wid); - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(wid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(wid).tlock)); return TRUE; } diff --git a/C/tracer.c b/C/tracer.c index 98c433b00..36f0094b1 100755 --- a/C/tracer.c +++ b/C/tracer.c @@ -28,12 +28,12 @@ STATIC_PROTO(int TracePutchar, (int, int)); STATIC_PROTO(void send_tracer_message, (char *, char *, Int, char *, CELL *)); -static int do_trace_primitives = TRUE; + static int TracePutchar(int sno, int ch) { - return(putc(ch, Yap_stderr)); /* use standard error stream, which is supposed to be 2*/ + return(putc(ch, GLOBAL_stderr)); /* use standard error stream, which is supposed to be 2*/ } static void @@ -42,24 +42,24 @@ send_tracer_message(char *start, char *name, Int arity, char *mname, CELL *args) CACHE_REGS if (name == NULL) { #ifdef YAPOR - fprintf(Yap_stderr, "(%d)%s", worker_id, start); + fprintf(GLOBAL_stderr, "(%d)%s", worker_id, start); #else - fprintf(Yap_stderr, "%s", start); + fprintf(GLOBAL_stderr, "%s", start); #endif } else { int i; if (arity) { if (args) - fprintf(Yap_stderr, "%s %s:%s(", start, mname, name); + fprintf(GLOBAL_stderr, "%s %s:%s(", start, mname, name); else - fprintf(Yap_stderr, "%s %s:%s/%lu", start, mname, name, (unsigned long int)arity); + fprintf(GLOBAL_stderr, "%s %s:%s/%lu", start, mname, name, (unsigned long int)arity); } else { - fprintf(Yap_stderr, "%s %s:%s", start, mname, name); + fprintf(GLOBAL_stderr, "%s %s:%s", start, mname, name); } if (args) { for (i= 0; i < arity; i++) { - if (i > 0) fprintf(Yap_stderr, ","); + if (i > 0) fprintf(GLOBAL_stderr, ","); #if DEBUG #if COROUTINING Yap_Portray_delays = TRUE; @@ -73,11 +73,11 @@ send_tracer_message(char *start, char *name, Int arity, char *mname, CELL *args) #endif } if (arity) { - fprintf(Yap_stderr, ")"); + fprintf(GLOBAL_stderr, ")"); } } } - fprintf(Yap_stderr, "\n"); + fprintf(GLOBAL_stderr, "\n"); } #if defined(__GNUC__) @@ -94,7 +94,7 @@ static int thread_trace; static int check_trail_consistency(void) { tr_fr_ptr ptr = TR; - while (ptr > (CELL *)Yap_TrailBase) { + while (ptr > (CELL *)LOCAL_TrailBase) { ptr = --ptr; if (!IsVarTerm(TrailTerm(ptr))) { if (IsApplTerm(TrailTerm(ptr))) { @@ -164,7 +164,7 @@ low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) sc = Yap_heap_regs; vsc_count++; #ifdef THREADS - MY_ThreadHandle.thread_inst_count++; + LOCAL_ThreadHandle.thread_inst_count++; #endif #ifdef COMMENTED { choiceptr myB = B; @@ -186,7 +186,7 @@ low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) } else return; { - tr_fr_ptr pt = (tr_fr_ptr)Yap_TrailBase; + tr_fr_ptr pt = (tr_fr_ptr)LOCAL_TrailBase; if (pt[140].term == 0 && pt[140].value != 0) jmp_deb(1); } @@ -235,7 +235,7 @@ low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) if (TR_FZ > TR) jmp_deb(1); { - tr_fr_ptr pt = (tr_fr_ptr)Yap_TrailBase; + tr_fr_ptr pt = (tr_fr_ptr)LOCAL_TrailBase; if (pt[153].term == 0 && pt[153].value == 0 && pt[154].term != 0 && pt[154].value != 0 && ( TR > pt+154 || TR_FZ > pt+154)) @@ -293,16 +293,16 @@ low_level_trace(yap_low_level_port port, PredEntry *pred, CELL *args) printf("\n"); } #endif - fprintf(Yap_stderr,"%lld ",vsc_count); + fprintf(GLOBAL_stderr,"%lld ",vsc_count); #if defined(THREADS) || defined(YAPOR) - fprintf(Yap_stderr,"(%d)", worker_id); + fprintf(GLOBAL_stderr,"(%d)", worker_id); #endif /* check_trail_consistency(); */ if (pred == NULL) { UNLOCK(Yap_heap_regs->low_level_trace_lock); return; } - if (pred->ModuleOfPred == 0 && !do_trace_primitives) { + if (pred->ModuleOfPred == 0 && !LOCAL_do_trace_primitives) { UNLOCK(Yap_heap_regs->low_level_trace_lock); return; } @@ -396,12 +396,12 @@ static Int p_start_low_level_trace( USES_REGS1 ) static Int p_total_choicepoints( USES_REGS1 ) { - return Yap_unify(MkIntegerTerm(Yap_total_choicepoints),ARG1); + return Yap_unify(MkIntegerTerm(LOCAL_total_choicepoints),ARG1); } static Int p_reset_total_choicepoints( USES_REGS1 ) { - Yap_total_choicepoints = 0; + LOCAL_total_choicepoints = 0; return TRUE; } @@ -425,7 +425,7 @@ static Int p_start_low_level_trace2( USES_REGS1 ) static Int p_stop_low_level_trace( USES_REGS1 ) { Yap_do_low_level_trace = FALSE; - do_trace_primitives = TRUE; + LOCAL_do_trace_primitives = TRUE; return(TRUE); } diff --git a/C/utilpreds.c b/C/utilpreds.c index 8684cc32c..37f763193 100644 --- a/C/utilpreds.c +++ b/C/utilpreds.c @@ -244,7 +244,7 @@ copy_complex_term(CELL *pt0, CELL *pt0_end, int share, int newattvs, CELL *ptf, CELL new; bp = to_visit; - if (!attas[ExtFromCell(ptd0)].copy_term_op(ptd0, &bp, ptf PASS_REGS)) { + if (!GLOBAL_attas[ExtFromCell(ptd0)].copy_term_op(ptd0, &bp, ptf PASS_REGS)) { goto overflow; } to_visit = bp; @@ -255,7 +255,7 @@ copy_complex_term(CELL *pt0, CELL *pt0_end, int share, int newattvs, CELL *ptf, #endif /* first time we met this term */ RESET_VARIABLE(ptf); - if (TR > (tr_fr_ptr)Yap_TrailTop - 256) { + if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) { /* Trail overflow */ if (!Yap_growtrail((TR-TR0)*sizeof(tr_fr_ptr *), TRUE)) { goto trail_overflow; @@ -355,7 +355,7 @@ trail_overflow: } #endif reset_trail(TR0); - Yap_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0; + LOCAL_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0; return -3; } @@ -368,7 +368,7 @@ handle_cp_overflow(int res, tr_fr_ptr TR0, UInt arity, Term t) switch(res) { case -1: if (!Yap_gcl((ASP-H)*sizeof(CELL), arity+1, ENV, gc_P(P,CP))) { - Yap_Error(OUT_OF_STACK_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_STACK_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } return Deref(XREGS[arity+1]); @@ -376,19 +376,19 @@ handle_cp_overflow(int res, tr_fr_ptr TR0, UInt arity, Term t) return Deref(XREGS[arity+1]); case -3: { - UInt size = Yap_Error_Size; - Yap_Error_Size = 0L; + UInt size = LOCAL_Error_Size; + LOCAL_Error_Size = 0L; if (size > 4*1024*1024) size = 4*1024*1024; if (!Yap_ExpandPreAllocCodeSpace(size, NULL, TRUE)) { - Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_AUXSPACE_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } } return Deref(XREGS[arity+1]); case -4: if (!Yap_growtrail((TR-TR0)*sizeof(tr_fr_ptr *), FALSE)) { - Yap_Error(OUT_OF_TRAIL_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_TRAIL_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } return Deref(XREGS[arity+1]); @@ -751,7 +751,7 @@ break_rationals_complex_term(CELL *pt0, CELL *pt0_end, CELL *ptf, CELL *HLow USE } #endif reset_trail(TR0); - Yap_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0; + LOCAL_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0; return -3; } @@ -1066,7 +1066,7 @@ restore_rationals_complex_term(CELL *pt0, CELL *pt0_end, CELL *ptf, CELL *HLow, } #endif reset_trail(TR0); - Yap_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0; + LOCAL_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0; return -3; } @@ -1400,7 +1400,7 @@ export_complex_term(Term tf, CELL *pt0, CELL *pt0_end, char * buf, size_t len0, CELL new; bp = to_visit; - if (!attas[ExtFromCell(ptd0)].copy_term_op(ptd0, &bp, ptf PASS_REGS)) { + if (!GLOBAL_attas[ExtFromCell(ptd0)].copy_term_op(ptd0, &bp, ptf PASS_REGS)) { goto overflow; } to_visit = bp; @@ -1411,7 +1411,7 @@ export_complex_term(Term tf, CELL *pt0, CELL *pt0_end, char * buf, size_t len0, #endif /* first time we met this term */ *ptf = (CELL)CellDifH(ptf,HLow); - if (TR > (tr_fr_ptr)Yap_TrailTop - 256) { + if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) { /* Trail overflow */ if (!Yap_growtrail((TR-TR0)*sizeof(tr_fr_ptr *), TRUE)) { goto trail_overflow; @@ -1501,7 +1501,7 @@ trail_overflow: } #endif reset_trail(TR0); - Yap_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0; + LOCAL_Error_Size = (ADDR)AuxSp-(ADDR)to_visit0; return -3; } @@ -1749,7 +1749,7 @@ static Term vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, Ter H += 2; H[-2] = (CELL)ptd0; /* next make sure noone will see this as a variable again */ - if (TR > (tr_fr_ptr)Yap_TrailTop - 256) { + if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) { /* Trail overflow */ if (!Yap_growtrail((TR-TR0)*sizeof(tr_fr_ptr *), TRUE)) { goto trail_overflow; @@ -1796,15 +1796,15 @@ static Term vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, Ter *pt0 = (CELL)to_visit[2]; } #endif - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; - Yap_Error_Size = (TR-TR0)*sizeof(tr_fr_ptr *); + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_Error_Size = (TR-TR0)*sizeof(tr_fr_ptr *); clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; return 0L; aux_overflow: - Yap_Error_Size = (to_visit-to_visit0)*sizeof(CELL **); + LOCAL_Error_Size = (to_visit-to_visit0)*sizeof(CELL **); #ifdef RATIONAL_TREES while (to_visit > to_visit0) { to_visit -= 3; @@ -1812,7 +1812,7 @@ static Term vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, Ter *pt0 = (CELL)to_visit[2]; } #endif - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; @@ -1829,8 +1829,8 @@ static Term vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, Ter clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; - Yap_Error_TYPE = OUT_OF_STACK_ERROR; - Yap_Error_Size = (ASP-H)*sizeof(CELL); + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Size = (ASP-H)*sizeof(CELL); return 0L; } @@ -1838,11 +1838,11 @@ static Term vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, Ter static int expand_vts( USES_REGS1 ) { - UInt expand = Yap_Error_Size; - yap_error_number yap_errno = Yap_Error_TYPE; + UInt expand = LOCAL_Error_Size; + yap_error_number yap_errno = LOCAL_Error_TYPE; - Yap_Error_Size = 0; - Yap_Error_TYPE = YAP_NO_ERROR; + LOCAL_Error_Size = 0; + LOCAL_Error_TYPE = YAP_NO_ERROR; if (yap_errno == OUT_OF_TRAIL_ERROR) { /* Trail overflow */ if (!Yap_growtrail(expand, FALSE)) { @@ -1881,7 +1881,7 @@ p_variables_in_term( USES_REGS1 ) /* variables in term t */ *ptr = TermFoundVar; TrailTerm(TR++) = t; count++; - if (TR > (tr_fr_ptr)Yap_TrailTop - 256) { + if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) { clean_tr(TR-count PASS_REGS); if (!Yap_growtrail(count*sizeof(tr_fr_ptr *), FALSE)) { return FALSE; @@ -2032,7 +2032,7 @@ static Term attvars_in_complex_term(register CELL *pt0, register CELL *pt0_end, /* do or pt2 are unbound */ *ptd0 = TermNil; /* next make sure noone will see this as a variable again */ - if (TR > (tr_fr_ptr)Yap_TrailTop - 256) { + if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) { /* Trail overflow */ if (!Yap_growtrail((TR-TR0)*sizeof(tr_fr_ptr *), TRUE)) { goto trail_overflow; @@ -2106,15 +2106,15 @@ static Term attvars_in_complex_term(register CELL *pt0, register CELL *pt0_end, *pt0 = (CELL)to_visit[2]; } #endif - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; - Yap_Error_Size = (TR-TR0)*sizeof(tr_fr_ptr *); + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_Error_Size = (TR-TR0)*sizeof(tr_fr_ptr *); clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; return 0L; aux_overflow: - Yap_Error_Size = (to_visit-to_visit0)*sizeof(CELL **); + LOCAL_Error_Size = (to_visit-to_visit0)*sizeof(CELL **); #ifdef RATIONAL_TREES while (to_visit > to_visit0) { to_visit -= 3; @@ -2122,7 +2122,7 @@ static Term attvars_in_complex_term(register CELL *pt0, register CELL *pt0_end, *pt0 = (CELL)to_visit[2]; } #endif - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; @@ -2139,8 +2139,8 @@ static Term attvars_in_complex_term(register CELL *pt0, register CELL *pt0_end, clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; - Yap_Error_TYPE = OUT_OF_STACK_ERROR; - Yap_Error_Size = (ASP-H)*sizeof(CELL); + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Size = (ASP-H)*sizeof(CELL); return 0L; } @@ -2225,7 +2225,7 @@ static Term vars_within_complex_term(register CELL *pt0, register CELL *pt0_end, CELL *ptr = VarOfTerm(t); *ptr = TermFoundVar; TrailTerm(TR++) = t; - if (TR > (tr_fr_ptr)Yap_TrailTop - 256) { + if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) { if (!Yap_growtrail((TR-TR0)*sizeof(tr_fr_ptr *), TRUE)) { goto trail_overflow; } @@ -2338,15 +2338,15 @@ static Term vars_within_complex_term(register CELL *pt0, register CELL *pt0_end, *pt0 = (CELL)to_visit[2]; } #endif - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; - Yap_Error_Size = (TR-TR0)*sizeof(tr_fr_ptr *); + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_Error_Size = (TR-TR0)*sizeof(tr_fr_ptr *); clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; return 0L; aux_overflow: - Yap_Error_Size = (to_visit-to_visit0)*sizeof(CELL **); + LOCAL_Error_Size = (to_visit-to_visit0)*sizeof(CELL **); #ifdef RATIONAL_TREES while (to_visit > to_visit0) { to_visit -= 3; @@ -2354,7 +2354,7 @@ static Term vars_within_complex_term(register CELL *pt0, register CELL *pt0_end, *pt0 = (CELL)to_visit[2]; } #endif - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; @@ -2371,8 +2371,8 @@ static Term vars_within_complex_term(register CELL *pt0, register CELL *pt0_end, clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; - Yap_Error_TYPE = OUT_OF_STACK_ERROR; - Yap_Error_Size = (ASP-H)*sizeof(CELL); + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Size = (ASP-H)*sizeof(CELL); return 0L; } @@ -2422,7 +2422,7 @@ static Term new_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, CELL *ptr = VarOfTerm(t); *ptr = TermFoundVar; TrailTerm(TR++) = t; - if (TR > (tr_fr_ptr)Yap_TrailTop - 256) { + if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) { if (!Yap_growtrail((TR-TR0)*sizeof(tr_fr_ptr *), TRUE)) { goto trail_overflow; } @@ -2503,7 +2503,7 @@ static Term new_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, H += 2; H[-2] = (CELL)ptd0; /* next make sure noone will see this as a variable again */ - if (TR > (tr_fr_ptr)Yap_TrailTop - 256) { + if (TR > (tr_fr_ptr)LOCAL_TrailTop - 256) { /* Trail overflow */ if (!Yap_growtrail((TR-TR0)*sizeof(tr_fr_ptr *), TRUE)) { goto trail_overflow; @@ -2543,15 +2543,15 @@ static Term new_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, *pt0 = (CELL)to_visit[2]; } #endif - Yap_Error_TYPE = OUT_OF_TRAIL_ERROR; - Yap_Error_Size = (TR-TR0)*sizeof(tr_fr_ptr *); + LOCAL_Error_TYPE = OUT_OF_TRAIL_ERROR; + LOCAL_Error_Size = (TR-TR0)*sizeof(tr_fr_ptr *); clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; return 0L; aux_overflow: - Yap_Error_Size = (to_visit-to_visit0)*sizeof(CELL **); + LOCAL_Error_Size = (to_visit-to_visit0)*sizeof(CELL **); #ifdef RATIONAL_TREES while (to_visit > to_visit0) { to_visit -= 3; @@ -2559,7 +2559,7 @@ static Term new_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, *pt0 = (CELL)to_visit[2]; } #endif - Yap_Error_TYPE = OUT_OF_AUXSPACE_ERROR; + LOCAL_Error_TYPE = OUT_OF_AUXSPACE_ERROR; clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; @@ -2576,8 +2576,8 @@ static Term new_vars_in_complex_term(register CELL *pt0, register CELL *pt0_end, clean_tr(TR0 PASS_REGS); Yap_ReleasePreAllocCodeSpace((ADDR)to_visit0); H = InitialH; - Yap_Error_TYPE = OUT_OF_STACK_ERROR; - Yap_Error_Size = (ASP-H)*sizeof(CELL); + LOCAL_Error_TYPE = OUT_OF_STACK_ERROR; + LOCAL_Error_Size = (ASP-H)*sizeof(CELL); return 0L; } diff --git a/C/write.c b/C/write.c index 62137bdb2..0e70abf69 100755 --- a/C/write.c +++ b/C/write.c @@ -85,7 +85,7 @@ STATIC_PROTO(wtype AtomIsSymbols, (unsigned char *)); STATIC_PROTO(void putAtom, (Atom, int, wrf)); STATIC_PROTO(void writeTerm, (Term, int, int, int, struct write_globs *, struct rewind_term *)); -#define wrputc(X,WF) ((*WF)(Yap_c_output_stream,X)) /* writes a character */ +#define wrputc(X,WF) ((*WF)(LOCAL_c_output_stream,X)) /* writes a character */ static void wrputn(Int n, wrf writewch) /* writes an integer */ @@ -149,7 +149,7 @@ ensure_space(size_t sz) { } if (!s) { s = (char *)TR; - while (s+sz >= Yap_TrailTop) { + while (s+sz >= LOCAL_TrailTop) { if (!Yap_growtrail(sz/sizeof(CELL), FALSE)) { s = NULL; break; @@ -746,26 +746,26 @@ writeTerm(Term t, int p, int depth, int rinfixarg, struct write_globs *wglb, str lastw = separator; if (wglb->keep_terms) { /* garbage collection may be called */ - sl = Yap_InitSlot(t); + sl = Yap_InitSlot(t PASS_REGS); } writeTerm(HeadOfTerm(t), 999, depth + 1, FALSE, wglb, &nrwt); restore_from_write(&nrwt, wglb); if (wglb->keep_terms) { /* garbage collection may be called */ - t = Yap_GetFromSlot(sl); - Yap_RecoverSlots(1); + t = Yap_GetFromSlot(sl PASS_REGS); + Yap_RecoverSlots(1 PASS_REGS); } wrputs(",",wglb->writewch); if (wglb->keep_terms) { /* garbage collection may be called */ - sl = Yap_InitSlot(t); + sl = Yap_InitSlot(t PASS_REGS); } writeTerm(TailOfTerm(t), 999, depth + 1, FALSE, wglb, &nrwt); restore_from_write(&nrwt, wglb); if (wglb->keep_terms) { /* garbage collection may be called */ - t = Yap_GetFromSlot(sl); - Yap_RecoverSlots(1); + t = Yap_GetFromSlot(sl PASS_REGS); + Yap_RecoverSlots(1 PASS_REGS); } wrputc(')', wglb->writewch); lastw = separator; diff --git a/H/Regs.h b/H/Regs.h index 388505181..ee9ccb7ed 100644 --- a/H/Regs.h +++ b/H/Regs.h @@ -126,9 +126,10 @@ typedef struct regstore_t #endif /* YAPOR_SBA || TABLING */ struct pred_entry *PP_; #if defined(YAPOR) || defined(THREADS) + unsigned int worker_id_; + struct worker_local *worker_local_; /* recursive write-locks for PredEntry */ yamop **PREG_ADDR_; - unsigned int worker_id_; #ifdef YAPOR_SBA choiceptr BSEG_; struct or_frame *frame_head_, *frame_tail_; @@ -138,9 +139,6 @@ typedef struct regstore_t int sba_size_; #endif /* YAPOR_SBA */ #endif /* YAPOR || THREADS */ -#if defined(YAPOR) || defined(TABLING) - struct local_data *LOCAL_; -#endif #if PUSH_REGS /* On a X86 machine, the best solution is to keep the X registers on a global variable, whose address is known between @@ -210,7 +208,6 @@ extern REGSTORE Yap_REGS; #define MinTrailGap (sizeof(CELL)*1024) #define MinHeapGap (sizeof(CELL)*4096) #define MinStackGap (sizeof(CELL)*8*1024) -extern int Yap_stack_overflows; #define ENV Yap_REGS.ENV_ /* current environment */ @@ -642,8 +639,9 @@ EXTERN inline void restore_B(void) { #endif /* YAPOR_SBA || TABLING */ #define PP (Yap_REGS.PP_) #if defined(YAPOR) || defined(THREADS) -#define worker_id (Yap_REGS.worker_id_) -#define PREG_ADDR (Yap_REGS.PREG_ADDR_) +#define worker_id (Yap_REGS.worker_id_) +#define LOCAL (Yap_REGS.worker_local_) +#define PREG_ADDR (Yap_REGS.PREG_ADDR_) #ifdef YAPOR_SBA #define BSEG Yap_REGS.BSEG_ #define binding_array Yap_REGS.binding_array_ @@ -653,10 +651,9 @@ EXTERN inline void restore_B(void) { #define frame_head Yap_REGS.frame_head_ #define frame_tail Yap_REGS.frame_tail_ #endif /* YAPOR_SBA */ -#endif /* YAPOR */ -#if defined(YAPOR) || defined(TABLING) -#define LOCAL Yap_REGS.LOCAL_ -#endif +#else +#define LOCAL (&Yap_local) +#endif /* YAPOR || THREADS */ #define CurrentModule Yap_REGS.CurrentModule_ #define ARITH_EXCEPTION Yap_REGS.ARITH_EXCEPTION_ #define Yap_isint Yap_REGS.isint_ diff --git a/H/ScannerTypes.h b/H/ScannerTypes.h new file mode 100644 index 000000000..6665b3279 --- /dev/null +++ b/H/ScannerTypes.h @@ -0,0 +1,28 @@ +typedef enum TokenKinds { + Name_tok, + Number_tok, + Var_tok, + String_tok, + WString_tok, + Ponctuation_tok, + Error_tok, + eot_tok +} tkinds; + +typedef struct TOKEN { + enum TokenKinds Tok; + Term TokInfo; + int TokPos; + struct TOKEN *TokNext; +} TokEntry; + +#define Ord(X) ((enum TokenKinds) (X)) + +#define NextToken GNextToken( PASS_REGS1 ) + +typedef struct VARSTRUCT { + Term VarAdr; + CELL hv; + struct VARSTRUCT *VarLeft, *VarRight; + char VarRep[1]; +} VarEntry; diff --git a/H/TermExt.h b/H/TermExt.h index 1f7d7f2a2..4a9d46a2e 100755 --- a/H/TermExt.h +++ b/H/TermExt.h @@ -136,8 +136,7 @@ typedef enum exts; -/* array with the ops for your favourite extensions */ -extern ext_op attas[attvars_ext + 1]; + #endif diff --git a/H/Yap.h b/H/Yap.h index 47079467a..cf0bbb445 100755 --- a/H/Yap.h +++ b/H/Yap.h @@ -45,11 +45,8 @@ /* #define RATIONAL_TREES 1 - #define DEPTH_LIMIT 1 - #define COROUTINING 1 - #define ANALYST 1 */ @@ -73,52 +70,47 @@ #define USE_SYSTEM_MALLOC 1 #endif /* THREADS || SUPPORT_CONDOR */ -#ifdef ANALYST -#ifdef USE_THREADED_CODE +#if defined(ANALYST) && defined(USE_THREADED_CODE) #undef USE_THREADED_CODE -#endif -#endif +#endif /* ANALYST && USE_THREADED_CODE */ -#ifdef COROUTINING -#ifndef TERM_EXTENSIONS +#if defined(COROUTINING) && !defined(TERM_EXTENSIONS) #define TERM_EXTENSIONS 1 -#endif -#endif +#endif /* COROUTINING && !TERM_EXTENSIONS */ -#ifdef _MSC_VER /* Microsoft's Visual C++ Compiler */ -/* adjust a config.h from mingw32 to work with vc++ */ +/* Microsoft's Visual C++ Compiler */ +#ifdef _MSC_VER /* adjust a config.h from mingw32 to work with vc++ */ #ifdef HAVE_GCC -#undef HAVE_GCC -#endif +#undef HAVE_GCC +#endif /* HAVE_GCC */ #ifdef USE_THREADED_CODE #undef USE_THREADED_CODE -#endif +#endif /* USE_THREADED_CODE */ #define inline __inline #define YAP_VERSION "YAP-6.3.0" - #define BIN_DIR "c:\\Yap\\bin" #define LIB_DIR "c:\\Yap\\lib\\Yap" #define SHARE_DIR "c:\\Yap\\share\\Yap" -#ifdef HOST_ALIAS -#undef HOST_ALIAS -#endif +#ifdef HOST_ALIAS +#undef HOST_ALIAS +#endif /* HOST_ALIAS */ #define HOST_ALIAS "i386-pc-win32" -#ifdef HAVE_IEEEFP_H -#undef HAVE_IEEEFP_H -#endif -#ifdef HAVE_UNISTD_H -#undef HAVE_UNISTD_H -#endif -#ifdef HAVE_SYS_TIME_H -#undef HAVE_SYS_TIME_H -#endif -#endif +#ifdef HAVE_IEEEFP_H +#undef HAVE_IEEEFP_H +#endif /* HAVE_IEEEFP_H */ +#ifdef HAVE_UNISTD_H +#undef HAVE_UNISTD_H +#endif /* HAVE_UNISTD_H */ +#ifdef HAVE_SYS_TIME_H +#undef HAVE_SYS_TIME_H +#endif /* HAVE_SYS_TIME_H */ +#endif /* _MSC_VER */ #ifdef __MINGW32__ #ifndef _WIN32 #define _WIN32 1 -#endif -#endif +#endif /* _WIN32 */ +#endif /* __MINGW32__ */ #if HAVE_GCC #define MIN_ARRAY 0 @@ -126,35 +118,36 @@ #else #define MIN_ARRAY 1 #define DUMMY_FILLER_FOR_ABS_TYPE int dummy; -#endif +#endif /* HAVE_GCC */ #ifndef ADTDEFS_C #define EXTERN static #else #define EXTERN -#endif +#endif /* ADTDEFS_C */ -/* truth-values */ +/* truth-values */ #define TRUE 1 #define FALSE 0 -/* null pointer */ + +/* null pointer */ #define NIL 0 + /* Basic types */ /* defines integer types Int and UInt (unsigned) with the same size as a ptr -** and integer types Short and UShort with half the size of a ptr -*/ +** and integer types Short and UShort with half the size of a ptr */ #ifdef THREADS #if USE_PTHREAD_LOCKING #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE 600 -#endif -#endif +#endif /* !_XOPEN_SOURCE */ +#endif /* USE_PTHREAD_LOCKING */ #include -#endif +#endif /* THREADS */ #if SIZEOF_INT_P==4 @@ -173,7 +166,7 @@ #define UInt_FORMAT "%lu" #else -# error Yap require integer types of the same size as a pointer +#error Yap require integer types of the same size as a pointer #endif #if SIZEOF_SHORT_INT==2 @@ -249,16 +242,13 @@ typedef unsigned long int YAP_ULONG_LONG; #define LOW_PROF 1 #endif -#ifdef DEBUG -extern char Yap_Option[20]; -#endif /* #define FORCE_SECOND_QUADRANT 1 */ #if defined(FORCE_SECOND_QUADRANT) #define IN_SECOND_QUADRANT 1 #define MMAP_ADDR 0x42000000 -#endif +#endif /* FORCE_SECOND_QUADRANT */ #if !defined(IN_SECOND_QUADRANT) #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(mips) || defined(__APPLE__) || defined(__DragonFly__) @@ -276,10 +266,10 @@ extern char Yap_Option[20]; #define MMAP_ADDR 0x20000000 #else #define MMAP_ADDR 0x10000000 -#endif +#endif /* YAPOR && __alpha */ #elif __svr4__ || defined(__SVR4) #define MMAP_ADDR 0x02000000 -#endif +#endif /* __linux__ || __FreeBSD__ || __NetBSD__ || mips || __APPLE__ || __DragonFly__ */ #endif /* !IN_SECOND_QUADRANT */ /* #define RANDOMIZE_START_ADDRESS 1 */ @@ -287,15 +277,15 @@ extern char Yap_Option[20]; #ifdef USE_SYSTEM_MALLOC #define HEAP_INIT_BASE 0L #define AtomBase NULL -#else +#else /* !USE_SYSTEM_MALLOC */ #if defined(MMAP_ADDR) && (defined(USE_MMAP) || USE_SHMAT) && !defined(__simplescalar__) && !defined(RANDOMIZE_START_ADDRESS) #define HEAP_INIT_BASE (MMAP_ADDR) #define AtomBase ((char *)MMAP_ADDR) -#else +#else /*! (MMAP_ADDR && (USE_MMAP || USE_SHMAT) && !__simplescalar__ && !RANDOMIZE_START_ADDRESS) */ #define HEAP_INIT_BASE ((CELL)Yap_HeapBase) #define AtomBase (Yap_HeapBase) -#endif -#endif +#endif /* MMAP_ADDR && (USE_MMAP || USE_SHMAT) && !__simplescalar__ && !RANDOMIZE_START_ADDRESS */ +#endif /* USE_SYSTEM_MALLOC */ @@ -315,7 +305,9 @@ extern char Yap_Option[20]; #define M1 ((CELL)(1024*1024)) #define M2 ((CELL)(2048*1024)) -/* basic data types */ +/************************************************************************************************* + basic data types +*************************************************************************************************/ typedef UInt CELL; typedef UShort BITS16; @@ -336,7 +328,9 @@ typedef unsigned char *CODEADDR; #define CellSize sizeof(CELL) #define SmallSize sizeof(SMALLUNSGN) -/* type casting macros */ +/************************************************************************************************* + type casting macros +*************************************************************************************************/ #define Addr(V) ((ADDR) (V)) #define Unsigned(V) ((CELL) (V)) @@ -351,7 +345,9 @@ typedef unsigned char *CODEADDR; #define DisplPtr(V) ((DISPREG *)(V)) #define TermPtr(V) ((Term *) (V)) -/* Abstract Type Definitions for YAPProlog */ +/************************************************************************************************* + Abstract Type Definitions for YAPProlog +*************************************************************************************************/ typedef CELL Term; @@ -390,7 +386,9 @@ typedef pthread_rwlock_t rwlock_t; #include #endif -/********************** use an auxiliary function for ranges ************/ +/************************************************************************************************* + use an auxiliary function for ranges +*************************************************************************************************/ #ifdef __GNUC__ #define IN_BETWEEN(MIN,X,MAX) (Unsigned((Int)(X)-(Int)(MIN)) <= \ @@ -404,19 +402,25 @@ typedef pthread_rwlock_t rwlock_t; #define OUTSIDE(MIN,X,MAX) ((void *)(X) < (void *)(MIN) || (void *)(X) > (void *)(MAX)) #endif -/* ************************* Atoms *************************************/ +/************************************************************************************************* + Atoms +*************************************************************************************************/ #include "Atoms.h" -/* ************************* Coroutining **********************************/ +/************************************************************************************************* + Coroutining +*************************************************************************************************/ + #ifdef COROUTINING /* Support for co-routining */ #include "corout.h" #endif -/********* abstract machine registers **********************************/ - +/************************************************************************************************* + abstract machine registers +*************************************************************************************************/ #include "amidefs.h" @@ -431,7 +435,9 @@ typedef pthread_rwlock_t rwlock_t; #endif #endif -/************ variables concerned with Error Handling *************/ +/************************************************************************************************* + variables concerned with Error Handling +*************************************************************************************************/ #include @@ -444,7 +450,6 @@ typedef pthread_rwlock_t rwlock_t; /* Support for arrays */ #include "arrays.h" -/************ variables concerned with Error Handling *************/ /* Types of Errors */ typedef enum @@ -622,7 +627,9 @@ typedef enum #define NUMBER_OF_YAP_FLAGS LAST_FLAG -/************************ prototypes **********************************/ +/************************************************************************************************* + prototypes +*************************************************************************************************/ #include "Yapproto.h" @@ -740,7 +747,9 @@ typedef enum #define TermSize sizeof(Term) -/************* variables related to memory allocation *******************/ +/************************************************************************************************* + variables related to memory allocation +*************************************************************************************************/ /* must be before TermExt.h */ extern ADDR Yap_HeapBase; @@ -750,71 +759,17 @@ extern ADDR Yap_HeapBase; #define MAX_ERROR_MSG_SIZE YAP_FILENAME_MAX -#ifdef THREADS -typedef struct thread_globs -{ - ADDR local_base; - ADDR global_base; - ADDR trail_base; - ADDR trail_top; - char *error_message; - Term error_term; - Term error_type; - UInt error_size; - char error_say[MAX_ERROR_MSG_SIZE]; - jmp_buf io_botch; - sigjmp_buf restart_env; - struct TOKEN *tokptr; - struct TOKEN *toktide; - struct VARSTRUCT *var_table; - struct VARSTRUCT *anon_var_table; - int eot_before_eof; - char file_name_buf[YAP_FILENAME_MAX]; - char file_name_buf2[YAP_FILENAME_MAX]; -} tglobs; - -extern struct thread_globs Yap_thread_gl[MAX_THREADS]; - -#define Yap_LocalBase Yap_thread_gl[worker_id].local_base -#define Yap_GlobalBase Yap_thread_gl[worker_id].global_base -#define Yap_TrailBase Yap_thread_gl[worker_id].trail_base -#define Yap_TrailTop Yap_thread_gl[worker_id].trail_top -#define Yap_ErrorMessage Yap_thread_gl[worker_id].error_message -#define Yap_Error_Term Yap_thread_gl[worker_id].error_term -#define Yap_Error_TYPE Yap_thread_gl[worker_id].error_type -#define Yap_Error_Size Yap_thread_gl[worker_id].error_size -#define Yap_ErrorSay Yap_thread_gl[worker_id].error_say -#define Yap_RestartEnv Yap_thread_gl[worker_id].restart_env - -/* This is the guy who actually started the system, and who has the correct registers */ -extern pthread_t Yap_master_thread; - -#else -extern ADDR Yap_HeapBase, - Yap_LocalBase, Yap_GlobalBase, Yap_TrailBase, Yap_TrailTop; - -extern sigjmp_buf Yap_RestartEnv; /* used to restart after an abort */ - -extern char *Yap_ErrorMessage; /* used to pass error messages */ -extern Term Yap_Error_Term; /* used to pass error terms */ -extern yap_error_number Yap_Error_TYPE; /* used to pass the error */ -extern UInt Yap_Error_Size; /* used to pass the error */ - -/******************* storing error messages ****************************/ -extern char Yap_ErrorSay[MAX_ERROR_MSG_SIZE]; - -#endif - -#ifdef DEBUG -/************** Debugging Support ***************************/ -extern int Yap_output_msg; -#endif +/************************************************************************************************* + ??? +*************************************************************************************************/ #define MkVarTerm() MkVarTerm__( PASS_REGS1 ) #define MkPairTerm(A,B) MkPairTerm__( A, B PASS_REGS ) -/* applies to unbound variables */ +/************************************************************************************************* + applies to unbound variables +*************************************************************************************************/ inline EXTERN Term *VarOfTerm (Term t); @@ -1058,18 +1013,317 @@ IntegerOfTerm (Term t) +/************************************************************************************************* + variables concerned with atoms table +*************************************************************************************************/ -/*************** unification routines ***********************************/ +#define MaxHash 3333 +#define MaxWideHash (MaxHash/10+1) + +#define FAIL_RESTORE 0 +#define DO_EVERYTHING 1 +#define DO_ONLY_CODE 2 + +/************************************************************************************************* + common instructions codes +*************************************************************************************************/ + +#define MAX_PROMPT 256 + +#if USE_THREADED_CODE + +/************************************************************************************************* + reverse lookup of instructions +*************************************************************************************************/ +typedef struct opcode_tab_entry +{ + OPCODE opc; + op_numbers opnum; +} opentry; + +#endif + +/************************************************************************************************* + Prolog may be in several modes +*************************************************************************************************/ + +typedef enum +{ + BootMode = 0x1, /* if booting or restoring */ + UserMode = 0x2, /* Normal mode */ + CritMode = 0x4, /* If we are meddling with the heap */ + AbortMode = 0x8, /* expecting to abort */ + InterruptMode = 0x10, /* under an interrupt */ + InErrorMode = 0x20, /* under an interrupt */ + ConsoleGetcMode = 0x40, /* blocked reading from console */ + ExtendStackMode = 0x80, /* trying to extend stack */ + GrowHeapMode = 0x100, /* extending Heap */ + GrowStackMode = 0x200, /* extending Stack */ + GCMode = 0x400, /* doing Garbage Collecting */ + ErrorHandlingMode = 0x800, /* doing error handling */ + CCallMode = 0x1000, /* In c Call */ + UnifyMode = 0x2000, /* In Unify Code */ + UserCCallMode = 0x4000, /* In User C-call Code */ + MallocMode = 0x8000, /* Doing malloc, realloc, free */ + SystemMode = 0x10000, /* in system mode */ + AsyncIntMode = 0x20000, /* YAP has just been interrupted from the outside */ + InReadlineMode = 0x40000 /* YAP has just been interrupted from the outside */ +} prolog_exec_mode; + + +/************************************************************************************************* + number of modules +*************************************************************************************************/ + +#define DefaultMaxModules 256 + +/************************************************************************************************* + Critical sections +*************************************************************************************************/ +#ifdef YAPOR +#define YAPEnterCriticalSection() \ + { \ + if (worker_id != GLOBAL_locks_who_locked_heap) { \ + LOCK(GLOBAL_locks_heap_access); \ + GLOBAL_locks_who_locked_heap = worker_id; \ + } \ + LOCAL_PrologMode |= CritMode; \ + LOCAL_CritLocks++; \ + } +#define YAPLeaveCriticalSection() \ + { \ + LOCAL_CritLocks--; \ + if (!LOCAL_CritLocks) { \ + LOCAL_PrologMode &= ~CritMode; \ + if (LOCAL_PrologMode & InterruptMode) { \ + LOCAL_PrologMode &= ~InterruptMode; \ + Yap_ProcessSIGINT(); \ + } \ + if (LOCAL_PrologMode & AbortMode) { \ + LOCAL_PrologMode &= ~AbortMode; \ + Yap_Error(PURE_ABORT, 0, ""); \ + } \ + GLOBAL_locks_who_locked_heap = MAX_WORKERS; \ + UNLOCK(GLOBAL_locks_heap_access); \ + } \ + } +#elif defined(THREADS) +#define YAPEnterCriticalSection() \ + { \ + /* LOCK(BGL); */ \ + LOCAL_PrologMode |= CritMode; \ + } +#define YAPLeaveCriticalSection() \ + { \ + LOCAL_PrologMode &= ~CritMode; \ + if (LOCAL_PrologMode & InterruptMode) { \ + LOCAL_PrologMode &= ~InterruptMode; \ + Yap_ProcessSIGINT(); \ + } \ + if (LOCAL_PrologMode & AbortMode) { \ + LOCAL_PrologMode &= ~AbortMode; \ + Yap_Error(PURE_ABORT, 0, ""); \ + } \ + /* UNLOCK(BGL); */ \ + } +#else +#define YAPEnterCriticalSection() \ + { \ + LOCAL_PrologMode |= CritMode; \ + LOCAL_CritLocks++; \ + } +#define YAPLeaveCriticalSection() \ + { \ + LOCAL_CritLocks--; \ + if (!LOCAL_CritLocks) { \ + LOCAL_PrologMode &= ~CritMode; \ + if (LOCAL_PrologMode & InterruptMode) { \ + LOCAL_PrologMode &= ~InterruptMode; \ + Yap_ProcessSIGINT(); \ + } \ + if (LOCAL_PrologMode & AbortMode) { \ + LOCAL_PrologMode &= ~AbortMode; \ + Yap_Error(PURE_ABORT, 0, ""); \ + } \ + } \ + } +#endif /* YAPOR */ + +/* when we are calling the InitStaff procedures */ +#define AT_BOOT 0 +#define AT_RESTORE 1 + + +/************************************************************************************************* + mutable variables +*************************************************************************************************/ + +/* I assume that the size of this structure is a multiple of the size + of CELL!!! */ +typedef struct TIMED_MAVAR +{ + CELL value; + CELL clock; +} timed_var; + + +/************************************************************************************************* + execution mode +*************************************************************************************************/ + +typedef enum + { + INTERPRETED, /* interpreted */ + MIXED_MODE_USER, /* mixed mode only for user predicates */ + MIXED_MODE_ALL, /* mixed mode for all predicates */ + COMPILE_USER, /* compile all user predicates*/ + COMPILE_ALL /* compile all predicates */ + } yap_exec_mode; + + +/************************************************************************************************* + slots +*************************************************************************************************/ + + +static inline void +Yap_StartSlots( USES_REGS1 ) { + *--ASP = MkIntegerTerm(CurSlot); + *--ASP = MkIntTerm(0); + CurSlot = LCL0-ASP; +} + +static inline void +Yap_CloseSlots( USES_REGS1 ) { + Int old_slots; + old_slots = IntOfTerm(ASP[0]); + ASP += (old_slots+1); + CurSlot = IntOfTerm(*ASP); + ASP++; +} + +static inline Int +Yap_CurrentSlot( USES_REGS1 ) { + return IntOfTerm(ASP[0]); +} + +/************************/ +#ifdef THREADS +typedef struct thandle { + int in_use; + int zombie; + UInt ssize; + UInt tsize; + UInt sysize; + void *stack_address; + Term tdetach; + Term cmod, texit_mod; + struct DB_TERM *tgoal, *texit; + int id; + int ret; + REGSTORE *default_yaam_regs; + REGSTORE *current_yaam_regs; + struct pred_entry *local_preds; + pthread_t pthread_handle; + int ref_count; +#ifdef LOW_LEVEL_TRACER + long long int thread_inst_count; + int been_here1; + int been_here2; +#endif +#ifdef DEBUG + int been_here; +#endif + pthread_mutex_t tlock; + pthread_mutex_t tlock_status; +#if HAVE_GETRUSAGE||defined(_WIN32) + struct timeval *start_of_timesp; + struct timeval *last_timep; +#endif +} yap_thandle; +#endif /* THREADS */ + +#define GC_MAVARS_HASH_SIZE 512 +typedef struct gc_ma_hash_entry_struct { + UInt timestmp; +#ifdef TABLING + tr_fr_ptr loc; + struct gc_ma_hash_entry_struct *more; +#endif + CELL* addr; + struct gc_ma_hash_entry_struct *next; +} gc_ma_hash_entry; + +typedef int (*Agc_hook)(Atom); + +typedef struct scratch_block_struct { + char *ptr; + UInt sz, msz; +} scratch_block; + + +/* scanner types */ +#include "ScannerTypes.h" + +/************************************************************************************************* + OPTYAP includes +*************************************************************************************************/ + +#if defined(YAPOR) || defined(TABLING) +#include "opt.structs.h" +#include "opt.proto.h" +#include "opt.macros.h" +#endif /* YAPOR || TABLING */ + + + +/************************************************************************************************* + GLOBAL and LOCAL variables +*************************************************************************************************/ + +#if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA) +extern struct global_data *Yap_global; +extern long Yap_worker_area_size; +#else +extern struct global_data Yap_Global; +#define Yap_global (&Yap_Global) +#endif + +#if defined(THREADS) +extern struct worker_local *Yap_local[MAX_THREADS]; +#define REMOTE(wid) (Yap_local[wid]) +#elif defined(YAPOR) +extern struct worker_local *Yap_local; +#define REMOTE(wid) (Yap_local + wid) +#else /* !THREADS && !YAPOR */ +extern struct worker_local Yap_local; +#define REMOTE(wid) (&Yap_local) +#endif + +#define YP_FILE FILE +#include "hglobals.h" +#include "dglobals.h" +#include "hlocals.h" +#include "dlocals.h" + + +/************************************************************************************************* + unification routines +*************************************************************************************************/ #ifdef YAPOR_SBA #include "or.sba_amiops.h" +#include "or.sba_unify.h" #else #include "amiops.h" -#endif +#endif /* YAPOR_SBA */ -/*************** High level macros to access arguments ******************/ +/************************************************************************************************* + High level macros to access arguments +*************************************************************************************************/ + inline EXTERN Term ArgOfTerm (int i, Term t); inline EXTERN Term @@ -1129,214 +1383,4 @@ TailOfTermCell (Term t) return (Term) ((CELL) (RepPair (t) + 1)); } - - -/*************** variables concerned with atoms table *******************/ -#define MaxHash 3333 -#define MaxWideHash (MaxHash/10+1) - -#define FAIL_RESTORE 0 -#define DO_EVERYTHING 1 -#define DO_ONLY_CODE 2 - - -#ifdef EMACS - -/******************** using Emacs mode ********************************/ - -extern int emacs_mode; - -#endif - - -/********* common instructions codes*************************/ - -#define MAX_PROMPT 256 - -#if USE_THREADED_CODE - -/************ reverse lookup of instructions *****************/ -typedef struct opcode_tab_entry -{ - OPCODE opc; - op_numbers opnum; -} opentry; - -#endif - -/********* Prolog may be in several modes *******************************/ - -typedef enum -{ - BootMode = 0x1, /* if booting or restoring */ - UserMode = 0x2, /* Normal mode */ - CritMode = 0x4, /* If we are meddling with the heap */ - AbortMode = 0x8, /* expecting to abort */ - InterruptMode = 0x10, /* under an interrupt */ - InErrorMode = 0x20, /* under an interrupt */ - ConsoleGetcMode = 0x40, /* blocked reading from console */ - ExtendStackMode = 0x80, /* trying to extend stack */ - GrowHeapMode = 0x100, /* extending Heap */ - GrowStackMode = 0x200, /* extending Stack */ - GCMode = 0x400, /* doing Garbage Collecting */ - ErrorHandlingMode = 0x800, /* doing error handling */ - CCallMode = 0x1000, /* In c Call */ - UnifyMode = 0x2000, /* In Unify Code */ - UserCCallMode = 0x4000, /* In User C-call Code */ - MallocMode = 0x8000, /* Doing malloc, realloc, free */ - SystemMode = 0x10000, /* in system mode */ - AsyncIntMode = 0x20000, /* YAP has just been interrupted from the outside */ - InReadlineMode = 0x40000 /* YAP has just been interrupted from the outside */ -} prolog_exec_mode; - -extern Int Yap_PrologMode; -extern int Yap_CritLocks; - -/************** Access to yap initial arguments ***************************/ - -extern char **Yap_argv; -extern int Yap_argc; - -/******** whether Yap is responsible for signal handling ******************/ - -extern int Yap_PrologShouldHandleInterrupts; - -/******************* number of modules ****************************/ - -#define DefaultMaxModules 256 - -#ifdef YAPOR -#define YAPEnterCriticalSection() \ - { \ - if (worker_id != Yap_locks_who_locked_heap) { \ - LOCK(Yap_locks_heap_access); \ - Yap_locks_who_locked_heap = worker_id; \ - } \ - Yap_PrologMode |= CritMode; \ - Yap_CritLocks++; \ - } -#define YAPLeaveCriticalSection() \ - { \ - Yap_CritLocks--; \ - if (!Yap_CritLocks) { \ - Yap_PrologMode &= ~CritMode; \ - if (Yap_PrologMode & InterruptMode) { \ - Yap_PrologMode &= ~InterruptMode; \ - Yap_ProcessSIGINT(); \ - } \ - if (Yap_PrologMode & AbortMode) { \ - Yap_PrologMode &= ~AbortMode; \ - Yap_Error(PURE_ABORT, 0, ""); \ - } \ - Yap_locks_who_locked_heap = MAX_WORKERS; \ - UNLOCK(Yap_locks_heap_access); \ - } \ - } -#elif defined(THREADS) -#define YAPEnterCriticalSection() \ - { \ - /* LOCK(BGL); */ \ - Yap_PrologMode |= CritMode; \ - } -#define YAPLeaveCriticalSection() \ - { \ - Yap_PrologMode &= ~CritMode; \ - if (Yap_PrologMode & InterruptMode) { \ - Yap_PrologMode &= ~InterruptMode; \ - Yap_ProcessSIGINT(); \ - } \ - if (Yap_PrologMode & AbortMode) { \ - Yap_PrologMode &= ~AbortMode; \ - Yap_Error(PURE_ABORT, 0, ""); \ - } \ - /* UNLOCK(BGL); */ \ - } -#else -#define YAPEnterCriticalSection() \ - { \ - Yap_PrologMode |= CritMode; \ - Yap_CritLocks++; \ - } -#define YAPLeaveCriticalSection() \ - { \ - Yap_CritLocks--; \ - if (!Yap_CritLocks) { \ - Yap_PrologMode &= ~CritMode; \ - if (Yap_PrologMode & InterruptMode) { \ - Yap_PrologMode &= ~InterruptMode; \ - Yap_ProcessSIGINT(); \ - } \ - if (Yap_PrologMode & AbortMode) { \ - Yap_PrologMode &= ~AbortMode; \ - Yap_Error(PURE_ABORT, 0, ""); \ - } \ - } \ - } -#endif /* YAPOR */ - -/* when we are calling the InitStaff procedures */ -#define AT_BOOT 0 -#define AT_RESTORE 1 - -/********* mutable variables ******************/ - -/* I assume that the size of this structure is a multiple of the size - of CELL!!! */ -typedef struct TIMED_MAVAR -{ - CELL value; - CELL clock; -} timed_var; - -/********* while debugging you may need some info ***********************/ - -#ifdef EMACS -extern char emacs_tmp[], emacs_tmp2[]; -#endif - -#if defined(YAPOR) || defined(TABLING) -#include "opt.structs.h" -#include "opt.proto.h" -#include "opt.macros.h" -#endif /* YAPOR || TABLING */ - -#ifdef YAPOR_SBA -#include "or.sba_unify.h" -#endif - -/********* execution mode ***********************/ - -typedef enum - { - INTERPRETED, /* interpreted */ - MIXED_MODE_USER, /* mixed mode only for user predicates */ - MIXED_MODE_ALL, /* mixed mode for all predicates */ - COMPILE_USER, /* compile all user predicates*/ - COMPILE_ALL /* compile all predicates */ - } yap_exec_mode; - -/********* slots ***********************/ - - -static inline void -Yap_StartSlots( USES_REGS1 ) { - *--ASP = MkIntegerTerm(CurSlot); - *--ASP = MkIntTerm(0); - CurSlot = LCL0-ASP; -} - -static inline void -Yap_CloseSlots( USES_REGS1 ) { - Int old_slots; - old_slots = IntOfTerm(ASP[0]); - ASP += (old_slots+1); - CurSlot = IntOfTerm(*ASP); - ASP++; -} - -static inline Int -Yap_CurrentSlot( USES_REGS1 ) { - return IntOfTerm(ASP[0]); -} - #endif /* YAP_H */ diff --git a/H/YapHeap.h b/H/YapHeap.h index 8f7ab1644..d24d28ab8 100755 --- a/H/YapHeap.h +++ b/H/YapHeap.h @@ -52,17 +52,17 @@ typedef struct swi_reverse_hash { Int pos; } swi_rev_hash; -#define GC_MAVARS_HASH_SIZE 512 - -typedef struct gc_ma_hash_entry_struct { - UInt timestmp; -#ifdef TABLING - tr_fr_ptr loc; - struct gc_ma_hash_entry_struct *more; -#endif - CELL* addr; - struct gc_ma_hash_entry_struct *next; -} gc_ma_hash_entry; +//#define GC_MAVARS_HASH_SIZE 512 +// +//typedef struct gc_ma_hash_entry_struct { +// UInt timestmp; +//#ifdef TABLING +// tr_fr_ptr loc; +// struct gc_ma_hash_entry_struct *more; +//#endif +// CELL* addr; +// struct gc_ma_hash_entry_struct *next; +//} gc_ma_hash_entry; typedef void (*HaltHookFunc)(int, void *); @@ -81,19 +81,10 @@ typedef struct atom_hash_entry { Atom Entry; } AtomHashEntry; -typedef struct reduction_counters { - YAP_ULONG_LONG reductions; - YAP_ULONG_LONG reductions_retries; - YAP_ULONG_LONG retries; - int reductions_on; - int reductions_retries_on; - int retries_on; -} red_counters; - -typedef struct scratch_block_struct { - char *ptr; - UInt sz, msz; -} scratch_block; +//typedef struct scratch_block_struct { +// char *ptr; +// UInt sz, msz; +//} scratch_block; typedef struct record_list { /* a list of dbterms associated with a clause */ @@ -101,34 +92,12 @@ typedef struct record_list { struct record_list *next_rec, *prev_rec; } DBRecordList; -typedef struct restore_info { - Int base_diff; - Int cl_diff; - Int g_diff; - Int g_diff0; - Int h_diff; - Int l_diff; - Int tr_diff; - Int x_diff; - Int delay_diff; - CELL *old_ASP; - CELL *old_LCL0; - CELL *g_split; - tr_fr_ptr old_TR; - CELL *old_GlobalBase; - CELL *old_H; - CELL *old_H0; - ADDR old_TrailBase; - ADDR old_TrailTop; - ADDR old_HeapBase; - ADDR old_HeapTop; -} restoreinfo; - /* SWI Emulation */ #define SWI_BUF_SIZE 512 #define SWI_TMP_BUF_SIZE 2*SWI_BUF_SIZE #define SWI_BUF_RINGS 16 +/* ricardo #ifdef THREADS typedef struct thandle { int in_use; @@ -162,9 +131,9 @@ typedef struct thandle { struct timeval *last_timep; #endif } yap_thandle; -#endif +#endif */ -typedef int (*Agc_hook)(Atom); +//typedef int (*Agc_hook)(Atom); /******************* this is the data base: everything here should be possible to restore @@ -177,9 +146,10 @@ typedef struct various_codes { } all_heap_codes; -#include "hglobals.h" -#include "hlocals.h" +//#include "hglobals.h" +//#include "hlocals.h" +/* ricardo #if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA) extern struct global_data *Yap_global; extern long Yap_worker_area_size; @@ -189,19 +159,16 @@ extern struct global_data Yap_Global; #endif #if defined(THREADS) -extern struct worker_local *Yap_WLocal[MAX_THREADS]; -#define WL (Yap_WLocal[worker_id]) -#define FOREIGN(wid) (Yap_WLocal[(wid)]) +extern struct worker_local *Yap_local[MAX_THREADS]; +#define REMOTE(wid) (Yap_local[wid]) #elif defined(YAPOR) -extern struct worker_local *Yap_WLocal; -#define WL (Yap_WLocal+worker_id) -#define FOREIGN(wid) (Yap_WLocal+wid) -#else /* !THREADS && !YAPOR */ -extern struct worker_local Yap_WLocal; -#define WL (&Yap_WLocal) -#define FOREIGN(wid) (&Yap_WLocal) +extern struct worker_local *Yap_local; +#define REMOTE(wid) (Yap_local + wid) +#else +extern struct worker_local Yap_local; +#define REMOTE(wid) (&Yap_local) #endif - +*/ #ifdef USE_SYSTEM_MALLOC extern struct various_codes *Yap_heap_regs; @@ -210,8 +177,8 @@ extern struct various_codes *Yap_heap_regs; #endif #include "dhstruct.h" -#include "dglobals.h" -#include "dlocals.h" +//#include "dglobals.h" +//#include "dlocals.h" /******************* these are the global variables: they need not be restored... diff --git a/H/Yapproto.h b/H/Yapproto.h index edc2b8368..0c8be2542 100755 --- a/H/Yapproto.h +++ b/H/Yapproto.h @@ -132,9 +132,6 @@ Term STD_PROTO(Yap_all_calls,(void)); Atom STD_PROTO(Yap_ConsultingFile,(void)); struct pred_entry *STD_PROTO(Yap_PredForChoicePt,(choiceptr)); void STD_PROTO(Yap_InitCdMgr,(void)); -#ifdef EMACS -int STD_PROTO(where_new_clause, (Prop, int)); -#endif void STD_PROTO(Yap_init_consult,(int, char *)); void STD_PROTO(Yap_end_consult,(void)); void STD_PROTO(Yap_Abolish,(struct pred_entry *)); @@ -239,6 +236,9 @@ void STD_PROTO(Yap_InitCPredBack_,(char *, unsigned long int, unsigned int, C #endif void STD_PROTO(Yap_InitWorkspace,(UInt,UInt,UInt,UInt,UInt,int,int,int)); +#ifdef YAPOR +void STD_PROTO(Yap_init_yapor_workers, (void)); +#endif /* YAPOR */ #if defined(YAPOR) || defined(THREADS) void STD_PROTO(Yap_KillStacks,(int)); #else @@ -328,6 +328,7 @@ void STD_PROTO(Yap_undo_signal,(yap_signals)); int STD_PROTO(Yap_IsOpMaxPrio,(Atom)); /* sysbits.c */ +void STD_PROTO(Yap_InitPageSize, (void)); void STD_PROTO(Yap_set_fpu_exceptions,(int)); UInt STD_PROTO(Yap_cputime,(void)); Int STD_PROTO(Yap_walltime,(void)); @@ -391,6 +392,11 @@ void STD_PROTO(Yap_InitUtilCPreds,(void)); Int STD_PROTO(Yap_TermHash,(Term, Int, Int, int)); /* yap.c */ + +/* write.c */ +void STD_PROTO(Yap_plwrite,(Term,int (*)(int, wchar_t), int, int)); + + /* MYDDAS */ #if defined MYDDAS_MYSQL || defined MYDDAS_ODBC diff --git a/H/Yatom.h b/H/Yatom.h index 95f7ca01f..03289ac25 100755 --- a/H/Yatom.h +++ b/H/Yatom.h @@ -1493,7 +1493,7 @@ Yap_GetThreadPred(struct pred_entry *ap USES_REGS) { Functor f = ap->FunctorOfPred; Term mod = ap->ModuleOfPred; - Prop p0 = AbsPredProp(MY_ThreadHandle.local_preds); + Prop p0 = AbsPredProp(LOCAL_ThreadHandle.local_preds); while(p0) { PredEntry *ap = RepPredProp(p0); diff --git a/H/absmi.h b/H/absmi.h index fd34bcb55..c68eb45c0 100644 --- a/H/absmi.h +++ b/H/absmi.h @@ -192,7 +192,7 @@ restore_absmi_regs(REGSTORE * old_regs) memcpy(old_regs, Yap_regp, sizeof(REGSTORE)); #ifdef THREADS pthread_setspecific(Yap_yaamregs_key, (void *)old_regs); - MY_ThreadHandle.current_yaam_regs = old_regs; + LOCAL_ThreadHandle.current_yaam_regs = old_regs; #else Yap_regp = old_regs; #endif @@ -682,10 +682,10 @@ Macros to check the limits of stacks #else -#define check_trail(x) if (Unsigned(Yap_TrailTop) - Unsigned(x) < MinTrailGap) \ +#define check_trail(x) if (Unsigned(LOCAL_TrailTop) - Unsigned(x) < MinTrailGap) \ goto notrailleft -#define check_trail_in_indexing(x) if (Unsigned(Yap_TrailTop) - Unsigned(x) < MinTrailGap) \ +#define check_trail_in_indexing(x) if (Unsigned(LOCAL_TrailTop) - Unsigned(x) < MinTrailGap) \ goto notrailleft_from_index #endif @@ -734,7 +734,7 @@ Macros to check the limits of stacks ENDP(pt0) #if LOW_LEVEL_TRACER -#define COUNT_CPS() Yap_total_choicepoints++ +#define COUNT_CPS() LOCAL_total_choicepoints++ #else #define COUNT_CPS() #endif diff --git a/H/amidefs.h b/H/amidefs.h index 13a09dd22..e3c111f1a 100644 --- a/H/amidefs.h +++ b/H/amidefs.h @@ -1095,12 +1095,8 @@ extern void **Yap_ABSMI_OPCODES; #define absmadr(i) ((OPCODE)(i)) #endif -/* used to find out how many instructions of each kind are executed */ -#ifdef ANALYST -extern YAP_ULONG_LONG Yap_opcount[_std_top + 1]; -extern YAP_ULONG_LONG Yap_2opcount[_std_top + 1][_std_top + 1]; -#endif /* ANALYST */ + #if DEPTH_LIMIT /* diff --git a/H/amiops.h b/H/amiops.h index d58cfb0f1..0df524333 100644 --- a/H/amiops.h +++ b/H/amiops.h @@ -15,6 +15,7 @@ * dereferencing, binding, trailing, and unification. * * * *************************************************************************/ + #ifdef SCCS static char SccsId[] = "%W% %G%"; #endif /* SCCS */ @@ -276,7 +277,7 @@ Binding Macros for Multiple Assignment Variables. #define TRAIL_CLREF(REF) TrailTerm(TR++) = CLREF_TO_TRENTRY(REF) #define TRAIL_LINK(REF) TrailTerm(TR++) = AbsPair((CELL *)(REF)) #endif -#define TRAIL_FRAME(FR) DO_TRAIL(AbsPair((CELL *)(Yap_TrailBase)), FR) +#define TRAIL_FRAME(FR) DO_TRAIL(AbsPair((CELL *)(LOCAL_TrailBase)), FR) extern void Yap_WakeUp(CELL *v); diff --git a/H/cut_c.h b/H/cut_c.h index 857a96da5..cf53117a7 100755 --- a/H/cut_c.h +++ b/H/cut_c.h @@ -32,7 +32,7 @@ struct cut_c_str{ #define POP_CHOICE_POINT(cp) \ - (((CELL *)Yap_REGS.CUT_C_TOP != (CELL *)Yap_LocalBase) && ((CELL *)(cp) > (CELL *)Yap_REGS.CUT_C_TOP)) + (((CELL *)Yap_REGS.CUT_C_TOP != (CELL *)LOCAL_LocalBase) && ((CELL *)(cp) > (CELL *)Yap_REGS.CUT_C_TOP)) #define POP_EXECUTE() \ diff --git a/H/dglobals.h b/H/dglobals.h index ffdeca415..e049b2252 100644 --- a/H/dglobals.h +++ b/H/dglobals.h @@ -1,5 +1,5 @@ - /* This file, dglobals.h, was generated automatically by "yap -L misc/buildheap" + /* This file, dglobals.h, was generated automatically by "yap -L misc/buildlocalglobal" please do not update, update misc/GLOBALS instead */ @@ -20,45 +20,91 @@ +#define GLOBAL_Initialised Yap_global->Initialised_ +#define GLOBAL_InitialisedFromPL Yap_global->InitialisedFromPL_ +#define GLOBAL_PL_Argc Yap_global->PL_Argc_ +#define GLOBAL_PL_Argv Yap_global->PL_Argv_ +#define GLOBAL_HaltHooks Yap_global->HaltHooks_ + +#define GLOBAL_AllowLocalExpansion Yap_global->AllowLocalExpansion_ +#define GLOBAL_AllowGlobalExpansion Yap_global->AllowGlobalExpansion_ +#define GLOBAL_AllowTrailExpansion Yap_global->AllowTrailExpansion_ +#define GLOBAL_SizeOfOverflow Yap_global->SizeOfOverflow_ + +#define GLOBAL_AGcThreshold Yap_global->AGcThreshold_ +#define GLOBAL_AGCHook Yap_global->AGCHook_ #if THREADS -#define Yap_NOfThreads Yap_global->n_of_threads +#define GLOBAL_NOfThreads Yap_global->NOfThreads_ -#define Yap_NOfThreadsCreated Yap_global->n_of_threads_created +#define GLOBAL_NOfThreadsCreated Yap_global->NOfThreadsCreated_ -#define Yap_ThreadsTotalTime Yap_global->threads_total_time -#endif +#define GLOBAL_ThreadsTotalTime Yap_global->ThreadsTotalTime_ +#define GLOBAL_ThreadHandlesLock Yap_global->ThreadHandlesLock_ +#endif #if defined(YAPOR) || defined(THREADS) -#define Yap_BGL Yap_global->bgl +#define GLOBAL_BGL Yap_global->BGL_ #endif - -#define Yap_AllowLocalExpansion Yap_global->allow_local_expansion -#define Yap_AllowGlobalExpansion Yap_global->allow_global_expansion -#define Yap_AllowTrailExpansion Yap_global->allow_trail_expansion -#define Yap_SizeOfOverflow Yap_global->size_of_overflow - -#define Yap_AGcLastCall Yap_global->agc_last_call - -#define Yap_AGcThreshold Yap_global->agc_threshold -#define Yap_AGCHook Yap_global->agc_hook - -#ifdef THREADS -#define Yap_ThreadHandlesLock Yap_global->thread_handles_lock -#endif - #if defined(YAPOR) || defined(TABLING) -#define Yap_optyap_data Yap_global->optyap_data -#define REMOTE Yap_global->remote +#define GLOBAL_optyap_data Yap_global->optyap_data_ +#endif /* YAPOR || TABLING */ + +#define GLOBAL_PrologShouldHandleInterrupts Yap_global->PrologShouldHandleInterrupts_ + +#if defined(THREADS) +#define GLOBAL_master_thread Yap_global->master_thread_ +#endif /* THREADS */ + +#define GLOBAL_stdout Yap_global->stdout_ +#define GLOBAL_stderr Yap_global->stderr_ + +#define GLOBAL_argv Yap_global->argv_ +#define GLOBAL_argc Yap_global->argc_ + +#ifdef COROUTINING + +#define GLOBAL_attas Yap_global->attas_ +#endif + +#define GLOBAL_agc_calls Yap_global->agc_calls_ +#define GLOBAL_agc_collected Yap_global->agc_collected_ + +#define GLOBAL_tot_agc_time Yap_global->tot_agc_time_ + +#define GLOBAL_tot_agc_recovered Yap_global->tot_agc_recovered_ + +#if HAVE_MMAP +#define GLOBAL_mmap_arrays Yap_global->mmap_arrays_ +#endif +#ifdef DEBUG + +#define GLOBAL_Option Yap_global->Option_ +#define GLOBAL_logfile Yap_global->logfile_ + +#define GLOBAL_output_msg Yap_global->output_msg_ +#endif + +#define GLOBAL_ProfCalls Yap_global->ProfCalls_ +#define GLOBAL_ProfGCs Yap_global->ProfGCs_ +#define GLOBAL_ProfHGrows Yap_global->ProfHGrows_ +#define GLOBAL_ProfSGrows Yap_global->ProfSGrows_ +#define GLOBAL_ProfMallocs Yap_global->ProfMallocs_ +#define GLOBAL_ProfOn Yap_global->ProfOn_ +#define GLOBAL_ProfOns Yap_global->ProfOns_ +#define GLOBAL_ProfilerRoot Yap_global->ProfilerRoot_ +#define GLOBAL_ProfilerNil Yap_global->ProfilerNil_ +#define GLOBAL_DIRNAME Yap_global->DIRNAME_ +#if defined(COFF) || defined(A_OUT) + +#define GLOBAL_Executable Yap_global->Executable_ +#endif +#if __simplescalar__ +#define GLOBAL_pwd Yap_global->pwd_ #endif -#define Yap_Initialised Yap_global->initialised -#define Yap_InitialisedFromPL Yap_global->initialised_from_pl -#define Yap_PL_Argc Yap_global->pl_argc -#define Yap_PL_Argv Yap_global->pl_argv -#define Yap_HaltHooks Yap_global->yap_halt_hook diff --git a/H/dlocals.h b/H/dlocals.h index 71b71fd79..367b899be 100644 --- a/H/dlocals.h +++ b/H/dlocals.h @@ -1,143 +1,319 @@ - /* This file, dlocals.h, was generated automatically by "yap -L misc/buildheap" + /* This file, dlocals.h, was generated automatically by "yap -L misc/buildlocalglobal" please do not update, update misc/LOCALS instead */ -#define Yap_c_input_stream WL->c_input_stream -#define Yap_c_output_stream WL->c_output_stream -#define Yap_c_error_stream WL->c_error_stream +#define LOCAL_c_input_stream LOCAL->c_input_stream_ +#define REMOTE_c_input_stream(wid) REMOTE(wid)->c_input_stream_ +#define LOCAL_c_output_stream LOCAL->c_output_stream_ +#define REMOTE_c_output_stream(wid) REMOTE(wid)->c_output_stream_ +#define LOCAL_c_error_stream LOCAL->c_error_stream_ +#define REMOTE_c_error_stream(wid) REMOTE(wid)->c_error_stream_ -#define OldASP WL->rinfo.old_ASP -#define OldLCL0 WL->rinfo.old_LCL0 -#define OldTR WL->rinfo.old_TR -#define OldGlobalBase WL->rinfo.old_GlobalBase -#define OldH WL->rinfo.old_H -#define OldH0 WL->rinfo.old_H0 -#define OldTrailBase WL->rinfo.old_TrailBase -#define OldTrailTop WL->rinfo.old_TrailTop -#define OldHeapBase WL->rinfo.old_HeapBase -#define OldHeapTop WL->rinfo.old_HeapTop -#define ClDiff WL->rinfo.cl_diff -#define GDiff WL->rinfo.g_diff -#define HDiff WL->rinfo.h_diff -#define GDiff0 WL->rinfo.g_diff0 -#define GSplit WL->rinfo.g_split -#define LDiff WL->rinfo.l_diff -#define TrDiff WL->rinfo.tr_diff -#define XDiff WL->rinfo.x_diff -#define DelayDiff WL->rinfo.delay_diff -#define BaseDiff WL->rinfo.base_diff -#define ReductionsCounter WL->call_counters.reductions -#define PredEntriesCounter WL->call_counters.reductions_retries -#define RetriesCounter WL->call_counters.retries -#define ReductionsCounterOn WL->call_counters.reductions_on -#define PredEntriesCounterOn WL->call_counters.reductions_retries_on -#define RetriesCounterOn WL->call_counters.retries_on -#define Yap_InterruptsDisabled WL->interrupts_disabled +#define LOCAL_OldASP LOCAL->OldASP_ +#define REMOTE_OldASP(wid) REMOTE(wid)->OldASP_ +#define LOCAL_OldLCL0 LOCAL->OldLCL0_ +#define REMOTE_OldLCL0(wid) REMOTE(wid)->OldLCL0_ +#define LOCAL_OldTR LOCAL->OldTR_ +#define REMOTE_OldTR(wid) REMOTE(wid)->OldTR_ +#define LOCAL_OldGlobalBase LOCAL->OldGlobalBase_ +#define REMOTE_OldGlobalBase(wid) REMOTE(wid)->OldGlobalBase_ +#define LOCAL_OldH LOCAL->OldH_ +#define REMOTE_OldH(wid) REMOTE(wid)->OldH_ +#define LOCAL_OldH0 LOCAL->OldH0_ +#define REMOTE_OldH0(wid) REMOTE(wid)->OldH0_ +#define LOCAL_OldTrailBase LOCAL->OldTrailBase_ +#define REMOTE_OldTrailBase(wid) REMOTE(wid)->OldTrailBase_ +#define LOCAL_OldTrailTop LOCAL->OldTrailTop_ +#define REMOTE_OldTrailTop(wid) REMOTE(wid)->OldTrailTop_ +#define LOCAL_OldHeapBase LOCAL->OldHeapBase_ +#define REMOTE_OldHeapBase(wid) REMOTE(wid)->OldHeapBase_ +#define LOCAL_OldHeapTop LOCAL->OldHeapTop_ +#define REMOTE_OldHeapTop(wid) REMOTE(wid)->OldHeapTop_ +#define LOCAL_ClDiff LOCAL->ClDiff_ +#define REMOTE_ClDiff(wid) REMOTE(wid)->ClDiff_ +#define LOCAL_GDiff LOCAL->GDiff_ +#define REMOTE_GDiff(wid) REMOTE(wid)->GDiff_ +#define LOCAL_HDiff LOCAL->HDiff_ +#define REMOTE_HDiff(wid) REMOTE(wid)->HDiff_ +#define LOCAL_GDiff0 LOCAL->GDiff0_ +#define REMOTE_GDiff0(wid) REMOTE(wid)->GDiff0_ +#define LOCAL_GSplit LOCAL->GSplit_ +#define REMOTE_GSplit(wid) REMOTE(wid)->GSplit_ +#define LOCAL_LDiff LOCAL->LDiff_ +#define REMOTE_LDiff(wid) REMOTE(wid)->LDiff_ +#define LOCAL_TrDiff LOCAL->TrDiff_ +#define REMOTE_TrDiff(wid) REMOTE(wid)->TrDiff_ +#define LOCAL_XDiff LOCAL->XDiff_ +#define REMOTE_XDiff(wid) REMOTE(wid)->XDiff_ +#define LOCAL_DelayDiff LOCAL->DelayDiff_ +#define REMOTE_DelayDiff(wid) REMOTE(wid)->DelayDiff_ +#define LOCAL_BaseDiff LOCAL->BaseDiff_ +#define REMOTE_BaseDiff(wid) REMOTE(wid)->BaseDiff_ + +#define LOCAL_ReductionsCounter LOCAL->ReductionsCounter_ +#define REMOTE_ReductionsCounter(wid) REMOTE(wid)->ReductionsCounter_ +#define LOCAL_PredEntriesCounter LOCAL->PredEntriesCounter_ +#define REMOTE_PredEntriesCounter(wid) REMOTE(wid)->PredEntriesCounter_ +#define LOCAL_RetriesCounter LOCAL->RetriesCounter_ +#define REMOTE_RetriesCounter(wid) REMOTE(wid)->RetriesCounter_ +#define LOCAL_ReductionsCounterOn LOCAL->ReductionsCounterOn_ +#define REMOTE_ReductionsCounterOn(wid) REMOTE(wid)->ReductionsCounterOn_ +#define LOCAL_PredEntriesCounterOn LOCAL->PredEntriesCounterOn_ +#define REMOTE_PredEntriesCounterOn(wid) REMOTE(wid)->PredEntriesCounterOn_ +#define LOCAL_RetriesCounterOn LOCAL->RetriesCounterOn_ +#define REMOTE_RetriesCounterOn(wid) REMOTE(wid)->RetriesCounterOn_ -#define ConsultSp WL->consultsp +#define LOCAL_ConsultSp LOCAL->ConsultSp_ +#define REMOTE_ConsultSp(wid) REMOTE(wid)->ConsultSp_ -#define ConsultCapacity WL->consultcapacity +#define LOCAL_ConsultCapacity LOCAL->ConsultCapacity_ +#define REMOTE_ConsultCapacity(wid) REMOTE(wid)->ConsultCapacity_ -#define ConsultBase WL->consultbase +#define LOCAL_ConsultBase LOCAL->ConsultBase_ +#define REMOTE_ConsultBase(wid) REMOTE(wid)->ConsultBase_ -#define ConsultLow WL->consultlow +#define LOCAL_ConsultLow LOCAL->ConsultLow_ +#define REMOTE_ConsultLow(wid) REMOTE(wid)->ConsultLow_ -#define GlobalArena WL->global_arena -#define GlobalArenaOverflows WL->global_arena_overflows -#define DelayArenaOverflows WL->delay_arena_overflows -#define ArenaOverflows WL->arena_overflows -#define DepthArenas WL->depth_arenas -#define ArithError WL->arith_error -#define LastAssertedPred WL->last_asserted_pred -#define DebugOn WL->debug_on -#define FormatInfo WL->f_info -#define ScannerStack WL->scanner_stack -#define ScannerExtraBlocks WL->scanner_extra_blocks -#define BallTerm WL->ball_term -#define ActiveSignals WL->active_signals -#define IPredArity WL->i_pred_arity -#define ProfEnd WL->prof_end -#define UncaughtThrow WL->uncaught_throw -#define DoingUndefp WL->doing_undefp -#define StartLine WL->start_line -#define ScratchPad WL->scratchpad +#define LOCAL_GlobalArena LOCAL->GlobalArena_ +#define REMOTE_GlobalArena(wid) REMOTE(wid)->GlobalArena_ +#define LOCAL_GlobalArenaOverflows LOCAL->GlobalArenaOverflows_ +#define REMOTE_GlobalArenaOverflows(wid) REMOTE(wid)->GlobalArenaOverflows_ +#define LOCAL_ArenaOverflows LOCAL->ArenaOverflows_ +#define REMOTE_ArenaOverflows(wid) REMOTE(wid)->ArenaOverflows_ +#define LOCAL_DepthArenas LOCAL->DepthArenas_ +#define REMOTE_DepthArenas(wid) REMOTE(wid)->DepthArenas_ +#define LOCAL_ArithError LOCAL->ArithError_ +#define REMOTE_ArithError(wid) REMOTE(wid)->ArithError_ +#define LOCAL_LastAssertedPred LOCAL->LastAssertedPred_ +#define REMOTE_LastAssertedPred(wid) REMOTE(wid)->LastAssertedPred_ +#define LOCAL_DebugOn LOCAL->DebugOn_ +#define REMOTE_DebugOn(wid) REMOTE(wid)->DebugOn_ +#define LOCAL_ScannerStack LOCAL->ScannerStack_ +#define REMOTE_ScannerStack(wid) REMOTE(wid)->ScannerStack_ +#define LOCAL_ScannerExtraBlocks LOCAL->ScannerExtraBlocks_ +#define REMOTE_ScannerExtraBlocks(wid) REMOTE(wid)->ScannerExtraBlocks_ +#define LOCAL_BallTerm LOCAL->BallTerm_ +#define REMOTE_BallTerm(wid) REMOTE(wid)->BallTerm_ +#define LOCAL_ActiveSignals LOCAL->ActiveSignals_ +#define REMOTE_ActiveSignals(wid) REMOTE(wid)->ActiveSignals_ +#define LOCAL_IPredArity LOCAL->IPredArity_ +#define REMOTE_IPredArity(wid) REMOTE(wid)->IPredArity_ +#define LOCAL_ProfEnd LOCAL->ProfEnd_ +#define REMOTE_ProfEnd(wid) REMOTE(wid)->ProfEnd_ +#define LOCAL_UncaughtThrow LOCAL->UncaughtThrow_ +#define REMOTE_UncaughtThrow(wid) REMOTE(wid)->UncaughtThrow_ +#define LOCAL_DoingUndefp LOCAL->DoingUndefp_ +#define REMOTE_DoingUndefp(wid) REMOTE(wid)->DoingUndefp_ +#define LOCAL_StartLine LOCAL->StartLine_ +#define REMOTE_StartLine(wid) REMOTE(wid)->StartLine_ +#define LOCAL_ScratchPad LOCAL->ScratchPad_ +#define REMOTE_ScratchPad(wid) REMOTE(wid)->ScratchPad_ #ifdef COROUTINING -#define WokenGoals WL->woken_goals -#define AttsMutableList WL->atts_mutable_list +#define LOCAL_WokenGoals LOCAL->WokenGoals_ +#define REMOTE_WokenGoals(wid) REMOTE(wid)->WokenGoals_ +#define LOCAL_AttsMutableList LOCAL->AttsMutableList_ +#define REMOTE_AttsMutableList(wid) REMOTE(wid)->AttsMutableList_ #endif -#define GcGeneration WL->gc_generation -#define GcPhase WL->gc_phase -#define GcCurrentPhase WL->gc_current_phase -#define GcCalls WL->gc_calls -#define TotGcTime WL->tot_gc_time -#define TotGcRecovered WL->tot_gc_recovered -#define LastGcTime WL->last_gc_time -#define LastSSTime WL->last_ss_time -#if LOW_LEVEL_TRACER -#define Yap_total_choicepoints WL->total_cps +#define LOCAL_GcGeneration LOCAL->GcGeneration_ +#define REMOTE_GcGeneration(wid) REMOTE(wid)->GcGeneration_ +#define LOCAL_GcPhase LOCAL->GcPhase_ +#define REMOTE_GcPhase(wid) REMOTE(wid)->GcPhase_ +#define LOCAL_GcCurrentPhase LOCAL->GcCurrentPhase_ +#define REMOTE_GcCurrentPhase(wid) REMOTE(wid)->GcCurrentPhase_ +#define LOCAL_GcCalls LOCAL->GcCalls_ +#define REMOTE_GcCalls(wid) REMOTE(wid)->GcCalls_ +#define LOCAL_TotGcTime LOCAL->TotGcTime_ +#define REMOTE_TotGcTime(wid) REMOTE(wid)->TotGcTime_ +#define LOCAL_TotGcRecovered LOCAL->TotGcRecovered_ +#define REMOTE_TotGcRecovered(wid) REMOTE(wid)->TotGcRecovered_ +#define LOCAL_LastGcTime LOCAL->LastGcTime_ +#define REMOTE_LastGcTime(wid) REMOTE(wid)->LastGcTime_ +#define LOCAL_LastSSTime LOCAL->LastSSTime_ +#define REMOTE_LastSSTime(wid) REMOTE(wid)->LastSSTime_ + +#define LOCAL_total_marked LOCAL->total_marked_ +#define REMOTE_total_marked(wid) REMOTE(wid)->total_marked_ +#define LOCAL_total_oldies LOCAL->total_oldies_ +#define REMOTE_total_oldies(wid) REMOTE(wid)->total_oldies_ +#define LOCAL_current_B LOCAL->current_B_ +#define REMOTE_current_B(wid) REMOTE(wid)->current_B_ +#define LOCAL_prev_HB LOCAL->prev_HB_ +#define REMOTE_prev_HB(wid) REMOTE(wid)->prev_HB_ +#define LOCAL_HGEN LOCAL->HGEN_ +#define REMOTE_HGEN(wid) REMOTE(wid)->HGEN_ +#define LOCAL_iptop LOCAL->iptop_ +#define REMOTE_iptop(wid) REMOTE(wid)->iptop_ +#if defined(GC_NO_TAGS) +#define LOCAL_bp LOCAL->bp_ +#define REMOTE_bp(wid) REMOTE(wid)->bp_ #endif -#define consult_level WL->consult_level_ +#define LOCAL_sTR LOCAL->sTR_ +#define REMOTE_sTR(wid) REMOTE(wid)->sTR_ +#define LOCAL_sTR0 LOCAL->sTR0_ +#define REMOTE_sTR0(wid) REMOTE(wid)->sTR0_ +#define LOCAL_new_TR LOCAL->new_TR_ +#define REMOTE_new_TR(wid) REMOTE(wid)->new_TR_ +#define LOCAL_cont_top0 LOCAL->cont_top0_ +#define REMOTE_cont_top0(wid) REMOTE(wid)->cont_top0_ +#define LOCAL_cont_top LOCAL->cont_top_ +#define REMOTE_cont_top(wid) REMOTE(wid)->cont_top_ +#define LOCAL_discard_trail_entries LOCAL->discard_trail_entries_ +#define REMOTE_discard_trail_entries(wid) REMOTE(wid)->discard_trail_entries_ +#define LOCAL_gc_ma_hash_table LOCAL->gc_ma_hash_table_ +#define REMOTE_gc_ma_hash_table(wid) REMOTE(wid)->gc_ma_hash_table_ +#define LOCAL_gc_ma_h_top LOCAL->gc_ma_h_top_ +#define REMOTE_gc_ma_h_top(wid) REMOTE(wid)->gc_ma_h_top_ +#define LOCAL_gc_ma_h_list LOCAL->gc_ma_h_list_ +#define REMOTE_gc_ma_h_list(wid) REMOTE(wid)->gc_ma_h_list_ +#define LOCAL_gc_timestamp LOCAL->gc_timestamp_ +#define REMOTE_gc_timestamp(wid) REMOTE(wid)->gc_timestamp_ +#define LOCAL_db_vec LOCAL->db_vec_ +#define REMOTE_db_vec(wid) REMOTE(wid)->db_vec_ +#define LOCAL_db_vec0 LOCAL->db_vec0_ +#define REMOTE_db_vec0(wid) REMOTE(wid)->db_vec0_ +#define LOCAL_db_root LOCAL->db_root_ +#define REMOTE_db_root(wid) REMOTE(wid)->db_root_ +#define LOCAL_db_nil LOCAL->db_nil_ +#define REMOTE_db_nil(wid) REMOTE(wid)->db_nil_ +#define LOCAL_gc_restore LOCAL->gc_restore_ +#define REMOTE_gc_restore(wid) REMOTE(wid)->gc_restore_ +#define LOCAL_DynamicArrays LOCAL->DynamicArrays_ +#define REMOTE_DynamicArrays(wid) REMOTE(wid)->DynamicArrays_ +#define LOCAL_StaticArrays LOCAL->StaticArrays_ +#define REMOTE_StaticArrays(wid) REMOTE(wid)->StaticArrays_ +#define LOCAL_GlobalVariables LOCAL->GlobalVariables_ +#define REMOTE_GlobalVariables(wid) REMOTE(wid)->GlobalVariables_ +#define LOCAL_AllowRestart LOCAL->AllowRestart_ +#define REMOTE_AllowRestart(wid) REMOTE(wid)->AllowRestart_ -#if defined(YAPOR) || defined(THREADS) -#define SignalLock WL->signal_lock -#define WPP WL->wpp +#define LOCAL_CMemFirstBlock LOCAL->CMemFirstBlock_ +#define REMOTE_CMemFirstBlock(wid) REMOTE(wid)->CMemFirstBlock_ +#define LOCAL_CMemFirstBlockSz LOCAL->CMemFirstBlockSz_ +#define REMOTE_CMemFirstBlockSz(wid) REMOTE(wid)->CMemFirstBlockSz_ -#define total_marked WL->tot_marked -#define total_oldies WL->tot_oldies -#if DEBUG && COROUTINING -#define total_smarked WL->tot_smarked -#endif -#define current_B WL->wl_current_B -#define prev_HB WL->wl_prev_HB -#define HGEN WL->hgen -#define iptop WL->ip_top -#if GC_NO_TAGS -#define Yap_bp WL->b_p -#endif -#if defined(TABLING) || defined(YAPOR_SBA) -#define sTR WL->wl_sTR -#define sTR0 WL->wl_sTR0 -#define new_TR WL->new_tr -#else -#define sTR WL->wl_sTR -#define sTR0 WL->wl_sTR0 -#define new_TR WL->new_tr -#endif -#define cont_top0 WL->conttop0 -#define cont_top WL->conttop -#define discard_trail_entries WL->disc_trail_entries -#define gc_ma_hash_table WL->Gc_ma_hash_table -#define gc_ma_h_top WL->Gc_ma_h_top -#define gc_ma_h_list WL->Gc_ma_h_list -#define gc_timestamp WL->Gc_timestamp -#define db_vec WL->DB_vec -#define db_vec0 WL->DB_vec0 -#define db_root WL->DB_root -#define db_nil WL->DB_nil -#endif /* defined(YAPOR) || defined(THREADS) */ -#define Yap_gc_restore WL->gc_restore -#define DynamicArrays WL->dynamic_arrays -#define StaticArrays WL->static_arrays -#define GlobalVariables WL->global_variables -#define Yap_AllowRestart WL->allow_restart +#define LOCAL_LabelFirstArray LOCAL->LabelFirstArray_ +#define REMOTE_LabelFirstArray(wid) REMOTE(wid)->LabelFirstArray_ +#define LOCAL_LabelFirstArraySz LOCAL->LabelFirstArraySz_ +#define REMOTE_LabelFirstArraySz(wid) REMOTE(wid)->LabelFirstArraySz_ -#define Yap_CMemFirstBlock WL->cmem_first_block -#define Yap_CMemFirstBlockSz WL->cmem_first_block_sz - -#define Yap_LabelFirstArray WL->label_first_array -#define Yap_LabelFirstArraySz WL->label_first_array_sz - -#define PL_local_data_p WL->Yap_ld_ -#define execution WL->_execution +#define LOCAL_PL_local_data_p LOCAL->PL_local_data_p_ +#define REMOTE_PL_local_data_p(wid) REMOTE(wid)->PL_local_data_p_ #ifdef THREADS -#define ThreadHandle WL->thread_handle -#define FOREIGN_ThreadHandle(wid) (Yap_WLocal[(wid)]->thread_handle) -#define MY_ThreadHandle (Yap_WLocal[worker_id]->thread_handle) +#define LOCAL_ThreadHandle LOCAL->ThreadHandle_ +#define REMOTE_ThreadHandle(wid) REMOTE(wid)->ThreadHandle_ +#endif /* THREADS */ +#if defined(YAPOR) || defined(TABLING) +#define LOCAL_optyap_data LOCAL->optyap_data_ +#define REMOTE_optyap_data(wid) REMOTE(wid)->optyap_data_ +#endif /* YAPOR || TABLING */ +#define LOCAL_InterruptsDisabled LOCAL->InterruptsDisabled_ +#define REMOTE_InterruptsDisabled(wid) REMOTE(wid)->InterruptsDisabled_ +#define LOCAL_execution LOCAL->execution_ +#define REMOTE_execution(wid) REMOTE(wid)->execution_ +#if LOW_LEVEL_TRACER +#define LOCAL_total_choicepoints LOCAL->total_choicepoints_ +#define REMOTE_total_choicepoints(wid) REMOTE(wid)->total_choicepoints_ +#endif +#define LOCAL_consult_level LOCAL->consult_level_ +#define REMOTE_consult_level(wid) REMOTE(wid)->consult_level_ +#if defined(YAPOR) || defined(THREADS) +#define LOCAL_SignalLock LOCAL->SignalLock_ +#define REMOTE_SignalLock(wid) REMOTE(wid)->SignalLock_ #endif +#define LOCAL_LocalBase LOCAL->LocalBase_ +#define REMOTE_LocalBase(wid) REMOTE(wid)->LocalBase_ +#define LOCAL_GlobalBase LOCAL->GlobalBase_ +#define REMOTE_GlobalBase(wid) REMOTE(wid)->GlobalBase_ +#define LOCAL_TrailBase LOCAL->TrailBase_ +#define REMOTE_TrailBase(wid) REMOTE(wid)->TrailBase_ +#define LOCAL_TrailTop LOCAL->TrailTop_ +#define REMOTE_TrailTop(wid) REMOTE(wid)->TrailTop_ +#define LOCAL_ErrorMessage LOCAL->ErrorMessage_ +#define REMOTE_ErrorMessage(wid) REMOTE(wid)->ErrorMessage_ +#define LOCAL_Error_Term LOCAL->Error_Term_ +#define REMOTE_Error_Term(wid) REMOTE(wid)->Error_Term_ +#ifdef THREADS +#define LOCAL_Error_TYPE LOCAL->Error_TYPE_ +#define REMOTE_Error_TYPE(wid) REMOTE(wid)->Error_TYPE_ +#else +#define LOCAL_Error_TYPE LOCAL->Error_TYPE_ +#define REMOTE_Error_TYPE(wid) REMOTE(wid)->Error_TYPE_ +#endif +#define LOCAL_Error_Size LOCAL->Error_Size_ +#define REMOTE_Error_Size(wid) REMOTE(wid)->Error_Size_ +#define LOCAL_ErrorSay LOCAL->ErrorSay_ +#define REMOTE_ErrorSay(wid) REMOTE(wid)->ErrorSay_ +#define LOCAL_IOBotch LOCAL->IOBotch_ +#define REMOTE_IOBotch(wid) REMOTE(wid)->IOBotch_ +#define LOCAL_tokptr LOCAL->tokptr_ +#define REMOTE_tokptr(wid) REMOTE(wid)->tokptr_ +#define LOCAL_toktide LOCAL->toktide_ +#define REMOTE_toktide(wid) REMOTE(wid)->toktide_ +#define LOCAL_VarTable LOCAL->VarTable_ +#define REMOTE_VarTable(wid) REMOTE(wid)->VarTable_ +#define LOCAL_AnonVarTable LOCAL->AnonVarTable_ +#define REMOTE_AnonVarTable(wid) REMOTE(wid)->AnonVarTable_ +#define LOCAL_RestartEnv LOCAL->RestartEnv_ +#define REMOTE_RestartEnv(wid) REMOTE(wid)->RestartEnv_ +#define LOCAL_FileNameBuf LOCAL->FileNameBuf_ +#define REMOTE_FileNameBuf(wid) REMOTE(wid)->FileNameBuf_ +#define LOCAL_FileNameBuf2 LOCAL->FileNameBuf2_ +#define REMOTE_FileNameBuf2(wid) REMOTE(wid)->FileNameBuf2_ + +#define LOCAL_PrologMode LOCAL->PrologMode_ +#define REMOTE_PrologMode(wid) REMOTE(wid)->PrologMode_ +#define LOCAL_CritLocks LOCAL->CritLocks_ +#define REMOTE_CritLocks(wid) REMOTE(wid)->CritLocks_ + + +#ifdef ANALYST +#define LOCAL_opcount LOCAL->opcount_ +#define REMOTE_opcount(wid) REMOTE(wid)->opcount_ +#define LOCAL_2opcount LOCAL->2opcount_ +#define REMOTE_2opcount(wid) REMOTE(wid)->2opcount_ +#endif /* ANALYST */ + +#define LOCAL_s_dbg LOCAL->s_dbg_ +#define REMOTE_s_dbg(wid) REMOTE(wid)->s_dbg_ + +#define LOCAL_matherror LOCAL->matherror_ +#define REMOTE_matherror(wid) REMOTE(wid)->matherror_ + +#define LOCAL_heap_overflows LOCAL->heap_overflows_ +#define REMOTE_heap_overflows(wid) REMOTE(wid)->heap_overflows_ +#define LOCAL_total_heap_overflow_time LOCAL->total_heap_overflow_time_ +#define REMOTE_total_heap_overflow_time(wid) REMOTE(wid)->total_heap_overflow_time_ +#define LOCAL_stack_overflows LOCAL->stack_overflows_ +#define REMOTE_stack_overflows(wid) REMOTE(wid)->stack_overflows_ +#define LOCAL_total_stack_overflow_time LOCAL->total_stack_overflow_time_ +#define REMOTE_total_stack_overflow_time(wid) REMOTE(wid)->total_stack_overflow_time_ +#define LOCAL_delay_overflows LOCAL->delay_overflows_ +#define REMOTE_delay_overflows(wid) REMOTE(wid)->delay_overflows_ +#define LOCAL_total_delay_overflow_time LOCAL->total_delay_overflow_time_ +#define REMOTE_total_delay_overflow_time(wid) REMOTE(wid)->total_delay_overflow_time_ +#define LOCAL_trail_overflows LOCAL->trail_overflows_ +#define REMOTE_trail_overflows(wid) REMOTE(wid)->trail_overflows_ +#define LOCAL_total_trail_overflow_time LOCAL->total_trail_overflow_time_ +#define REMOTE_total_trail_overflow_time(wid) REMOTE(wid)->total_trail_overflow_time_ +#define LOCAL_atom_table_overflows LOCAL->atom_table_overflows_ +#define REMOTE_atom_table_overflows(wid) REMOTE(wid)->atom_table_overflows_ +#define LOCAL_total_atom_table_overflow_time LOCAL->total_atom_table_overflow_time_ +#define REMOTE_total_atom_table_overflow_time(wid) REMOTE(wid)->total_atom_table_overflow_time_ + +#ifdef LOAD_DYLD +#define LOCAL_dl_errno LOCAL->dl_errno_ +#define REMOTE_dl_errno(wid) REMOTE(wid)->dl_errno_ +#endif + +#ifdef LOW_LEVEL_TRACER +#define LOCAL_do_trace_primitives LOCAL->do_trace_primitives_ +#define REMOTE_do_trace_primitives(wid) REMOTE(wid)->do_trace_primitives_ +#endif diff --git a/H/eval.h b/H/eval.h index 511b5e54b..7894042f1 100644 --- a/H/eval.h +++ b/H/eval.h @@ -161,8 +161,6 @@ Functor STD_PROTO(EvalArg,(Term)); #define FL(X) ((double)(X)) #endif -extern yap_error_number Yap_matherror; - void STD_PROTO(Yap_InitConstExps,(void)); void STD_PROTO(Yap_InitUnaryExps,(void)); void STD_PROTO(Yap_InitBinaryExps,(void)); @@ -190,8 +188,8 @@ inline static Term Yap_FoundArithError(Term t, Term inp) { CACHE_REGS - if (Yap_Error_TYPE) { - Yap_Error(Yap_Error_TYPE, (inp ? inp : Yap_Error_Term), Yap_ErrorMessage); + if (LOCAL_Error_TYPE) { + Yap_Error(LOCAL_Error_TYPE, (inp ? inp : LOCAL_Error_Term), LOCAL_ErrorMessage); P = FAILCODE; return 0L; } diff --git a/H/heapgc.h b/H/heapgc.h index a53a0a955..79d5d97ca 100755 --- a/H/heapgc.h +++ b/H/heapgc.h @@ -49,7 +49,7 @@ /* is ptr a pointer to code space? */ #if USE_SYSTEM_MALLOC -#define ONCODE(ptr) (Addr(ptr) < Yap_GlobalBase || Addr(ptr) > Yap_TrailTop) +#define ONCODE(ptr) (Addr(ptr) < LOCAL_GlobalBase || Addr(ptr) > LOCAL_TrailTop) #else #define ONCODE(ptr) (Addr(ptr) < HeapTop && Addr(ptr) >= Yap_HeapBase) #endif @@ -77,14 +77,10 @@ (CellPtr(B) < CellPtr(val) && CellPtr(val) <= \ LCL0 && HEAP_PTR(val)))) -#if !defined(YAPOR) && !defined(THREADS) -extern char *Yap_bp; -#endif - #define MARK_BIT ((char)1) #define RMARK_BIT ((char)2) -#define mcell(X) Yap_bp[(X)-(CELL *)Yap_GlobalBase] +#define mcell(X) LOCAL_bp[(X)-(CELL *)LOCAL_GlobalBase] #define MARKED_PTR(P) MARKED_PTR__(P PASS_REGS) #define UNMARKED_MARK(P, BP) UNMARKED_MARK__(P, BP PASS_REGS) @@ -103,7 +99,7 @@ MARKED_PTR__(CELL* ptr USES_REGS) static inline Int UNMARKED_MARK__(CELL* ptr, char *bp USES_REGS) { - Int pos = ptr - (CELL *)Yap_GlobalBase; + Int pos = ptr - (CELL *)LOCAL_GlobalBase; char t = bp[pos]; if (t & MARK_BIT) { return TRUE; diff --git a/H/hglobals.h b/H/hglobals.h index f7c14454f..ad4c1e699 100644 --- a/H/hglobals.h +++ b/H/hglobals.h @@ -1,5 +1,5 @@ - /* This file, hglobals.h, was generated automatically by "yap -L misc/buildheap" + /* This file, hglobals.h, was generated automatically by "yap -L misc/buildlocalglobal" please do not update, update misc/GLOBALS instead */ @@ -18,47 +18,93 @@ - - typedef struct global_data { + int Initialised_; + int InitialisedFromPL_; + int PL_Argc_; + char** PL_Argv_; + + struct halt_hook* HaltHooks_; + + int AllowLocalExpansion_; + int AllowGlobalExpansion_; + int AllowTrailExpansion_; + UInt SizeOfOverflow_; + + UInt AGcThreshold_; + Agc_hook AGCHook_; + #if THREADS - UInt n_of_threads; + UInt NOfThreads_; - UInt n_of_threads_created; + UInt NOfThreadsCreated_; - UInt threads_total_time; -#endif + UInt ThreadsTotalTime_; + lockvar ThreadHandlesLock_; +#endif #if defined(YAPOR) || defined(THREADS) - lockvar bgl; + lockvar BGL_; #endif - - int allow_local_expansion; - int allow_global_expansion; - int allow_trail_expansion; - UInt size_of_overflow; - - UInt agc_last_call; - - UInt agc_threshold; - Agc_hook agc_hook; - -#ifdef THREADS - lockvar thread_handles_lock; -#endif - #if defined(YAPOR) || defined(TABLING) - struct global_optyap_data optyap_data; - struct local_data remote[MAX_WORKERS]; + struct global_optyap_data optyap_data_; +#endif /* YAPOR || TABLING */ + + int PrologShouldHandleInterrupts_; + +#if defined(THREADS) + pthread_t master_thread_; +#endif /* THREADS */ + + YP_FILE* stdout_; + YP_FILE* stderr_; + + char** argv_; + int argc_; + +#ifdef COROUTINING + + ext_op attas_[attvars_ext+1]; +#endif + + int agc_calls_; + YAP_ULONG_LONG agc_collected_; + + Int tot_agc_time_; + + Int tot_agc_recovered_; + +#if HAVE_MMAP + struct MMAP_ARRAY_BLOCK* mmap_arrays_; +#endif +#ifdef DEBUG + + char Option_[20]; + YP_FILE* logfile_; + + int output_msg_; +#endif + + Int ProfCalls_; + Int ProfGCs_; + Int ProfHGrows_; + Int ProfSGrows_; + Int ProfMallocs_; + Int ProfOn_; + Int ProfOns_; + struct RB_red_blk_node* ProfilerRoot_; + struct RB_red_blk_node* ProfilerNil_; + char* DIRNAME_; +#if defined(COFF) || defined(A_OUT) + + char Executable_[YAP_FILENAME_MAX]; +#endif +#if __simplescalar__ + char pwd_[YAP_FILENAME_MAX]; #endif - int initialised; - int initialised_from_pl; - int pl_argc; - char **pl_argv; - struct halt_hook *yap_halt_hook; } w_shared; diff --git a/H/hlocals.h b/H/hlocals.h index 6e08f7af2..c737f5b59 100644 --- a/H/hlocals.h +++ b/H/hlocals.h @@ -1,145 +1,185 @@ - /* This file, hlocals.h, was generated automatically by "yap -L misc/buildheap" + /* This file, hlocals.h, was generated automatically by "yap -L misc/buildlocalglobal" please do not update, update misc/LOCALS instead */ typedef struct worker_local { - int c_input_stream; - int c_output_stream; - int c_error_stream; + int c_input_stream_; + int c_output_stream_; + int c_error_stream_; - restoreinfo rinfo; + CELL* OldASP_; + CELL* OldLCL0_; + tr_fr_ptr OldTR_; + CELL* OldGlobalBase_; + CELL* OldH_; + CELL* OldH0_; + ADDR OldTrailBase_; + ADDR OldTrailTop_; + ADDR OldHeapBase_; + ADDR OldHeapTop_; + Int ClDiff_; + Int GDiff_; + Int HDiff_; + Int GDiff0_; + CELL* GSplit_; + Int LDiff_; + Int TrDiff_; + Int XDiff_; + Int DelayDiff_; + Int BaseDiff_; + + YAP_ULONG_LONG ReductionsCounter_; + YAP_ULONG_LONG PredEntriesCounter_; + YAP_ULONG_LONG RetriesCounter_; + int ReductionsCounterOn_; + int PredEntriesCounterOn_; + int RetriesCounterOn_; + union CONSULT_OBJ* ConsultSp_; + UInt ConsultCapacity_; + union CONSULT_OBJ* ConsultBase_; + union CONSULT_OBJ* ConsultLow_; - - - - - - - - - - - - - - - struct reduction_counters call_counters; - - - - - - - int interrupts_disabled; - - - union CONSULT_OBJ* consultsp; - - UInt consultcapacity; - - union CONSULT_OBJ* consultbase; - - union CONSULT_OBJ* consultlow; - - Term global_arena; - UInt global_arena_overflows; - Int delay_arena_overflows; - Int arena_overflows; - Int depth_arenas; - int arith_error; - struct pred_entry* last_asserted_pred; - int debug_on; - struct format_status* f_info; - char* scanner_stack; - struct scanner_extra_alloc* scanner_extra_blocks; - struct DB_TERM *ball_term; - UInt active_signals; - UInt i_pred_arity; - yamop* prof_end; - int uncaught_throw; - int doing_undefp; - Int start_line; - scratch_block scratchpad; + Term GlobalArena_; + UInt GlobalArenaOverflows_; + Int ArenaOverflows_; + Int DepthArenas_; + int ArithError_; + struct pred_entry* LastAssertedPred_; + int DebugOn_; + char* ScannerStack_; + struct scanner_extra_alloc* ScannerExtraBlocks_; + struct DB_TERM* BallTerm_; + UInt ActiveSignals_; + UInt IPredArity_; + yamop* ProfEnd_; + int UncaughtThrow_; + int DoingUndefp_; + Int StartLine_; + scratch_block ScratchPad_; #ifdef COROUTINING - Term woken_goals; - Term atts_mutable_list; + Term WokenGoals_; + Term AttsMutableList_; #endif - Term gc_generation; - Term gc_phase; - UInt gc_current_phase; - UInt gc_calls; - Int tot_gc_time; - YAP_ULONG_LONG tot_gc_recovered; - Int last_gc_time; - Int last_ss_time; + Term GcGeneration_; + Term GcPhase_; + UInt GcCurrentPhase_; + UInt GcCalls_; + Int TotGcTime_; + YAP_ULONG_LONG TotGcRecovered_; + Int LastGcTime_; + Int LastSSTime_; + + Int total_marked_; + Int total_oldies_; + struct choicept* current_B_; + CELL* prev_HB_; + CELL* HGEN_; + CELL** iptop_; +#if defined(GC_NO_TAGS) + char* bp_; +#endif + tr_fr_ptr sTR_; + tr_fr_ptr sTR0_; + tr_fr_ptr new_TR_; + struct gc_mark_continuation* cont_top0_; + struct gc_mark_continuation* cont_top_; + int discard_trail_entries_; + gc_ma_hash_entry gc_ma_hash_table_[GC_MAVARS_HASH_SIZE]; + gc_ma_hash_entry* gc_ma_h_top_; + gc_ma_hash_entry* gc_ma_h_list_; + UInt gc_timestamp_; + ADDR db_vec_; + ADDR db_vec0_; + struct RB_red_blk_node* db_root_; + struct RB_red_blk_node* db_nil_; + sigjmp_buf gc_restore_; + struct array_entry* DynamicArrays_; + struct static_array_entry* StaticArrays_; + struct global_entry* GlobalVariables_; + int AllowRestart_; + + struct mem_blk* CMemFirstBlock_; + UInt CMemFirstBlockSz_; + + Int* LabelFirstArray_; + UInt LabelFirstArraySz_; + + struct PL_local_data* PL_local_data_p_; +#ifdef THREADS + struct thandle ThreadHandle_; +#endif /* THREADS */ +#if defined(YAPOR) || defined(TABLING) + struct local_optyap_data optyap_data_; +#endif /* YAPOR || TABLING */ + int InterruptsDisabled_; + struct open_query_struct* execution_; #if LOW_LEVEL_TRACER - Int total_cps; + Int total_choicepoints_; #endif int consult_level_; - #if defined(YAPOR) || defined(THREADS) - lockvar signal_lock; - struct pred_entry* wpp; - - Int tot_marked; - Int tot_oldies; -#if DEBUG && COROUTINING - UInt tot_smarked; + lockvar SignalLock_; #endif - struct choicept *wl_current_B; - CELL* wl_prev_HB; - CELL* hgen; - CELL** ip_top; -#if GC_NO_TAGS - char* b_p; -#endif -#if defined(TABLING) || defined(YAPOR_SBA) - struct trail_frame* wl_sTR; - struct trail_frame* wl_sTR0; - struct trail_frame* new_tr; -#else - Term *wl_sTR; - Term *wl_sTR0; - Term *new_tr; -#endif - struct gc_mark_continuation* conttop0; - struct gc_mark_continuation* conttop; - int disc_trail_entries; - gc_ma_hash_entry Gc_ma_hash_table[GC_MAVARS_HASH_SIZE]; - gc_ma_hash_entry* Gc_ma_h_top; - gc_ma_hash_entry* Gc_ma_h_list; - UInt Gc_timestamp; - ADDR DB_vec; - ADDR DB_vec0; - struct RB_red_blk_node* DB_root; - struct RB_red_blk_node* DB_nil; -#endif /* defined(YAPOR) || defined(THREADS) */ - sigjmp_buf gc_restore; - struct array_entry* dynamic_arrays; - struct static_array_entry* static_arrays; - struct global_entry* global_variables; - int allow_restart; - struct mem_blk* cmem_first_block; - UInt cmem_first_block_sz; - - Int* label_first_array; - UInt label_first_array_sz; - - struct PL_local_data *Yap_ld_; - struct open_query_struct* _execution; + ADDR LocalBase_; + ADDR GlobalBase_; + ADDR TrailBase_; + ADDR TrailTop_; + char* ErrorMessage_; + Term Error_Term_; #ifdef THREADS - struct thandle thread_handle; -#define FOREIGN_ThreadHandle(wid) (Yap_WLocal[(wid)]->thread_handle) -#define MY_ThreadHandle (Yap_WLocal[worker_id]->thread_handle) + Term Error_TYPE_; +#else + yap_error_number Error_TYPE_; +#endif + UInt Error_Size_; + char ErrorSay_[MAX_ERROR_MSG_SIZE]; + jmp_buf IOBotch_; + TokEntry* tokptr_; + TokEntry* toktide_; + VarEntry* VarTable_; + VarEntry* AnonVarTable_; + sigjmp_buf RestartEnv_; + char FileNameBuf_[YAP_FILENAME_MAX]; + char FileNameBuf2_[YAP_FILENAME_MAX]; + + Int PrologMode_; + int CritLocks_; + + +#ifdef ANALYST + YAP_ULONG_LONG opcount_[_std_top+1]; + YAP_ULONG_LONG 2opcount[_std_top+1][_std_top+1]_; +#endif /* ANALYST */ + + struct db_globs* s_dbg_; + + yap_error_number matherror_; + + int heap_overflows_; + Int total_heap_overflow_time_; + int stack_overflows_; + Int total_stack_overflow_time_; + int delay_overflows_; + Int total_delay_overflow_time_; + int trail_overflows_; + Int total_trail_overflow_time_; + int atom_table_overflows_; + Int total_atom_table_overflow_time_; + +#ifdef LOAD_DYLD + static dl_errno_; #endif +#ifdef LOW_LEVEL_TRACER + int do_trace_primitives_; +#endif } w_local; diff --git a/H/iglobals.h b/H/iglobals.h index 18789bf6e..bf2abed19 100644 --- a/H/iglobals.h +++ b/H/iglobals.h @@ -1,5 +1,5 @@ - /* This file, iglobals.h, was generated automatically by "yap -L misc/buildheap" + /* This file, iglobals.h, was generated automatically by "yap -L misc/buildlocalglobal" please do not update, update misc/GLOBALS instead */ @@ -18,47 +18,93 @@ - - static void InitGlobal(void) { + GLOBAL_Initialised = FALSE; + GLOBAL_InitialisedFromPL = FALSE; + GLOBAL_PL_Argc = 0; + GLOBAL_PL_Argv = NULL; + + GLOBAL_HaltHooks = NULL; + + GLOBAL_AllowLocalExpansion = TRUE; + GLOBAL_AllowGlobalExpansion = TRUE; + GLOBAL_AllowTrailExpansion = TRUE; + GLOBAL_SizeOfOverflow = 0; + + GLOBAL_AGcThreshold = 10000; + GLOBAL_AGCHook = NULL; + #if THREADS - Yap_global->n_of_threads = 1; + GLOBAL_NOfThreads = 1; - Yap_global->n_of_threads_created = 1; + GLOBAL_NOfThreadsCreated = 1; - Yap_global->threads_total_time = 0L; -#endif + GLOBAL_ThreadsTotalTime = 0L; + INIT_LOCK(GLOBAL_ThreadHandlesLock); +#endif #if defined(YAPOR) || defined(THREADS) - INIT_LOCK(Yap_global->bgl); + INIT_LOCK(GLOBAL_BGL); #endif - - Yap_global->allow_local_expansion = TRUE; - Yap_global->allow_global_expansion = TRUE; - Yap_global->allow_trail_expansion = TRUE; - Yap_global->size_of_overflow = 0; - - Yap_global->agc_last_call = 0; - - Yap_global->agc_threshold = 10000; - Yap_global->agc_hook = NULL; - -#ifdef THREADS - INIT_LOCK(Yap_global->thread_handles_lock); -#endif - #if defined(YAPOR) || defined(TABLING) +#endif /* YAPOR || TABLING */ + + + +#if defined(THREADS) + +#endif /* THREADS */ + + GLOBAL_stdout = stdout; + GLOBAL_stderr = stderr; + + + + +#ifdef COROUTINING + + +#endif + + + + + GLOBAL_tot_agc_time = 0; + + GLOBAL_tot_agc_recovered = 0; + +#if HAVE_MMAP + GLOBAL_mmap_arrays = NULL; +#endif +#ifdef DEBUG + + + + + GLOBAL_output_msg = FALSE; +#endif + + + + + + + + + + + GLOBAL_DIRNAME = NULL; +#if defined(COFF) || defined(A_OUT) + + +#endif +#if __simplescalar__ #endif - Yap_global->initialised = FALSE; - Yap_global->initialised_from_pl = FALSE; - Yap_global->pl_argc = 0; - Yap_global->pl_argv = NULL; - Yap_global->yap_halt_hook = NULL; } diff --git a/H/ihstruct.h b/H/ihstruct.h index 45ab202c3..c17ef8c96 100644 --- a/H/ihstruct.h +++ b/H/ihstruct.h @@ -35,7 +35,7 @@ #if defined(YAPOR) || defined(THREADS) - INIT_LOCK(Yap_heap_regs->dlmalloc_lock); + INIT_LOCK(DLMallocLock); #endif #endif #if USE_DL_MALLOC || (USE_SYSTEM_MALLOC && HAVE_MALLINFO) @@ -51,10 +51,10 @@ #if defined(YAPOR) || defined(THREADS) - INIT_LOCK(Yap_heap_regs->free_blocks_lock); - INIT_LOCK(Yap_heap_regs->heap_used_lock); - INIT_LOCK(Yap_heap_regs->heap_top_lock); - Yap_heap_regs->heap_top_owner = -1; + INIT_LOCK(FreeBlocksLock); + INIT_LOCK(HeapUsedLock); + INIT_LOCK(HeapTopLock); + HeapTopOwner = -1; #endif @@ -62,13 +62,13 @@ #endif - Yap_heap_regs->execute_cpred_op_code = Yap_opcode(_execute_cpred); - Yap_heap_regs->expand_op_code = Yap_opcode(_expand_index); - Yap_heap_regs->fail_op = Yap_opcode(_op_fail); - Yap_heap_regs->index_op = Yap_opcode(_index_pred); - Yap_heap_regs->lockpred_op = Yap_opcode(_lock_pred); - Yap_heap_regs->orlast_op = Yap_opcode(_or_last); - Yap_heap_regs->undef_op = Yap_opcode(_undef_p); + EXECUTE_CPRED_OP_CODE = Yap_opcode(_execute_cpred); + EXPAND_OP_CODE = Yap_opcode(_expand_index); + FAIL_OPCODE = Yap_opcode(_op_fail); + INDEX_OPCODE = Yap_opcode(_index_pred); + LOCKPRED_OPCODE = Yap_opcode(_lock_pred); + ORLAST_OPCODE = Yap_opcode(_or_last); + UNDEF_OPCODE = Yap_opcode(_undef_p); @@ -80,100 +80,100 @@ #include "iatoms.h" #ifdef EUROTRA - Yap_heap_regs->term_dollar_u = MkAtomTerm(AtomDollarU); + TermDollarU = MkAtomTerm(AtomDollarU); #endif - Yap_heap_regs->term_prolog = MkAtomTerm(AtomProlog); - Yap_heap_regs->term_refound_var = MkAtomTerm(AtomRefoundVar); - Yap_heap_regs->user_module = MkAtomTerm(AtomUser); - Yap_heap_regs->idb_module = MkAtomTerm(AtomIDB); - Yap_heap_regs->attributes_module = MkAtomTerm(AtomAttributes); - Yap_heap_regs->charsio_module = MkAtomTerm(AtomCharsio); - Yap_heap_regs->terms_module = MkAtomTerm(AtomTerms); - Yap_heap_regs->system_module = MkAtomTerm(AtomSystem); - Yap_heap_regs->operating_system_module = MkAtomTerm(AtomOperatingSystemSupport); - Yap_heap_regs->readutil_module = MkAtomTerm(AtomReadutil); - Yap_heap_regs->hacks_module = MkAtomTerm(AtomYapHacks); - Yap_heap_regs->arg_module = MkAtomTerm(AtomArg); - Yap_heap_regs->globals_module = MkAtomTerm(AtomNb); - Yap_heap_regs->swi_module = MkAtomTerm(AtomSwi); - Yap_heap_regs->dbload_module = MkAtomTerm(AtomDBLoad); + TermProlog = MkAtomTerm(AtomProlog); + TermReFoundVar = MkAtomTerm(AtomRefoundVar); + USER_MODULE = MkAtomTerm(AtomUser); + IDB_MODULE = MkAtomTerm(AtomIDB); + ATTRIBUTES_MODULE = MkAtomTerm(AtomAttributes); + CHARSIO_MODULE = MkAtomTerm(AtomCharsio); + TERMS_MODULE = MkAtomTerm(AtomTerms); + SYSTEM_MODULE = MkAtomTerm(AtomSystem); + OPERATING_SYSTEM_MODULE = MkAtomTerm(AtomOperatingSystemSupport); + READUTIL_MODULE = MkAtomTerm(AtomReadutil); + HACKS_MODULE = MkAtomTerm(AtomYapHacks); + ARG_MODULE = MkAtomTerm(AtomArg); + GLOBALS_MODULE = MkAtomTerm(AtomNb); + SWI_MODULE = MkAtomTerm(AtomSwi); + DBLOAD_MODULE = MkAtomTerm(AtomDBLoad); - Yap_heap_regs->current_modules = NULL; + CurrentModules = NULL; Yap_InitModules(); - Yap_heap_regs->execution_mode = INTERPRETED; + Yap_ExecutionMode = INTERPRETED; InitPredHash(); #if defined(YAPOR) || defined(THREADS) #endif - Yap_heap_regs->preds_in_hash_table = 0; + PredsInHashTable = 0; - Yap_heap_regs->creep_code = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomCreep,1),PROLOG_MODULE)); - Yap_heap_regs->undef_code = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomUndefp,1),PROLOG_MODULE)); - Yap_heap_regs->spy_code = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomSpy,1),PROLOG_MODULE)); - Yap_heap_regs->pred_fail = RepPredProp(PredPropByAtom(AtomFail,PROLOG_MODULE)); - Yap_heap_regs->pred_true = RepPredProp(PredPropByAtom(AtomTrue,PROLOG_MODULE)); + CreepCode = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomCreep,1),PROLOG_MODULE)); + UndefCode = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomUndefp,1),PROLOG_MODULE)); + SpyCode = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomSpy,1),PROLOG_MODULE)); + PredFail = RepPredProp(PredPropByAtom(AtomFail,PROLOG_MODULE)); + PredTrue = RepPredProp(PredPropByAtom(AtomTrue,PROLOG_MODULE)); #ifdef COROUTINING - Yap_heap_regs->wake_up_code = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomWakeUpGoal,2),PROLOG_MODULE)); + WakeUpCode = RepPredProp(PredPropByFunc(Yap_MkFunctor(AtomWakeUpGoal,2),PROLOG_MODULE)); #endif - Yap_heap_regs->pred_goal_expansion = RepPredProp(PredPropByFunc(FunctorGoalExpansion,USER_MODULE)); - Yap_heap_regs->pred_meta_call = RepPredProp(PredPropByFunc(FunctorMetaCall,PROLOG_MODULE)); - Yap_heap_regs->pred_dollar_catch = RepPredProp(PredPropByFunc(FunctorCatch,PROLOG_MODULE)); - Yap_heap_regs->pred_recorded_with_key = RepPredProp(PredPropByFunc(FunctorRecordedWithKey,PROLOG_MODULE)); - Yap_heap_regs->pred_log_upd_clause = RepPredProp(PredPropByFunc(FunctorDoLogUpdClause,PROLOG_MODULE)); - Yap_heap_regs->pred_log_upd_clause_erase = RepPredProp(PredPropByFunc(FunctorDoLogUpdClauseErase,PROLOG_MODULE)); - Yap_heap_regs->pred_log_upd_clause0 = RepPredProp(PredPropByFunc(FunctorDoLogUpdClause,PROLOG_MODULE)); - Yap_heap_regs->pred_static_clause = RepPredProp(PredPropByFunc(FunctorDoStaticClause,PROLOG_MODULE)); - Yap_heap_regs->pred_throw = RepPredProp(PredPropByFunc(FunctorThrow,PROLOG_MODULE)); - Yap_heap_regs->pred_handle_throw = RepPredProp(PredPropByFunc(FunctorHandleThrow,PROLOG_MODULE)); - Yap_heap_regs->pred_is = RepPredProp(PredPropByFunc(FunctorIs,PROLOG_MODULE)); - Yap_heap_regs->pred_safe_call_cleanup = RepPredProp(PredPropByFunc(FunctorSafeCallCleanup,PROLOG_MODULE)); - Yap_heap_regs->pred_restore_regs = RepPredProp(PredPropByFunc(FunctorRestoreRegs,PROLOG_MODULE)); + PredGoalExpansion = RepPredProp(PredPropByFunc(FunctorGoalExpansion,USER_MODULE)); + PredMetaCall = RepPredProp(PredPropByFunc(FunctorMetaCall,PROLOG_MODULE)); + PredDollarCatch = RepPredProp(PredPropByFunc(FunctorCatch,PROLOG_MODULE)); + PredRecordedWithKey = RepPredProp(PredPropByFunc(FunctorRecordedWithKey,PROLOG_MODULE)); + PredLogUpdClause = RepPredProp(PredPropByFunc(FunctorDoLogUpdClause,PROLOG_MODULE)); + PredLogUpdClauseErase = RepPredProp(PredPropByFunc(FunctorDoLogUpdClauseErase,PROLOG_MODULE)); + PredLogUpdClause0 = RepPredProp(PredPropByFunc(FunctorDoLogUpdClause,PROLOG_MODULE)); + PredStaticClause = RepPredProp(PredPropByFunc(FunctorDoStaticClause,PROLOG_MODULE)); + PredThrow = RepPredProp(PredPropByFunc(FunctorThrow,PROLOG_MODULE)); + PredHandleThrow = RepPredProp(PredPropByFunc(FunctorHandleThrow,PROLOG_MODULE)); + PredIs = RepPredProp(PredPropByFunc(FunctorIs,PROLOG_MODULE)); + PredSafeCallCleanup = RepPredProp(PredPropByFunc(FunctorSafeCallCleanup,PROLOG_MODULE)); + PredRestoreRegs = RepPredProp(PredPropByFunc(FunctorRestoreRegs,PROLOG_MODULE)); #ifdef YAPOR - Yap_heap_regs->pred_getwork = RepPredProp(PredPropByAtom(AtomGetwork,PROLOG_MODULE)); - Yap_heap_regs->pred_getwork_seq = RepPredProp(PredPropByAtom(AtomGetworkSeq,PROLOG_MODULE)); + PredGetwork = RepPredProp(PredPropByAtom(AtomGetwork,PROLOG_MODULE)); + PredGetworkSeq = RepPredProp(PredPropByAtom(AtomGetworkSeq,PROLOG_MODULE)); #endif /* YAPOR */ #ifdef LOW_LEVEL_TRACER - Yap_heap_regs->yap_do_low_level_trace = FALSE; + Yap_do_low_level_trace = FALSE; #if defined(YAPOR) || defined(THREADS) - INIT_LOCK(Yap_heap_regs->low_level_trace_lock); + INIT_LOCK(Yap_low_level_trace_lock); #endif #endif - Yap_heap_regs->clause_space = 0; - Yap_heap_regs->index_space_Tree = 0; - Yap_heap_regs->index_space_EXT = 0; - Yap_heap_regs->index_space_SW = 0; - Yap_heap_regs->lu_clause_space = 0; - Yap_heap_regs->lu_index_space_Tree = 0; - Yap_heap_regs->lu_index_space_CP = 0; - Yap_heap_regs->lu_index_space_EXT = 0; - Yap_heap_regs->lu_index_space_SW = 0; + Yap_ClauseSpace = 0; + Yap_IndexSpace_Tree = 0; + Yap_IndexSpace_EXT = 0; + Yap_IndexSpace_SW = 0; + Yap_LUClauseSpace = 0; + Yap_LUIndexSpace_Tree = 0; + Yap_LUIndexSpace_CP = 0; + Yap_LUIndexSpace_EXT = 0; + Yap_LUIndexSpace_SW = 0; - Yap_heap_regs->dummycode->opc = Yap_opcode(_op_fail); - Yap_heap_regs->failcode->opc = Yap_opcode(_op_fail); - Yap_heap_regs->nocode->opc = Yap_opcode(_Nstop); + DUMMYCODE->opc = Yap_opcode(_op_fail); + FAILCODE->opc = Yap_opcode(_op_fail); + NOCODE->opc = Yap_opcode(_Nstop); InitEnvInst(ENV_FOR_TRUSTFAIL,&TRUSTFAILCODE,_trust_fail,PredFail); InitEnvInst(ENV_FOR_YESCODE,&YESCODE,_Ystop,PredFail); InitOtaplInst(RTRYCODE,_retry_and_mark,PredFail); #ifdef BEAM - Yap_heap_regs->beam_retry_code->opc = Yap_opcode(_beam_retry_code); + BEAM_RETRY_CODE->opc = Yap_opcode(_beam_retry_code); #endif /* BEAM */ #ifdef YAPOR - Yap_heap_regs->seq_def = FALSE; + SEQUENTIAL_IS_DEFAULT = FALSE; InitOtaplInst(GETWORK,_getwork,PredGetwork); InitOtaplInst(GETWORK_SEQ,_getwork_seq,PredGetworkSeq); - Yap_heap_regs->getwork_first_time->opc = Yap_opcode(_getwork_first_time); + GETWORK_FIRST_TIME->opc = Yap_opcode(_getwork_first_time); #endif /* YAPOR */ #ifdef TABLING InitOtaplInst(LOAD_ANSWER,_table_load_answer,PredFail); @@ -185,121 +185,121 @@ - Yap_heap_regs->debugger_p_before_spy = NULL; + P_before_spy = NULL; - Yap_heap_regs->retry_recordedp_code = NULL; - Yap_heap_regs->retry_recorded_k_code = NULL; + RETRY_C_RECORDEDP_CODE = NULL; + RETRY_C_RECORDED_K_CODE = NULL; - Yap_heap_regs->system_profiling = FALSE; - Yap_heap_regs->system_call_counting = FALSE; - Yap_heap_regs->system_pred_goal_expansion_all = FALSE; - Yap_heap_regs->system_pred_goal_expansion_func = FALSE; - Yap_heap_regs->system_pred_goal_expansion_on = FALSE; - Yap_heap_regs->compiler_optimizer_on = TRUE; - Yap_heap_regs->compiler_compile_mode = 0; - Yap_heap_regs->compiler_profiling = FALSE; - Yap_heap_regs->compiler_call_counting = FALSE; + PROFILING = FALSE; + CALL_COUNTING = FALSE; + PRED_GOAL_EXPANSION_ALL = FALSE; + PRED_GOAL_EXPANSION_FUNC = FALSE; + PRED_GOAL_EXPANSION_ON = FALSE; + optimizer_on = TRUE; + compile_mode = 0; + profiling = FALSE; + call_counting = FALSE; - Yap_heap_regs->compiler_compile_arrays = FALSE; + compile_arrays = FALSE; #if defined(YAPOR) || defined(THREADS) - INIT_LOCK(Yap_heap_regs->dbterms_list_lock); + INIT_LOCK(DBTermsListLock); #endif - Yap_heap_regs->dbterms_list = NULL; + DBTermsList = NULL; - Yap_heap_regs->expand_clauses_first = NULL; - Yap_heap_regs->expand_clauses_last = NULL; - Yap_heap_regs->expand_clauses = 0; + ExpandClausesFirst = NULL; + ExpandClausesLast = NULL; + Yap_ExpandClauses = 0; #if defined(YAPOR) || defined(THREADS) - INIT_LOCK(Yap_heap_regs->expand_clauses_list_lock); - INIT_LOCK(Yap_heap_regs->op_list_lock); + INIT_LOCK(ExpandClausesListLock); + INIT_LOCK(OpListLock); #endif #ifdef DEBUG - Yap_heap_regs->new_cps = 0L; - Yap_heap_regs->live_cps = 0L; - Yap_heap_regs->dirty_cps = 0L; - Yap_heap_regs->freed_cps = 0L; + Yap_NewCps = 0L; + Yap_LiveCps = 0L; + Yap_DirtyCps = 0L; + Yap_FreedCps = 0L; #endif - Yap_heap_regs->expand_clauses_sz = 0L; + Yap_expand_clauses_sz = 0L; - Yap_heap_regs->udi_control_blocks = NULL; + UdiControlBlocks = NULL; - Yap_heap_regs->static_predicates_marked = FALSE; + STATIC_PREDICATES_MARKED = FALSE; - Yap_heap_regs->IntKeys = NULL; - Yap_heap_regs->IntLUKeys = NULL; - Yap_heap_regs->IntBBKeys = NULL; + INT_KEYS = NULL; + INT_LU_KEYS = NULL; + INT_BB_KEYS = NULL; - Yap_heap_regs->int_keys_size = INT_KEYS_DEFAULT_SIZE; - Yap_heap_regs->int_keys_timestamp = 0L; - Yap_heap_regs->int_bb_keys_size = INT_KEYS_DEFAULT_SIZE; + INT_KEYS_SIZE = INT_KEYS_DEFAULT_SIZE; + INT_KEYS_TIMESTAMP = 0L; + INT_BB_KEYS_SIZE = INT_KEYS_DEFAULT_SIZE; - Yap_heap_regs->update_mode = UPDATE_MODE_LOGICAL; + UPDATE_MODE = UPDATE_MODE_LOGICAL; InitDBErasedMarker(); InitLogDBErasedMarker(); - Yap_heap_regs->dead_static_clauses = NULL; - Yap_heap_regs->dead_mega_clauses = NULL; - Yap_heap_regs->dead_static_indices = NULL; - Yap_heap_regs->db_erased_list = NULL; - Yap_heap_regs->db_erased_ilist = NULL; + DeadStaticClauses = NULL; + DeadMegaClauses = NULL; + DeadStaticIndices = NULL; + DBErasedList = NULL; + DBErasedIList = NULL; #if defined(YAPOR) || defined(THREADS) - INIT_LOCK(Yap_heap_regs->dead_static_clauses_lock); - INIT_LOCK(Yap_heap_regs->dead_mega_clauses_lock); - INIT_LOCK(Yap_heap_regs->dead_static_indices_lock); + INIT_LOCK(DeadStaticClausesLock); + INIT_LOCK(DeadMegaClausesLock); + INIT_LOCK(DeadStaticIndicesLock); #endif #ifdef COROUTINING - Yap_heap_regs->num_of_atts = 1; + NUM_OF_ATTS = 1; #endif InitFlags(); - Yap_heap_regs->op_list = NULL; + OpList = NULL; - Yap_heap_regs->yap_streams = NULL; + Stream = NULL; - Yap_heap_regs->n_of_file_aliases = 0; - Yap_heap_regs->sz_of_file_aliases = 0; - Yap_heap_regs->file_aliases = NULL; + NOfFileAliases = 0; + SzOfFileAliases = 0; + FileAliases = NULL; - Yap_heap_regs->atprompt = AtomNil; + AtPrompt = AtomNil; - Yap_heap_regs->char_conversion_table = NULL; - Yap_heap_regs->char_conversion_table2 = NULL; + CharConversionTable = NULL; + CharConversionTable2 = NULL; - Yap_heap_regs->parser_error_style = EXCEPTION_ON_PARSER_ERROR; + ParserErrorStyle = EXCEPTION_ON_PARSER_ERROR; - Yap_heap_regs->yap_lib_dir = NULL; + Yap_LibDir = NULL; - Yap_heap_regs->last_wtime = NULL; + LastWtimePtr = NULL; - Yap_heap_regs->debugger_output_msg = 0L; + output_msg = 0L; #if LOW_PROF - Yap_heap_regs->profiler_on = FALSE; - Yap_heap_regs->offline_profiler = FALSE; - Yap_heap_regs->f_prof = NULL; - Yap_heap_regs->f_preds = NULL; - Yap_heap_regs->prof_preds = 0L; + ProfilerOn = FALSE; + Yap_OffLineProfiler = FALSE; + FProf = NULL; + FPreds = NULL; + ProfPreds = 0L; #endif /* LOW_PROF */ - Yap_heap_regs->foreign_code_loaded = NULL; - Yap_heap_regs->foreign_code_base = NULL; - Yap_heap_regs->foreign_code_top = NULL; - Yap_heap_regs->foreign_code_max = NULL; + ForeignCodeLoaded = NULL; + ForeignCodeBase = NULL; + ForeignCodeTop = NULL; + ForeignCodeMax = NULL; - Yap_heap_regs->yap_records = NULL; + Yap_Records = NULL; InitSWIAtoms(); - Yap_heap_regs->swi_blob_types = NULL; - Yap_heap_regs->swi_blobs = NULL; + SWI_BlobTypes = NULL; + SWI_Blobs = NULL; diff --git a/H/ilocals.h b/H/ilocals.h index d616757ae..cd030df76 100644 --- a/H/ilocals.h +++ b/H/ilocals.h @@ -1,143 +1,185 @@ - /* This file, ilocals.h, was generated automatically by "yap -L misc/buildheap" + /* This file, ilocals.h, was generated automatically by "yap -L misc/buildlocalglobal" please do not update, update misc/LOCALS instead */ static void InitWorker(int wid) { - FOREIGN(wid)->c_input_stream = 0; - FOREIGN(wid)->c_output_stream = 1; - FOREIGN(wid)->c_error_stream = 2; + REMOTE_c_input_stream(wid) = 0; + REMOTE_c_output_stream(wid) = 1; + REMOTE_c_error_stream(wid) = 2; - FOREIGN(wid)->rinfo.old_ASP = NULL; - FOREIGN(wid)->rinfo.old_LCL0 = NULL; - FOREIGN(wid)->rinfo.old_TR = NULL; - FOREIGN(wid)->rinfo.old_GlobalBase = NULL; - FOREIGN(wid)->rinfo.old_H = NULL; - FOREIGN(wid)->rinfo.old_H0 = NULL; - FOREIGN(wid)->rinfo.old_TrailBase = NULL; - FOREIGN(wid)->rinfo.old_TrailTop = NULL; - FOREIGN(wid)->rinfo.old_HeapBase = NULL; - FOREIGN(wid)->rinfo.old_HeapTop = NULL; - FOREIGN(wid)->rinfo.cl_diff = 0L; - FOREIGN(wid)->rinfo.g_diff = 0L; - FOREIGN(wid)->rinfo.h_diff = 0L; - FOREIGN(wid)->rinfo.g_diff0 = 0L; - FOREIGN(wid)->rinfo.g_split = NULL; - FOREIGN(wid)->rinfo.l_diff = 0L; - FOREIGN(wid)->rinfo.tr_diff = 0L; - FOREIGN(wid)->rinfo.x_diff = 0L; - FOREIGN(wid)->rinfo.delay_diff = 0L; - FOREIGN(wid)->rinfo.base_diff = 0L; - FOREIGN(wid)->call_counters.reductions = 0L; - FOREIGN(wid)->call_counters.reductions_retries = 0L; - FOREIGN(wid)->call_counters.retries = 0L; - FOREIGN(wid)->call_counters.reductions_on = 0L; - FOREIGN(wid)->call_counters.reductions_retries_on = 0L; - FOREIGN(wid)->call_counters.retries_on = 0L; - FOREIGN(wid)->interrupts_disabled = FALSE; + REMOTE_OldASP(wid) = NULL; + REMOTE_OldLCL0(wid) = NULL; + REMOTE_OldTR(wid) = NULL; + REMOTE_OldGlobalBase(wid) = NULL; + REMOTE_OldH(wid) = NULL; + REMOTE_OldH0(wid) = NULL; + REMOTE_OldTrailBase(wid) = NULL; + REMOTE_OldTrailTop(wid) = NULL; + REMOTE_OldHeapBase(wid) = NULL; + REMOTE_OldHeapTop(wid) = NULL; + REMOTE_ClDiff(wid) = 0L; + REMOTE_GDiff(wid) = 0L; + REMOTE_HDiff(wid) = 0L; + REMOTE_GDiff0(wid) = 0L; + REMOTE_GSplit(wid) = NULL; + REMOTE_LDiff(wid) = 0L; + REMOTE_TrDiff(wid) = 0L; + REMOTE_XDiff(wid) = 0L; + REMOTE_DelayDiff(wid) = 0L; + REMOTE_BaseDiff(wid) = 0L; + + REMOTE_ReductionsCounter(wid) = 0L; + REMOTE_PredEntriesCounter(wid) = 0L; + REMOTE_RetriesCounter(wid) = 0L; + REMOTE_ReductionsCounterOn(wid) = 0L; + REMOTE_PredEntriesCounterOn(wid) = 0L; + REMOTE_RetriesCounterOn(wid) = 0L; - FOREIGN(wid)->consultsp = NULL; + REMOTE_ConsultSp(wid) = NULL; - FOREIGN(wid)->consultbase = NULL; + REMOTE_ConsultBase(wid) = NULL; - FOREIGN(wid)->consultlow = NULL; + REMOTE_ConsultLow(wid) = NULL; - FOREIGN(wid)->global_arena = 0L; - FOREIGN(wid)->global_arena_overflows = 0L; - FOREIGN(wid)->delay_arena_overflows = 0L; - FOREIGN(wid)->arena_overflows = 0L; - FOREIGN(wid)->depth_arenas = 0; - FOREIGN(wid)->arith_error = FALSE; - FOREIGN(wid)->last_asserted_pred = NULL; - FOREIGN(wid)->debug_on = FALSE; - FOREIGN(wid)->f_info = NULL; - FOREIGN(wid)->scanner_stack = NULL; - FOREIGN(wid)->scanner_extra_blocks = NULL; - FOREIGN(wid)->ball_term = NULL; - FOREIGN(wid)->active_signals = 0L; - FOREIGN(wid)->i_pred_arity = 0L; - FOREIGN(wid)->prof_end = NULL; - FOREIGN(wid)->uncaught_throw = FALSE; - FOREIGN(wid)->doing_undefp = FALSE; - FOREIGN(wid)->start_line = 0L; + REMOTE_GlobalArena(wid) = 0L; + REMOTE_GlobalArenaOverflows(wid) = 0L; + REMOTE_ArenaOverflows(wid) = 0L; + REMOTE_DepthArenas(wid) = 0; + REMOTE_ArithError(wid) = FALSE; + REMOTE_LastAssertedPred(wid) = NULL; + REMOTE_DebugOn(wid) = FALSE; + REMOTE_ScannerStack(wid) = NULL; + REMOTE_ScannerExtraBlocks(wid) = NULL; + REMOTE_BallTerm(wid) = NULL; + REMOTE_ActiveSignals(wid) = 0L; + REMOTE_IPredArity(wid) = 0L; + REMOTE_ProfEnd(wid) = NULL; + REMOTE_UncaughtThrow(wid) = FALSE; + REMOTE_DoingUndefp(wid) = FALSE; + REMOTE_StartLine(wid) = 0L; InitScratchPad(wid); #ifdef COROUTINING - FOREIGN(wid)->woken_goals = 0L; - FOREIGN(wid)->atts_mutable_list = 0L; + REMOTE_WokenGoals(wid) = 0L; + REMOTE_AttsMutableList(wid) = 0L; #endif - FOREIGN(wid)->gc_generation = 0L; - FOREIGN(wid)->gc_phase = 0L; - FOREIGN(wid)->gc_current_phase = 0L; - FOREIGN(wid)->gc_calls = 0L; - FOREIGN(wid)->tot_gc_time = 0L; - FOREIGN(wid)->tot_gc_recovered = 0L; - FOREIGN(wid)->last_gc_time = 0L; - FOREIGN(wid)->last_ss_time = 0L; -#if LOW_LEVEL_TRACER - FOREIGN(wid)->total_cps = 0; + REMOTE_GcGeneration(wid) = 0L; + REMOTE_GcPhase(wid) = 0L; + REMOTE_GcCurrentPhase(wid) = 0L; + REMOTE_GcCalls(wid) = 0L; + REMOTE_TotGcTime(wid) = 0L; + REMOTE_TotGcRecovered(wid) = 0L; + REMOTE_LastGcTime(wid) = 0L; + REMOTE_LastSSTime(wid) = 0L; + + REMOTE_total_marked(wid) = 0L; + REMOTE_total_oldies(wid) = 0L; + REMOTE_current_B(wid) = NULL; + REMOTE_prev_HB(wid) = NULL; + REMOTE_HGEN(wid) = NULL; + REMOTE_iptop(wid) = NULL; +#if defined(GC_NO_TAGS) + REMOTE_bp(wid) = NULL; #endif - FOREIGN(wid)->consult_level_ = 0; + REMOTE_sTR(wid) = NULL; + REMOTE_sTR0(wid) = NULL; + REMOTE_new_TR(wid) = NULL; + REMOTE_cont_top0(wid) = NULL; + REMOTE_cont_top(wid) = NULL; + REMOTE_discard_trail_entries(wid) = 0; -#if defined(YAPOR) || defined(THREADS) - INIT_LOCK(FOREIGN(wid)->signal_lock); - FOREIGN(wid)->wpp = NULL; + REMOTE_gc_ma_h_top(wid) = NULL; + REMOTE_gc_ma_h_list(wid) = NULL; + REMOTE_gc_timestamp(wid) = 0L; + REMOTE_db_vec(wid) = NULL; + REMOTE_db_vec0(wid) = NULL; + REMOTE_db_root(wid) = NULL; + REMOTE_db_nil(wid) = NULL; - FOREIGN(wid)->tot_marked = 0L; - FOREIGN(wid)->tot_oldies = 0L; -#if DEBUG && COROUTINING - FOREIGN(wid)->tot_smarked = 0L; -#endif - FOREIGN(wid)->wl_current_B = NULL; - FOREIGN(wid)->wl_prev_HB = NULL; - FOREIGN(wid)->hgen = NULL; - FOREIGN(wid)->ip_top = NULL; -#if GC_NO_TAGS - FOREIGN(wid)->b_p = NULL; -#endif -#if defined(TABLING) || defined(YAPOR_SBA) - FOREIGN(wid)->wl_sTR = NULL; - FOREIGN(wid)->wl_sTR0 = NULL; - FOREIGN(wid)->new_tr = NULL; -#else - FOREIGN(wid)->wl_sTR = NULL; - FOREIGN(wid)->wl_sTR0 = NULL; - FOREIGN(wid)->new_tr = NULL; -#endif - FOREIGN(wid)->conttop0 = NULL; - FOREIGN(wid)->conttop = NULL; - FOREIGN(wid)->disc_trail_entries = 0; + REMOTE_DynamicArrays(wid) = NULL; + REMOTE_StaticArrays(wid) = NULL; + REMOTE_GlobalVariables(wid) = NULL; + REMOTE_AllowRestart(wid) = FALSE; - FOREIGN(wid)->Gc_ma_h_top = NULL; - FOREIGN(wid)->Gc_ma_h_list = NULL; - FOREIGN(wid)->Gc_timestamp = 0L; - FOREIGN(wid)->DB_vec = NULL; - FOREIGN(wid)->DB_vec0 = NULL; - FOREIGN(wid)->DB_root = NULL; - FOREIGN(wid)->DB_nil = NULL; -#endif /* defined(YAPOR) || defined(THREADS) */ + REMOTE_CMemFirstBlock(wid) = NULL; + REMOTE_CMemFirstBlockSz(wid) = 0L; - FOREIGN(wid)->dynamic_arrays = NULL; - FOREIGN(wid)->static_arrays = NULL; - FOREIGN(wid)->global_variables = NULL; - FOREIGN(wid)->allow_restart = FALSE; + REMOTE_LabelFirstArray(wid) = NULL; + REMOTE_LabelFirstArraySz(wid) = 0L; - FOREIGN(wid)->cmem_first_block = NULL; - FOREIGN(wid)->cmem_first_block_sz = 0L; - - FOREIGN(wid)->label_first_array = NULL; - FOREIGN(wid)->label_first_array_sz = 0L; - - FOREIGN(wid)->Yap_ld_ = Yap_InitThreadIO(wid); - FOREIGN(wid)->_execution = NULL; + REMOTE_PL_local_data_p(wid) = Yap_InitThreadIO(wid); #ifdef THREADS InitThreadHandle(wid); -#define FOREIGN_ThreadHandle(wid) (Yap_WLocal[(wid)]->thread_handle) -#define MY_ThreadHandle (Yap_WLocal[worker_id]->thread_handle) +#endif /* THREADS */ +#if defined(YAPOR) || defined(TABLING) + Yap_init_local_optyap_data(wid); +#endif /* YAPOR || TABLING */ + REMOTE_InterruptsDisabled(wid) = FALSE; + REMOTE_execution(wid) = NULL; +#if LOW_LEVEL_TRACER + REMOTE_total_choicepoints(wid) = 0; +#endif + REMOTE_consult_level(wid) = 0; +#if defined(YAPOR) || defined(THREADS) + INIT_LOCK(REMOTE_SignalLock(wid)); #endif + + + + + + +#ifdef THREADS + +#else + +#endif + + + + + + + + + + + + REMOTE_PrologMode(wid) = BootMode; + REMOTE_CritLocks(wid) = 0; + + +#ifdef ANALYST + + +#endif /* ANALYST */ + + + + REMOTE_matherror(wid) = YAP_NO_ERROR; + + REMOTE_heap_overflows(wid) = 0; + REMOTE_total_heap_overflow_time(wid) = 0; + REMOTE_stack_overflows(wid) = 0; + REMOTE_total_stack_overflow_time(wid) = 0; + REMOTE_delay_overflows(wid) = 0; + REMOTE_total_delay_overflow_time(wid) = 0; + REMOTE_trail_overflows(wid) = 0; + REMOTE_total_trail_overflow_time(wid) = 0; + REMOTE_atom_table_overflows(wid) = 0; + REMOTE_total_atom_table_overflow_time(wid) = 0; + +#ifdef LOAD_DYLD + REMOTE_dl_errno(wid) = 0; +#endif + +#ifdef LOW_LEVEL_TRACER + REMOTE_do_trace_primitives(wid) = TRUE; +#endif } diff --git a/H/iopreds.h b/H/iopreds.h index 887f98684..f44373881 100644 --- a/H/iopreds.h +++ b/H/iopreds.h @@ -115,4 +115,5 @@ StreamDesc; void STD_PROTO (Yap_InitStdStreams, (void)); Term STD_PROTO (Yap_StreamPosition, (struct io_stream *)); +void STD_PROTO (Yap_InitPlIO, (void)); diff --git a/H/rglobals.h b/H/rglobals.h index c7bdffff9..289f14458 100644 --- a/H/rglobals.h +++ b/H/rglobals.h @@ -1,5 +1,5 @@ - /* This file, rglobals.h, was generated automatically by "yap -L misc/buildheap" + /* This file, rglobals.h, was generated automatically by "yap -L misc/buildlocalglobal" please do not update, update misc/GLOBALS instead */ @@ -18,10 +18,23 @@ - - static void RestoreGlobal(void) { + + + + + + + + + + + + + + + #if THREADS @@ -29,29 +42,31 @@ static void RestoreGlobal(void) { -#endif + REINIT_LOCK(GLOBAL_ThreadHandlesLock); +#endif #if defined(YAPOR) || defined(THREADS) - REINIT_LOCK(Yap_global->bgl); + REINIT_LOCK(GLOBAL_BGL); #endif - - - - - - - - - - - -#ifdef THREADS - REINIT_LOCK(Yap_global->thread_handles_lock); -#endif - #if defined(YAPOR) || defined(TABLING) +#endif /* YAPOR || TABLING */ + + + +#if defined(THREADS) + +#endif /* THREADS */ + + + + + + + +#ifdef COROUTINING + #endif @@ -61,4 +76,35 @@ static void RestoreGlobal(void) { + +#if HAVE_MMAP + +#endif +#ifdef DEBUG + + + + + +#endif + + + + + + + + + + + +#if defined(COFF) || defined(A_OUT) + + +#endif +#if __simplescalar__ + +#endif + + } diff --git a/H/rheap.h b/H/rheap.h index 8029d7ee5..341094f26 100755 --- a/H/rheap.h +++ b/H/rheap.h @@ -1016,9 +1016,9 @@ static void RestoreBallTerm(int wid) { CACHE_REGS - if (BallTerm) { - BallTerm = DBTermAdjust(BallTerm); - RestoreDBTerm(BallTerm, TRUE PASS_REGS); + if (LOCAL_BallTerm) { + LOCAL_BallTerm = DBTermAdjust(LOCAL_BallTerm); + RestoreDBTerm(LOCAL_BallTerm, TRUE PASS_REGS); } } @@ -1030,7 +1030,7 @@ static void restore_codes(void) { CACHE_REGS - Yap_heap_regs->heap_top = AddrAdjust(OldHeapTop); + Yap_heap_regs->heap_top = AddrAdjust(LOCAL_OldHeapTop); #include "rhstruct.h" RestoreGlobal(); #ifndef worker_id diff --git a/H/rhstruct.h b/H/rhstruct.h index 71e37aad3..323c3daf7 100644 --- a/H/rhstruct.h +++ b/H/rhstruct.h @@ -35,7 +35,7 @@ #if defined(YAPOR) || defined(THREADS) - REINIT_LOCK(Yap_heap_regs->dlmalloc_lock); + REINIT_LOCK(DLMallocLock); #endif #endif #if USE_DL_MALLOC || (USE_SYSTEM_MALLOC && HAVE_MALLINFO) @@ -51,24 +51,24 @@ #if defined(YAPOR) || defined(THREADS) - REINIT_LOCK(Yap_heap_regs->free_blocks_lock); - REINIT_LOCK(Yap_heap_regs->heap_used_lock); - REINIT_LOCK(Yap_heap_regs->heap_top_lock); + REINIT_LOCK(FreeBlocksLock); + REINIT_LOCK(HeapUsedLock); + REINIT_LOCK(HeapTopLock); #endif #if USE_THREADED_CODE - Yap_heap_regs->op_rtable = OpRTableAdjust(Yap_heap_regs->op_rtable); + OP_RTABLE = OpRTableAdjust(OP_RTABLE); #endif - Yap_heap_regs->execute_cpred_op_code = Yap_opcode(_execute_cpred); - Yap_heap_regs->expand_op_code = Yap_opcode(_expand_index); - Yap_heap_regs->fail_op = Yap_opcode(_op_fail); - Yap_heap_regs->index_op = Yap_opcode(_index_pred); - Yap_heap_regs->lockpred_op = Yap_opcode(_lock_pred); - Yap_heap_regs->orlast_op = Yap_opcode(_or_last); - Yap_heap_regs->undef_op = Yap_opcode(_undef_p); + EXECUTE_CPRED_OP_CODE = Yap_opcode(_execute_cpred); + EXPAND_OP_CODE = Yap_opcode(_expand_index); + FAIL_OPCODE = Yap_opcode(_op_fail); + INDEX_OPCODE = Yap_opcode(_index_pred); + LOCKPRED_OPCODE = Yap_opcode(_lock_pred); + ORLAST_OPCODE = Yap_opcode(_or_last); + UNDEF_OPCODE = Yap_opcode(_undef_p); @@ -80,27 +80,27 @@ #include "ratoms.h" #ifdef EUROTRA - Yap_heap_regs->term_dollar_u = AtomTermAdjust(Yap_heap_regs->term_dollar_u); + TermDollarU = AtomTermAdjust(TermDollarU); #endif - Yap_heap_regs->term_prolog = AtomTermAdjust(Yap_heap_regs->term_prolog); - Yap_heap_regs->term_refound_var = AtomTermAdjust(Yap_heap_regs->term_refound_var); - Yap_heap_regs->user_module = AtomTermAdjust(Yap_heap_regs->user_module); - Yap_heap_regs->idb_module = AtomTermAdjust(Yap_heap_regs->idb_module); - Yap_heap_regs->attributes_module = AtomTermAdjust(Yap_heap_regs->attributes_module); - Yap_heap_regs->charsio_module = AtomTermAdjust(Yap_heap_regs->charsio_module); - Yap_heap_regs->terms_module = AtomTermAdjust(Yap_heap_regs->terms_module); - Yap_heap_regs->system_module = AtomTermAdjust(Yap_heap_regs->system_module); - Yap_heap_regs->operating_system_module = AtomTermAdjust(Yap_heap_regs->operating_system_module); - Yap_heap_regs->readutil_module = AtomTermAdjust(Yap_heap_regs->readutil_module); - Yap_heap_regs->hacks_module = AtomTermAdjust(Yap_heap_regs->hacks_module); - Yap_heap_regs->arg_module = AtomTermAdjust(Yap_heap_regs->arg_module); - Yap_heap_regs->globals_module = AtomTermAdjust(Yap_heap_regs->globals_module); - Yap_heap_regs->swi_module = AtomTermAdjust(Yap_heap_regs->swi_module); - Yap_heap_regs->dbload_module = AtomTermAdjust(Yap_heap_regs->dbload_module); + TermProlog = AtomTermAdjust(TermProlog); + TermReFoundVar = AtomTermAdjust(TermReFoundVar); + USER_MODULE = AtomTermAdjust(USER_MODULE); + IDB_MODULE = AtomTermAdjust(IDB_MODULE); + ATTRIBUTES_MODULE = AtomTermAdjust(ATTRIBUTES_MODULE); + CHARSIO_MODULE = AtomTermAdjust(CHARSIO_MODULE); + TERMS_MODULE = AtomTermAdjust(TERMS_MODULE); + SYSTEM_MODULE = AtomTermAdjust(SYSTEM_MODULE); + OPERATING_SYSTEM_MODULE = AtomTermAdjust(OPERATING_SYSTEM_MODULE); + READUTIL_MODULE = AtomTermAdjust(READUTIL_MODULE); + HACKS_MODULE = AtomTermAdjust(HACKS_MODULE); + ARG_MODULE = AtomTermAdjust(ARG_MODULE); + GLOBALS_MODULE = AtomTermAdjust(GLOBALS_MODULE); + SWI_MODULE = AtomTermAdjust(SWI_MODULE); + DBLOAD_MODULE = AtomTermAdjust(DBLOAD_MODULE); - Yap_heap_regs->current_modules = ModEntryPtrAdjust(Yap_heap_regs->current_modules); + CurrentModules = ModEntryPtrAdjust(CurrentModules); @@ -114,36 +114,36 @@ - Yap_heap_regs->creep_code = PtoPredAdjust(Yap_heap_regs->creep_code); - Yap_heap_regs->undef_code = PtoPredAdjust(Yap_heap_regs->undef_code); - Yap_heap_regs->spy_code = PtoPredAdjust(Yap_heap_regs->spy_code); - Yap_heap_regs->pred_fail = PtoPredAdjust(Yap_heap_regs->pred_fail); - Yap_heap_regs->pred_true = PtoPredAdjust(Yap_heap_regs->pred_true); + CreepCode = PtoPredAdjust(CreepCode); + UndefCode = PtoPredAdjust(UndefCode); + SpyCode = PtoPredAdjust(SpyCode); + PredFail = PtoPredAdjust(PredFail); + PredTrue = PtoPredAdjust(PredTrue); #ifdef COROUTINING - Yap_heap_regs->wake_up_code = PtoPredAdjust(Yap_heap_regs->wake_up_code); + WakeUpCode = PtoPredAdjust(WakeUpCode); #endif - Yap_heap_regs->pred_goal_expansion = PtoPredAdjust(Yap_heap_regs->pred_goal_expansion); - Yap_heap_regs->pred_meta_call = PtoPredAdjust(Yap_heap_regs->pred_meta_call); - Yap_heap_regs->pred_dollar_catch = PtoPredAdjust(Yap_heap_regs->pred_dollar_catch); - Yap_heap_regs->pred_recorded_with_key = PtoPredAdjust(Yap_heap_regs->pred_recorded_with_key); - Yap_heap_regs->pred_log_upd_clause = PtoPredAdjust(Yap_heap_regs->pred_log_upd_clause); - Yap_heap_regs->pred_log_upd_clause_erase = PtoPredAdjust(Yap_heap_regs->pred_log_upd_clause_erase); - Yap_heap_regs->pred_log_upd_clause0 = PtoPredAdjust(Yap_heap_regs->pred_log_upd_clause0); - Yap_heap_regs->pred_static_clause = PtoPredAdjust(Yap_heap_regs->pred_static_clause); - Yap_heap_regs->pred_throw = PtoPredAdjust(Yap_heap_regs->pred_throw); - Yap_heap_regs->pred_handle_throw = PtoPredAdjust(Yap_heap_regs->pred_handle_throw); - Yap_heap_regs->pred_is = PtoPredAdjust(Yap_heap_regs->pred_is); - Yap_heap_regs->pred_safe_call_cleanup = PtoPredAdjust(Yap_heap_regs->pred_safe_call_cleanup); - Yap_heap_regs->pred_restore_regs = PtoPredAdjust(Yap_heap_regs->pred_restore_regs); + PredGoalExpansion = PtoPredAdjust(PredGoalExpansion); + PredMetaCall = PtoPredAdjust(PredMetaCall); + PredDollarCatch = PtoPredAdjust(PredDollarCatch); + PredRecordedWithKey = PtoPredAdjust(PredRecordedWithKey); + PredLogUpdClause = PtoPredAdjust(PredLogUpdClause); + PredLogUpdClauseErase = PtoPredAdjust(PredLogUpdClauseErase); + PredLogUpdClause0 = PtoPredAdjust(PredLogUpdClause0); + PredStaticClause = PtoPredAdjust(PredStaticClause); + PredThrow = PtoPredAdjust(PredThrow); + PredHandleThrow = PtoPredAdjust(PredHandleThrow); + PredIs = PtoPredAdjust(PredIs); + PredSafeCallCleanup = PtoPredAdjust(PredSafeCallCleanup); + PredRestoreRegs = PtoPredAdjust(PredRestoreRegs); #ifdef YAPOR - Yap_heap_regs->pred_getwork = PtoPredAdjust(Yap_heap_regs->pred_getwork); - Yap_heap_regs->pred_getwork_seq = PtoPredAdjust(Yap_heap_regs->pred_getwork_seq); + PredGetwork = PtoPredAdjust(PredGetwork); + PredGetworkSeq = PtoPredAdjust(PredGetworkSeq); #endif /* YAPOR */ #ifdef LOW_LEVEL_TRACER #if defined(YAPOR) || defined(THREADS) - REINIT_LOCK(Yap_heap_regs->low_level_trace_lock); + REINIT_LOCK(Yap_low_level_trace_lock); #endif #endif @@ -158,22 +158,22 @@ - Yap_heap_regs->dummycode->opc = Yap_opcode(_op_fail); - Yap_heap_regs->failcode->opc = Yap_opcode(_op_fail); - Yap_heap_regs->nocode->opc = Yap_opcode(_Nstop); + DUMMYCODE->opc = Yap_opcode(_op_fail); + FAILCODE->opc = Yap_opcode(_op_fail); + NOCODE->opc = Yap_opcode(_Nstop); RestoreEnvInst(ENV_FOR_TRUSTFAIL,&TRUSTFAILCODE,_trust_fail,PredFail); RestoreEnvInst(ENV_FOR_YESCODE,&YESCODE,_Ystop,PredFail); RestoreOtaplInst(RTRYCODE,_retry_and_mark,PredFail); #ifdef BEAM - Yap_heap_regs->beam_retry_code->opc = Yap_opcode(_beam_retry_code); + BEAM_RETRY_CODE->opc = Yap_opcode(_beam_retry_code); #endif /* BEAM */ #ifdef YAPOR RestoreOtaplInst(GETWORK,_getwork,PredGetwork); RestoreOtaplInst(GETWORK_SEQ,_getwork_seq,PredGetworkSeq); - Yap_heap_regs->getwork_first_time->opc = Yap_opcode(_getwork_first_time); + GETWORK_FIRST_TIME->opc = Yap_opcode(_getwork_first_time); #endif /* YAPOR */ #ifdef TABLING RestoreOtaplInst(LOAD_ANSWER,_table_load_answer,PredFail); @@ -185,10 +185,10 @@ - Yap_heap_regs->debugger_p_before_spy = PtoOpAdjust(Yap_heap_regs->debugger_p_before_spy); + P_before_spy = PtoOpAdjust(P_before_spy); - Yap_heap_regs->retry_recordedp_code = PtoOpAdjust(Yap_heap_regs->retry_recordedp_code); - Yap_heap_regs->retry_recorded_k_code = PtoOpAdjust(Yap_heap_regs->retry_recorded_k_code); + RETRY_C_RECORDEDP_CODE = PtoOpAdjust(RETRY_C_RECORDEDP_CODE); + RETRY_C_RECORDED_K_CODE = PtoOpAdjust(RETRY_C_RECORDED_K_CODE); @@ -203,7 +203,7 @@ #if defined(YAPOR) || defined(THREADS) - REINIT_LOCK(Yap_heap_regs->dbterms_list_lock); + REINIT_LOCK(DBTermsListLock); #endif RestoreDBTermsList(); @@ -211,8 +211,8 @@ RestoreExpandList(); #if defined(YAPOR) || defined(THREADS) - REINIT_LOCK(Yap_heap_regs->expand_clauses_list_lock); - REINIT_LOCK(Yap_heap_regs->op_list_lock); + REINIT_LOCK(ExpandClausesListLock); + REINIT_LOCK(OpListLock); #endif #ifdef DEBUG @@ -247,9 +247,9 @@ RestoreDBErasedList(); RestoreDBErasedIList(); #if defined(YAPOR) || defined(THREADS) - REINIT_LOCK(Yap_heap_regs->dead_static_clauses_lock); - REINIT_LOCK(Yap_heap_regs->dead_mega_clauses_lock); - REINIT_LOCK(Yap_heap_regs->dead_static_indices_lock); + REINIT_LOCK(DeadStaticClausesLock); + REINIT_LOCK(DeadMegaClausesLock); + REINIT_LOCK(DeadStaticIndicesLock); #endif #ifdef COROUTINING @@ -260,7 +260,7 @@ - Yap_heap_regs->op_list = OpListAdjust(Yap_heap_regs->op_list); + OpList = OpListAdjust(OpList); RestoreStreams(); @@ -269,17 +269,17 @@ RestoreAliases(); - Yap_heap_regs->atprompt = AtomAdjust(Yap_heap_regs->atprompt); + AtPrompt = AtomAdjust(AtPrompt); - Yap_heap_regs->char_conversion_table = CodeCharPAdjust(Yap_heap_regs->char_conversion_table); - Yap_heap_regs->char_conversion_table2 = CodeCharPAdjust(Yap_heap_regs->char_conversion_table2); + CharConversionTable = CodeCharPAdjust(CharConversionTable); + CharConversionTable2 = CodeCharPAdjust(CharConversionTable2); - Yap_heap_regs->yap_lib_dir = CodeCharPAdjust(Yap_heap_regs->yap_lib_dir); + Yap_LibDir = CodeCharPAdjust(Yap_LibDir); - Yap_heap_regs->last_wtime = CodeVoidPAdjust(Yap_heap_regs->last_wtime); + LastWtimePtr = CodeVoidPAdjust(LastWtimePtr); #if LOW_PROF diff --git a/H/rlocals.h b/H/rlocals.h index 39d783c70..44d5a5277 100644 --- a/H/rlocals.h +++ b/H/rlocals.h @@ -1,5 +1,5 @@ - /* This file, rlocals.h, was generated automatically by "yap -L misc/buildheap" + /* This file, rlocals.h, was generated automatically by "yap -L misc/buildlocalglobal" please do not update, update misc/LOCALS instead */ @@ -46,9 +46,7 @@ static void RestoreWorker(int wid USES_REGS) { - FOREIGN(wid)->global_arena = TermToGlobalOrAtomAdjust(FOREIGN(wid)->global_arena); - - + REMOTE_GlobalArena(wid) = TermToGlobalOrAtomAdjust(REMOTE_GlobalArena(wid)); @@ -66,46 +64,26 @@ static void RestoreWorker(int wid USES_REGS) { #ifdef COROUTINING - FOREIGN(wid)->woken_goals = TermToGlobalAdjust(FOREIGN(wid)->woken_goals); - FOREIGN(wid)->atts_mutable_list = TermToGlobalAdjust(FOREIGN(wid)->atts_mutable_list); + REMOTE_WokenGoals(wid) = TermToGlobalAdjust(REMOTE_WokenGoals(wid)); + REMOTE_AttsMutableList(wid) = TermToGlobalAdjust(REMOTE_AttsMutableList(wid)); #endif - FOREIGN(wid)->gc_generation = TermToGlobalAdjust(FOREIGN(wid)->gc_generation); - FOREIGN(wid)->gc_phase = TermToGlobalAdjust(FOREIGN(wid)->gc_phase); + REMOTE_GcGeneration(wid) = TermToGlobalAdjust(REMOTE_GcGeneration(wid)); + REMOTE_GcPhase(wid) = TermToGlobalAdjust(REMOTE_GcPhase(wid)); -#if LOW_LEVEL_TRACER - -#endif - - -#if defined(YAPOR) || defined(THREADS) - REINIT_LOCK(FOREIGN(wid)->signal_lock); -#if DEBUG && COROUTINING - -#endif - -#if GC_NO_TAGS - -#endif -#if defined(TABLING) || defined(YAPOR_SBA) - - - -#else - - +#if defined(GC_NO_TAGS) #endif @@ -119,14 +97,15 @@ static void RestoreWorker(int wid USES_REGS) { -#endif /* defined(YAPOR) || defined(THREADS) */ - FOREIGN(wid)->dynamic_arrays = PtoArrayEAdjust(FOREIGN(wid)->dynamic_arrays); - FOREIGN(wid)->static_arrays = PtoArraySAdjust(FOREIGN(wid)->static_arrays); - FOREIGN(wid)->global_variables = PtoGlobalEAdjust(FOREIGN(wid)->global_variables); + REMOTE_DynamicArrays(wid) = PtoArrayEAdjust(REMOTE_DynamicArrays(wid)); + REMOTE_StaticArrays(wid) = PtoArraySAdjust(REMOTE_StaticArrays(wid)); + REMOTE_GlobalVariables(wid) = PtoGlobalEAdjust(REMOTE_GlobalVariables(wid)); + + @@ -136,8 +115,71 @@ static void RestoreWorker(int wid USES_REGS) { #ifdef THREADS -#define FOREIGN_ThreadHandle(wid) (Yap_WLocal[(wid)]->thread_handle) -#define MY_ThreadHandle (Yap_WLocal[worker_id]->thread_handle) +#endif /* THREADS */ +#if defined(YAPOR) || defined(TABLING) + +#endif /* YAPOR || TABLING */ + + +#if LOW_LEVEL_TRACER + #endif +#if defined(YAPOR) || defined(THREADS) + REINIT_LOCK(REMOTE_SignalLock(wid)); +#endif + + + + + + + +#ifdef THREADS + +#else + +#endif + + + + + + + + + + + + + + + +#ifdef ANALYST + + +#endif /* ANALYST */ + + + + + + + + + + + + + + + + +#ifdef LOAD_DYLD + +#endif + +#ifdef LOW_LEVEL_TRACER + +#endif } diff --git a/H/sshift.h b/H/sshift.h index 51bfaf5f5..e0c7c61bd 100755 --- a/H/sshift.h +++ b/H/sshift.h @@ -124,7 +124,7 @@ inline EXTERN int IsHeapP__ (CELL * ptr USES_REGS) { #if USE_SYSTEM_MALLOC - return (int) ((ptr < (CELL *) Yap_GlobalBase || ptr > (CELL *) Yap_TrailTop)); + return (int) ((ptr < (CELL *) LOCAL_GlobalBase || ptr > (CELL *) LOCAL_TrailTop)); #else return (int) ((ptr >= (CELL *) Yap_HeapBase && ptr <= (CELL *) HeapTop)); #endif @@ -140,13 +140,13 @@ inline EXTERN CELL *PtoGloAdjust__ (CELL * CACHE_TYPE); inline EXTERN CELL * PtoGloAdjust__ (CELL * ptr USES_REGS) { - if (ptr < GSplit) { + if (ptr < LOCAL_GSplit) { if (ptr < H0) - return (CELL *) (((CELL *) (CharP (ptr) + DelayDiff))); + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_DelayDiff))); else - return (CELL *) (((CELL *) (CharP (ptr) + GDiff0))); + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_GDiff0))); } else { - return (CELL *) (((CELL *) (CharP (ptr) + GDiff))); + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_GDiff))); } } @@ -157,10 +157,10 @@ inline EXTERN CELL *PtoDelayAdjust__ (CELL * CACHE_TYPE); inline EXTERN CELL * PtoDelayAdjust__ (CELL * ptr USES_REGS) { - if (!GSplit || ptr < GSplit) - return (CELL *) (((CELL *) (CharP (ptr) + DelayDiff))); + if (!LOCAL_GSplit || ptr < LOCAL_GSplit) + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_DelayDiff))); else - return (CELL *) (((CELL *) (CharP (ptr) + GDiff0))); + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_GDiff0))); } inline EXTERN CELL *PtoBaseAdjust__ (CELL * CACHE_TYPE); @@ -168,7 +168,7 @@ inline EXTERN CELL *PtoBaseAdjust__ (CELL * CACHE_TYPE); inline EXTERN CELL * PtoBaseAdjust__ (CELL * ptr USES_REGS) { - return (CELL *) (((CELL *) (CharP (ptr) + BaseDiff))); + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_BaseDiff))); } @@ -178,7 +178,7 @@ inline EXTERN tr_fr_ptr PtoTRAdjust__ (tr_fr_ptr CACHE_TYPE); inline EXTERN tr_fr_ptr PtoTRAdjust__ (tr_fr_ptr ptr USES_REGS) { - return (tr_fr_ptr) (((tr_fr_ptr) (CharP (ptr) + TrDiff))); + return (tr_fr_ptr) (((tr_fr_ptr) (CharP (ptr) + LOCAL_TrDiff))); } @@ -188,7 +188,7 @@ inline EXTERN CELL *CellPtoTRAdjust__ (CELL * CACHE_TYPE); inline EXTERN CELL * CellPtoTRAdjust__ (CELL * ptr USES_REGS) { - return (CELL *) (((CELL *) (CharP (ptr) + TrDiff))); + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_TrDiff))); } @@ -198,7 +198,7 @@ inline EXTERN CELL *PtoLocAdjust__ (CELL * CACHE_TYPE); inline EXTERN CELL * PtoLocAdjust__ (CELL * ptr USES_REGS) { - return (CELL *) (((CELL *) (CharP (ptr) + LDiff))); + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_LDiff))); } @@ -207,7 +207,7 @@ inline EXTERN struct cut_c_str *CutCAdjust__ (struct cut_c_str * CACHE_TYPE); inline EXTERN struct cut_c_str * CutCAdjust__ (struct cut_c_str * ptr USES_REGS) { - return (struct cut_c_str *) (CharP (ptr) + LDiff); + return (struct cut_c_str *) (CharP (ptr) + LOCAL_LDiff); } @@ -217,7 +217,7 @@ inline EXTERN choiceptr ChoicePtrAdjust__ (choiceptr CACHE_TYPE); inline EXTERN choiceptr ChoicePtrAdjust__ (choiceptr ptr USES_REGS) { - return (choiceptr) (((choiceptr) (CharP (ptr) + LDiff))); + return (choiceptr) (((choiceptr) (CharP (ptr) + LOCAL_LDiff))); } @@ -228,7 +228,7 @@ inline EXTERN choiceptr ConsumerChoicePtrAdjust__ (choiceptr CACHE_TYPE); inline EXTERN choiceptr ConsumerChoicePtrAdjust__ (choiceptr ptr USES_REGS) { - return (choiceptr) (((choiceptr) (CharP (ptr) + LDiff))); + return (choiceptr) (((choiceptr) (CharP (ptr) + LOCAL_LDiff))); } @@ -238,7 +238,7 @@ inline EXTERN choiceptr GeneratorChoicePtrAdjust__ (choiceptr CACHE_TYPE); inline EXTERN choiceptr GeneratorChoicePtrAdjust__ (choiceptr ptr USES_REGS) { - return (choiceptr) (((choiceptr) (CharP (ptr) + LDiff))); + return (choiceptr) (((choiceptr) (CharP (ptr) + LOCAL_LDiff))); } @@ -250,13 +250,13 @@ inline EXTERN CELL GlobalAdjust__ (CELL CACHE_TYPE); inline EXTERN CELL GlobalAdjust__ (CELL val USES_REGS) { - if ((CELL *)val < GSplit) { + if ((CELL *)val < LOCAL_GSplit) { if ((CELL *)val < H0) - return (CELL) (val + DelayDiff); + return (CELL) (val + LOCAL_DelayDiff); else - return (CELL) (val + GDiff0); + return (CELL) (val + LOCAL_GDiff0); } else { - return (CELL) (val + GDiff); + return (CELL) (val + LOCAL_GDiff); } } @@ -267,10 +267,10 @@ inline EXTERN CELL DelayAdjust__ (CELL CACHE_TYPE); inline EXTERN CELL DelayAdjust__ (CELL val USES_REGS) { - if (!GSplit || (CELL *)val < GSplit) - return (CELL) (val + DelayDiff); + if (!LOCAL_GSplit || (CELL *)val < LOCAL_GSplit) + return (CELL) (val + LOCAL_DelayDiff); else - return (CELL) (val + GDiff0); + return (CELL) (val + LOCAL_GDiff0); } @@ -279,13 +279,13 @@ inline EXTERN ADDR GlobalAddrAdjust__ (ADDR CACHE_TYPE); inline EXTERN ADDR GlobalAddrAdjust__ (ADDR ptr USES_REGS) { - if ((CELL *)ptr < GSplit) { + if ((CELL *)ptr < LOCAL_GSplit) { if ((CELL *)ptr < H0) - return (ADDR) (ptr + DelayDiff); + return (ADDR) (ptr + LOCAL_DelayDiff); else - return (ADDR) ((ptr + GDiff0)); + return (ADDR) ((ptr + LOCAL_GDiff0)); } else { - return (ADDR) ((ptr + GDiff)); + return (ADDR) ((ptr + LOCAL_GDiff)); } } @@ -297,10 +297,10 @@ inline EXTERN ADDR DelayAddrAdjust__ (ADDR CACHE_TYPE); inline EXTERN ADDR DelayAddrAdjust__ (ADDR ptr USES_REGS) { - if (!GSplit || (CELL *)ptr < GSplit) - return (ADDR) ((ptr + DelayDiff)); + if (!LOCAL_GSplit || (CELL *)ptr < LOCAL_GSplit) + return (ADDR) ((ptr + LOCAL_DelayDiff)); else - return (ADDR) ((ptr + GDiff0)); + return (ADDR) ((ptr + LOCAL_GDiff0)); } @@ -309,7 +309,7 @@ inline EXTERN ADDR BaseAddrAdjust__ (ADDR CACHE_TYPE); inline EXTERN ADDR BaseAddrAdjust__ (ADDR ptr USES_REGS) { - return (ADDR) ((ptr + BaseDiff)); + return (ADDR) ((ptr + LOCAL_BaseDiff)); } @@ -319,7 +319,7 @@ inline EXTERN CELL LocalAdjust__ (CELL CACHE_TYPE); inline EXTERN CELL LocalAdjust__ (CELL val USES_REGS) { - return (CELL) ((val + LDiff)); + return (CELL) ((val + LOCAL_LDiff)); } @@ -329,7 +329,7 @@ inline EXTERN ADDR LocalAddrAdjust__ (ADDR CACHE_TYPE); inline EXTERN ADDR LocalAddrAdjust__ (ADDR ptr USES_REGS) { - return (ADDR) ((ptr + LDiff)); + return (ADDR) ((ptr + LOCAL_LDiff)); } @@ -339,7 +339,7 @@ inline EXTERN CELL TrailAdjust__ (CELL CACHE_TYPE); inline EXTERN CELL TrailAdjust__ (CELL val USES_REGS) { - return (CELL) ((val + TrDiff)); + return (CELL) ((val + LOCAL_TrDiff)); } @@ -349,7 +349,7 @@ inline EXTERN ADDR TrailAddrAdjust__ (ADDR CACHE_TYPE); inline EXTERN ADDR TrailAddrAdjust__ (ADDR ptr USES_REGS) { - return (ADDR) ((ptr + TrDiff)); + return (ADDR) ((ptr + LOCAL_TrDiff)); } @@ -359,7 +359,7 @@ inline EXTERN TokEntry *TokEntryAdjust__ (TokEntry * CACHE_TYPE); inline EXTERN TokEntry * TokEntryAdjust__ (TokEntry * ptr USES_REGS) { - return (TokEntry *) (((CELL) ptr + TrDiff)); + return (TokEntry *) (((CELL) ptr + LOCAL_TrDiff)); } @@ -369,7 +369,7 @@ inline EXTERN VarEntry *VarEntryAdjust__ (VarEntry * CACHE_TYPE); inline EXTERN VarEntry * VarEntryAdjust__ (VarEntry * ptr USES_REGS) { - return (VarEntry *) (((CELL) ptr + TrDiff)); + return (VarEntry *) (((CELL) ptr + LOCAL_TrDiff)); } @@ -381,7 +381,7 @@ inline EXTERN Functor FuncAdjust__ (Functor f USES_REGS) { if (!IsExtensionFunctor(f)) - return (Functor) ((CharP (f) + HDiff)); + return (Functor) ((CharP (f) + LOCAL_HDiff)); return f; } @@ -392,7 +392,7 @@ CellPtoHeapAdjust__ (CELL * ptr USES_REGS) { if (!ptr) return ptr; - return (CELL *) (((CELL *) (CharP (ptr) + HDiff))); + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_HDiff))); } inline EXTERN HoldEntry *HoldEntryAdjust__ (HoldEntry * CACHE_TYPE); @@ -400,7 +400,7 @@ inline EXTERN HoldEntry *HoldEntryAdjust__ (HoldEntry * CACHE_TYPE); inline EXTERN HoldEntry * HoldEntryAdjust__ (HoldEntry * ptr USES_REGS) { - return (HoldEntry *) (((HoldEntry *) (CharP (ptr) + HDiff))); + return (HoldEntry *) (((HoldEntry *) (CharP (ptr) + LOCAL_HDiff))); } inline EXTERN struct record_list *DBRecordAdjust__ (struct record_list * CACHE_TYPE); @@ -410,7 +410,7 @@ DBRecordAdjust__ (struct record_list * ptr USES_REGS) { if (!ptr) return ptr; - return (struct record_list *) (CharP (ptr) + HDiff); + return (struct record_list *) (CharP (ptr) + LOCAL_HDiff); } @@ -449,7 +449,7 @@ inline EXTERN Atom AtomAdjust__ (Atom CACHE_TYPE); inline EXTERN Atom AtomAdjust__ (Atom at USES_REGS) { - return (Atom) ((at == NULL ? (at) : (Atom) (CharP (at) + HDiff))); + return (Atom) ((at == NULL ? (at) : (Atom) (CharP (at) + LOCAL_HDiff))); } inline EXTERN Atom NoAGCAtomAdjust__ (Atom CACHE_TYPE); @@ -457,7 +457,7 @@ inline EXTERN Atom NoAGCAtomAdjust__ (Atom CACHE_TYPE); inline EXTERN Atom NoAGCAtomAdjust__ (Atom at USES_REGS) { - return (Atom) ((at == NULL ? (at) : (Atom) (CharP (at) + HDiff))); + return (Atom) ((at == NULL ? (at) : (Atom) (CharP (at) + LOCAL_HDiff))); } @@ -467,7 +467,7 @@ inline EXTERN Prop PropAdjust__ (Prop CACHE_TYPE); inline EXTERN Prop PropAdjust__ (Prop p USES_REGS) { - return (Prop) ((p == NULL ? (p) : (Prop) (CharP (p) + HDiff))); + return (Prop) ((p == NULL ? (p) : (Prop) (CharP (p) + LOCAL_HDiff))); } @@ -478,7 +478,7 @@ inline EXTERN struct PL_blob_t *BlobTypeAdjust__ (struct PL_blob_t *CACHE_TYPE); inline EXTERN struct PL_blob_t * BlobTypeAdjust__ (struct PL_blob_t *at USES_REGS) { - return (struct PL_blob_t *) ((at == NULL ? (at) : (struct PL_blob_t *) (CharP (at) + HDiff))); + return (struct PL_blob_t *) ((at == NULL ? (at) : (struct PL_blob_t *) (CharP (at) + LOCAL_HDiff))); } inline EXTERN PredEntry *PredEntryAdjust__ (PredEntry * CACHE_TYPE); @@ -486,7 +486,7 @@ inline EXTERN PredEntry *PredEntryAdjust__ (PredEntry * CACHE_TYPE); inline EXTERN PredEntry * PredEntryAdjust__ (PredEntry *p USES_REGS) { - return (PredEntry *) ((p == NULL ? (p) : (PredEntry *) (CharP (p) + HDiff))); + return (PredEntry *) ((p == NULL ? (p) : (PredEntry *) (CharP (p) + LOCAL_HDiff))); } inline EXTERN struct mod_entry *ModEntryPtrAdjust__ (struct mod_entry * CACHE_TYPE); @@ -494,7 +494,7 @@ inline EXTERN struct mod_entry *ModEntryPtrAdjust__ (struct mod_entry * CACHE_TY inline EXTERN struct mod_entry * ModEntryPtrAdjust__ (struct mod_entry *p USES_REGS) { - return (struct mod_entry *) ((p == NULL ? (p) : (struct mod_entry *) (CharP (p) + HDiff))); + return (struct mod_entry *) ((p == NULL ? (p) : (struct mod_entry *) (CharP (p) + LOCAL_HDiff))); } inline EXTERN COUNT ConstantAdjust__ (COUNT CACHE_TYPE); @@ -536,7 +536,7 @@ AtomTermAdjust__ (Term at USES_REGS) { if (at == 0L) return at; - return (Term)(CharP(at) + HDiff); + return (Term)(CharP(at) + LOCAL_HDiff); } inline EXTERN Term ModuleAdjust__ (Term CACHE_TYPE); @@ -554,7 +554,7 @@ CodeVarAdjust__ (Term var USES_REGS) { if (var == 0L) return var; - return (Term)(CharP(var) + HDiff); + return (Term)(CharP(var) + LOCAL_HDiff); } @@ -565,7 +565,7 @@ inline EXTERN Term BlobTermInCodeAdjust__ (Term CACHE_TYPE); inline EXTERN Term BlobTermInCodeAdjust__ (Term t USES_REGS) { - return (Term) (CharP(t) - HDiff); + return (Term) (CharP(t) - LOCAL_HDiff); } @@ -574,7 +574,7 @@ inline EXTERN Term CodeComposedTermAdjust__ (Term CACHE_TYPE); inline EXTERN Term CodeComposedTermAdjust__ (Term t USES_REGS) { - return (Term) (CharP(t) - HDiff); + return (Term) (CharP(t) - LOCAL_HDiff); } @@ -585,7 +585,7 @@ inline EXTERN Term BlobTermInCodeAdjust__ (Term CACHE_TYPE); inline EXTERN Term BlobTermInCodeAdjust__ (Term t USES_REGS) { - return (Term) (CharP(t) + HDiff); + return (Term) (CharP(t) + LOCAL_HDiff); } inline EXTERN Term CodeComposedTermAdjust__ (Term CACHE_TYPE); @@ -593,7 +593,7 @@ inline EXTERN Term CodeComposedTermAdjust__ (Term CACHE_TYPE); inline EXTERN Term CodeComposedTermAdjust__ (Term t USES_REGS) { - return (Term) (CharP(t) + HDiff); + return (Term) (CharP(t) + LOCAL_HDiff); } @@ -604,7 +604,7 @@ inline EXTERN AtomEntry *AtomEntryAdjust__ (AtomEntry * CACHE_TYPE); inline EXTERN AtomEntry * AtomEntryAdjust__ (AtomEntry * at USES_REGS) { - return (AtomEntry *) ((AtomEntry *) (CharP (at) + HDiff)); + return (AtomEntry *) ((AtomEntry *) (CharP (at) + LOCAL_HDiff)); } inline EXTERN struct mfile *MFileAdjust__ (struct mfile * CACHE_TYPE); @@ -612,7 +612,7 @@ inline EXTERN struct mfile *MFileAdjust__ (struct mfile * CACHE_TYPE); inline EXTERN struct mfile * MFileAdjust__ (struct mfile * at USES_REGS) { - return (struct mfile *) (CharP (at) + HDiff); + return (struct mfile *) (CharP (at) + LOCAL_HDiff); } inline EXTERN GlobalEntry *GlobalEntryAdjust__ (GlobalEntry * CACHE_TYPE); @@ -620,7 +620,7 @@ inline EXTERN GlobalEntry *GlobalEntryAdjust__ (GlobalEntry * CACHE_TYPE); inline EXTERN GlobalEntry * GlobalEntryAdjust__ (GlobalEntry * at USES_REGS) { - return (GlobalEntry *) ((GlobalEntry *) (CharP (at) + HDiff)); + return (GlobalEntry *) ((GlobalEntry *) (CharP (at) + LOCAL_HDiff)); } @@ -630,7 +630,7 @@ inline EXTERN union CONSULT_OBJ *ConsultObjAdjust__ (union CONSULT_OBJ * CACHE_T inline EXTERN union CONSULT_OBJ * ConsultObjAdjust__ (union CONSULT_OBJ *co USES_REGS) { - return (union CONSULT_OBJ *) ((union CONSULT_OBJ *) (CharP (co) + HDiff)); + return (union CONSULT_OBJ *) ((union CONSULT_OBJ *) (CharP (co) + LOCAL_HDiff)); } @@ -640,7 +640,7 @@ inline EXTERN DBRef DBRefAdjust__ (DBRef CACHE_TYPE); inline EXTERN DBRef DBRefAdjust__ (DBRef dbr USES_REGS) { - return (DBRef) ((DBRef) (CharP (dbr) + HDiff)); + return (DBRef) ((DBRef) (CharP (dbr) + LOCAL_HDiff)); } @@ -650,7 +650,7 @@ inline EXTERN DBRef *DBRefPAdjust__ (DBRef * CACHE_TYPE); inline EXTERN DBRef * DBRefPAdjust__ (DBRef * dbrp USES_REGS) { - return (DBRef *) ((DBRef *) (CharP (dbrp) + HDiff)); + return (DBRef *) ((DBRef *) (CharP (dbrp) + LOCAL_HDiff)); } @@ -660,7 +660,7 @@ inline EXTERN DBTerm *DBTermAdjust__ (DBTerm * CACHE_TYPE); inline EXTERN DBTerm * DBTermAdjust__ (DBTerm * dbtp USES_REGS) { - return (DBTerm *) ((DBTerm *) (CharP (dbtp) + HDiff)); + return (DBTerm *) ((DBTerm *) (CharP (dbtp) + LOCAL_HDiff)); } @@ -671,7 +671,7 @@ inline EXTERN struct static_index * SIndexAdjust__ (struct static_index *si USES_REGS) { return (struct static_index - *) ((struct static_index *) (CharP (si) + HDiff)); + *) ((struct static_index *) (CharP (si) + LOCAL_HDiff)); } @@ -683,7 +683,7 @@ inline EXTERN struct logic_upd_index * LUIndexAdjust__ (struct logic_upd_index *lui USES_REGS) { return (struct logic_upd_index - *) ((struct logic_upd_index *) (CharP (lui) + HDiff)); + *) ((struct logic_upd_index *) (CharP (lui) + LOCAL_HDiff)); } @@ -693,7 +693,7 @@ inline EXTERN Term CodeAdjust__ (Term CACHE_TYPE); inline EXTERN Term CodeAdjust__ (Term dbr USES_REGS) { - return (Term) (CharP(dbr) + HDiff); + return (Term) (CharP(dbr) + LOCAL_HDiff); } @@ -703,7 +703,7 @@ inline EXTERN ADDR AddrAdjust__ (ADDR CACHE_TYPE); inline EXTERN ADDR AddrAdjust__ (ADDR addr USES_REGS) { - return (ADDR) ((ADDR) (CharP (addr) + HDiff)); + return (ADDR) ((ADDR) (CharP (addr) + LOCAL_HDiff)); } @@ -713,7 +713,7 @@ inline EXTERN CODEADDR CodeAddrAdjust__ (CODEADDR CACHE_TYPE); inline EXTERN CODEADDR CodeAddrAdjust__ (CODEADDR addr USES_REGS) { - return (CODEADDR) ((CODEADDR) (CharP (addr) + HDiff)); + return (CODEADDR) ((CODEADDR) (CharP (addr) + LOCAL_HDiff)); } @@ -724,7 +724,7 @@ CodeCharPAdjust__ (char * addr USES_REGS) { if (!addr) return NULL; - return addr + HDiff; + return addr + LOCAL_HDiff; } inline EXTERN void * CodeVoidPAdjust__ (void * CACHE_TYPE); @@ -734,7 +734,7 @@ CodeVoidPAdjust__ (void * addr USES_REGS) { if (!addr) return NULL; - return addr + HDiff; + return addr + LOCAL_HDiff; } inline EXTERN struct halt_hook *HaltHookAdjust__ (struct halt_hook * CACHE_TYPE); @@ -744,7 +744,7 @@ HaltHookAdjust__ (struct halt_hook * addr USES_REGS) { if (!addr) return NULL; - return (struct halt_hook *) (CharP (addr) + HDiff); + return (struct halt_hook *) (CharP (addr) + LOCAL_HDiff); } inline EXTERN BlockHeader *BlockAdjust__ (BlockHeader * CACHE_TYPE); @@ -752,7 +752,7 @@ inline EXTERN BlockHeader *BlockAdjust__ (BlockHeader * CACHE_TYPE); inline EXTERN BlockHeader * BlockAdjust__ (BlockHeader * addr USES_REGS) { - return (BlockHeader *) ((BlockHeader *) (CharP (addr) + HDiff)); + return (BlockHeader *) ((BlockHeader *) (CharP (addr) + LOCAL_HDiff)); } inline EXTERN yamop *PtoOpAdjust__ (yamop * CACHE_TYPE); @@ -761,7 +761,7 @@ inline EXTERN yamop * PtoOpAdjust__ (yamop * ptr USES_REGS) { if (ptr) - return (yamop *) (CharP (ptr) + HDiff); + return (yamop *) (CharP (ptr) + LOCAL_HDiff); return ptr; } @@ -772,7 +772,7 @@ OpListAdjust__ (struct operator_entry * ptr USES_REGS) { if (!ptr) return ptr; - return (struct operator_entry *) (CharP (ptr) + HDiff); + return (struct operator_entry *) (CharP (ptr) + LOCAL_HDiff); } @@ -781,7 +781,7 @@ inline EXTERN struct logic_upd_clause *PtoLUClauseAdjust__ (struct logic_upd_cla inline EXTERN struct logic_upd_clause * PtoLUClauseAdjust__ (struct logic_upd_clause * ptr USES_REGS) { - return (struct logic_upd_clause *) (CharP (ptr) + HDiff); + return (struct logic_upd_clause *) (CharP (ptr) + LOCAL_HDiff); } inline EXTERN struct logic_upd_index *PtoLUIndexAdjust__ (struct logic_upd_index * CACHE_TYPE); @@ -789,7 +789,7 @@ inline EXTERN struct logic_upd_index *PtoLUIndexAdjust__ (struct logic_upd_index inline EXTERN struct logic_upd_index * PtoLUIndexAdjust__ (struct logic_upd_index * ptr USES_REGS) { - return (struct logic_upd_index *) (CharP (ptr) + HDiff); + return (struct logic_upd_index *) (CharP (ptr) + LOCAL_HDiff); } @@ -799,7 +799,7 @@ inline EXTERN CELL *PtoHeapCellAdjust__ (CELL * CACHE_TYPE); inline EXTERN CELL * PtoHeapCellAdjust__ (CELL * ptr USES_REGS) { - return (CELL *) (((CELL *) (CharP (ptr) + HDiff))); + return (CELL *) (((CELL *) (CharP (ptr) + LOCAL_HDiff))); } inline EXTERN AtomHashEntry *PtoAtomHashEntryAdjust__ (AtomHashEntry * CACHE_TYPE); @@ -807,7 +807,7 @@ inline EXTERN AtomHashEntry *PtoAtomHashEntryAdjust__ (AtomHashEntry * CACHE_TYP inline EXTERN AtomHashEntry * PtoAtomHashEntryAdjust__ (AtomHashEntry * ptr USES_REGS) { - return (AtomHashEntry *) (((AtomHashEntry *) (CharP (ptr) + HDiff))); + return (AtomHashEntry *) (((AtomHashEntry *) (CharP (ptr) + LOCAL_HDiff))); } inline EXTERN Term TermToGlobalAdjust__ (Term CACHE_TYPE); @@ -841,7 +841,7 @@ inline EXTERN opentry *OpRTableAdjust__ (opentry * CACHE_TYPE); inline EXTERN opentry * OpRTableAdjust__ (opentry * ptr USES_REGS) { - return (opentry *) (((opentry *) (CharP (ptr) + HDiff))); + return (opentry *) (((opentry *) (CharP (ptr) + LOCAL_HDiff))); } inline EXTERN OpEntry *OpEntryAdjust__ (OpEntry * CACHE_TYPE); @@ -849,7 +849,7 @@ inline EXTERN OpEntry *OpEntryAdjust__ (OpEntry * CACHE_TYPE); inline EXTERN OpEntry * OpEntryAdjust__ (OpEntry * ptr USES_REGS) { - return (OpEntry *) (((OpEntry *) (CharP (ptr) + HDiff))); + return (OpEntry *) (((OpEntry *) (CharP (ptr) + LOCAL_HDiff))); } inline EXTERN PredEntry *PtoPredAdjust__ (PredEntry * CACHE_TYPE); @@ -857,7 +857,7 @@ inline EXTERN PredEntry *PtoPredAdjust__ (PredEntry * CACHE_TYPE); inline EXTERN PredEntry * PtoPredAdjust__ (PredEntry * ptr USES_REGS) { - return (PredEntry *) (((PredEntry *) (CharP (ptr) + HDiff))); + return (PredEntry *) (((PredEntry *) (CharP (ptr) + LOCAL_HDiff))); } inline EXTERN PredEntry **PtoPtoPredAdjust__ (PredEntry ** CACHE_TYPE); @@ -867,7 +867,7 @@ PtoPtoPredAdjust__ (PredEntry **ptr USES_REGS) { if (!ptr) return NULL; - return (PredEntry **) (((PredEntry **) (CharP (ptr) + HDiff))); + return (PredEntry **) (((PredEntry **) (CharP (ptr) + LOCAL_HDiff))); } @@ -879,7 +879,7 @@ PtoArrayEAdjust__ (ArrayEntry * ptr USES_REGS) { if (!ptr) return NULL; - return (ArrayEntry *) (((ArrayEntry *) (CharP (ptr) + HDiff))); + return (ArrayEntry *) (((ArrayEntry *) (CharP (ptr) + LOCAL_HDiff))); } @@ -890,7 +890,7 @@ PtoGlobalEAdjust__ (GlobalEntry * ptr USES_REGS) { if (!ptr) return NULL; - return (GlobalEntry *) (((GlobalEntry *) (CharP (ptr) + HDiff))); + return (GlobalEntry *) (((GlobalEntry *) (CharP (ptr) + LOCAL_HDiff))); } @@ -901,7 +901,7 @@ PtoArraySAdjust__ (StaticArrayEntry * ptr USES_REGS) { if (!ptr) return NULL; - return (StaticArrayEntry *) (((StaticArrayEntry *) (CharP (ptr) + HDiff))); + return (StaticArrayEntry *) (((StaticArrayEntry *) (CharP (ptr) + LOCAL_HDiff))); } @@ -912,7 +912,7 @@ inline EXTERN struct logic_upd_clause * PtoLUCAdjust__ (struct logic_upd_clause *ptr USES_REGS) { return (struct logic_upd_clause - *) (((struct logic_upd_clause *) (CharP (ptr) + HDiff))); + *) (((struct logic_upd_clause *) (CharP (ptr) + LOCAL_HDiff))); } @@ -923,7 +923,7 @@ inline EXTERN struct static_clause * PtoStCAdjust__ (struct static_clause *ptr USES_REGS) { return (struct static_clause - *) (((struct static_upd_clause *) (CharP (ptr) + HDiff))); + *) (((struct static_upd_clause *) (CharP (ptr) + LOCAL_HDiff))); } @@ -932,7 +932,7 @@ inline EXTERN struct dbterm_list *PtoDBTLAdjust__ (struct dbterm_list * CACHE_TY inline EXTERN struct dbterm_list * PtoDBTLAdjust__ (struct dbterm_list * addr USES_REGS) { - return (struct dbterm_list *) ((ADDR) (CharP (addr) + HDiff)); + return (struct dbterm_list *) ((ADDR) (CharP (addr) + LOCAL_HDiff)); } @@ -943,7 +943,7 @@ inline EXTERN wamreg XAdjust__ (wamreg CACHE_TYPE); inline EXTERN wamreg XAdjust__ (wamreg reg USES_REGS) { - return (wamreg) ((wamreg) ((reg) + XDiff)); + return (wamreg) ((wamreg) ((reg) + LOCAL_XDiff)); } @@ -975,7 +975,7 @@ inline EXTERN int IsOldLocal__ (CELL CACHE_TYPE); inline EXTERN int IsOldLocal__ (CELL reg USES_REGS) { - return (int) (IN_BETWEEN (OldASP, reg, OldLCL0)); + return (int) (IN_BETWEEN (LOCAL_OldASP, reg, LOCAL_OldLCL0)); } @@ -985,7 +985,7 @@ inline EXTERN int IsOldLocalPtr__ (CELL * CACHE_TYPE); inline EXTERN int IsOldLocalPtr__ (CELL * ptr USES_REGS) { - return (int) (IN_BETWEEN (OldASP, ptr, OldLCL0)); + return (int) (IN_BETWEEN (LOCAL_OldASP, ptr, LOCAL_OldLCL0)); } @@ -997,7 +997,7 @@ inline EXTERN int IsOldLocalInTR__ (CELL CACHE_TYPE); inline EXTERN int IsOldLocalInTR__ (CELL reg USES_REGS) { - return (int) (IN_BETWEEN (OldH, reg, OldLCL0)); + return (int) (IN_BETWEEN (LOCAL_OldH, reg, LOCAL_OldLCL0)); } @@ -1007,7 +1007,7 @@ inline EXTERN int IsOldLocalInTRPtr__ (CELL * CACHE_TYPE); inline EXTERN int IsOldLocalInTRPtr__ (CELL * ptr USES_REGS) { - return (int) (IN_BETWEEN (OldH, ptr, OldLCL0)); + return (int) (IN_BETWEEN (LOCAL_OldH, ptr, LOCAL_OldLCL0)); } @@ -1018,7 +1018,7 @@ inline EXTERN int IsOldH__ (CELL CACHE_TYPE); inline EXTERN int IsOldH__ (CELL reg USES_REGS) { - return (int) ((CharP (reg) == CharP (OldH))); + return (int) ((CharP (reg) == CharP (LOCAL_OldH))); } @@ -1030,7 +1030,7 @@ inline EXTERN int IsOldGlobal__ (CELL CACHE_TYPE); inline EXTERN int IsOldGlobal__ (CELL reg USES_REGS) { - return (int) (IN_BETWEEN (OldGlobalBase, reg, OldH)); + return (int) (IN_BETWEEN (LOCAL_OldGlobalBase, reg, LOCAL_OldH)); } @@ -1039,7 +1039,7 @@ inline EXTERN int IsOldDelay__ (CELL CACHE_TYPE); inline EXTERN int IsOldDelay__ (CELL reg USES_REGS) { - return (int) (IN_BETWEEN (OldGlobalBase, reg, OldH0)); + return (int) (IN_BETWEEN (LOCAL_OldGlobalBase, reg, LOCAL_OldH0)); } @@ -1049,7 +1049,7 @@ inline EXTERN int IsOldGlobalPtr__ (CELL * CACHE_TYPE); inline EXTERN int IsOldGlobalPtr__ (CELL * ptr USES_REGS) { - return (int) (IN_BETWEEN (OldGlobalBase, ptr, OldH)); + return (int) (IN_BETWEEN (LOCAL_OldGlobalBase, ptr, LOCAL_OldH)); } @@ -1059,7 +1059,7 @@ inline EXTERN int IsOldTrail__ (CELL CACHE_TYPE); inline EXTERN int IsOldTrail__ (CELL reg USES_REGS) { - return (int) (IN_BETWEEN (OldTrailBase, reg, OldTR)); + return (int) (IN_BETWEEN (LOCAL_OldTrailBase, reg, LOCAL_OldTR)); } @@ -1069,7 +1069,7 @@ inline EXTERN int IsOldTrailPtr__ (CELL * CACHE_TYPE); inline EXTERN int IsOldTrailPtr__ (CELL * ptr USES_REGS) { - return (int) (IN_BETWEEN (OldTrailBase, ptr, OldTR)); + return (int) (IN_BETWEEN (LOCAL_OldTrailBase, ptr, LOCAL_OldTR)); } @@ -1079,7 +1079,7 @@ inline EXTERN int IsOldVarTableTrailPtr__ (struct VARSTRUCT * CACHE_TYPE); inline EXTERN int IsOldVarTableTrailPtr__ (struct VARSTRUCT *ptr USES_REGS) { - return (int) (IN_BETWEEN (OldTrailBase, ptr, OldTR)); + return (int) (IN_BETWEEN (LOCAL_OldTrailBase, ptr, LOCAL_OldTR)); } @@ -1089,7 +1089,7 @@ inline EXTERN int IsOldTokenTrailPtr__ (struct TOKEN * CACHE_TYPE); inline EXTERN int IsOldTokenTrailPtr__ (struct TOKEN *ptr USES_REGS) { - return (int) (IN_BETWEEN (OldTrailBase, ptr, OldTR)); + return (int) (IN_BETWEEN (LOCAL_OldTrailBase, ptr, LOCAL_OldTR)); } @@ -1100,9 +1100,9 @@ inline EXTERN int IsOldCode__ (CELL reg USES_REGS) { #if USE_SYSTEM_MALLOC - return reg < (CELL)OldGlobalBase || reg > (CELL)OldTrailTop; + return reg < (CELL)LOCAL_OldGlobalBase || reg > (CELL)LOCAL_OldTrailTop; #else - return (int) (IN_BETWEEN (OldHeapBase, reg, OldHeapTop)); + return (int) (IN_BETWEEN (LOCAL_OldHeapBase, reg, LOCAL_OldHeapTop)); #endif } @@ -1113,7 +1113,7 @@ inline EXTERN int IsOldCodeCellPtr__ (CELL * CACHE_TYPE); inline EXTERN int IsOldCodeCellPtr__ (CELL * ptr USES_REGS) { - return (int) (IN_BETWEEN (OldHeapBase, ptr, OldHeapTop)); + return (int) (IN_BETWEEN (LOCAL_OldHeapBase, ptr, LOCAL_OldHeapTop)); } @@ -1123,7 +1123,7 @@ inline EXTERN int IsGlobal__ (CELL CACHE_TYPE); inline EXTERN int IsGlobal__ (CELL reg USES_REGS) { - return (int) (IN_BETWEEN (Yap_GlobalBase, reg, H)); + return (int) (IN_BETWEEN (LOCAL_GlobalBase, reg, H)); } diff --git a/H/trim_trail.h b/H/trim_trail.h index 81233c769..872e6d74c 100644 --- a/H/trim_trail.h +++ b/H/trim_trail.h @@ -17,13 +17,13 @@ } else if (IsPairTerm(d1)) { CELL *pt = RepPair(d1); #ifdef LIMIT_TABLING - if ((ADDR) pt == Yap_TrailBase) { + if ((ADDR) pt == LOCAL_TrailBase) { sg_fr_ptr sg_fr = (sg_fr_ptr) TrailVal(pt1); SgFr_state(sg_fr)--; /* complete_in_use --> complete : compiled_in_use --> compiled */ insert_into_global_sg_fr_list(sg_fr); } else #endif /* LIMIT_TABLING */ - if (IN_BETWEEN(Yap_TrailBase, pt, Yap_TrailTop)) { + if (IN_BETWEEN(LOCAL_TrailBase, pt, LOCAL_TrailTop)) { /* skip, this is a problem because we lose information, namely active references */ pt1 = (tr_fr_ptr)pt; diff --git a/H/yapio.h b/H/yapio.h index 70fb9a5c0..7f891a96c 100644 --- a/H/yapio.h +++ b/H/yapio.h @@ -65,9 +65,6 @@ #endif #define YP_FILE FILE -extern YP_FILE *Yap_stdin; -extern YP_FILE *Yap_stdout; -extern YP_FILE *Yap_stderr; int STD_PROTO(YP_putc,(int, int)); @@ -167,6 +164,7 @@ extern YP_FILE yp_iob[YP_MAX_FILES]; typedef YP_FILE *YP_File; +/* ricardo typedef enum TokenKinds { Name_tok, Number_tok, @@ -195,6 +193,7 @@ typedef struct VARSTRUCT { struct VARSTRUCT *VarLeft, *VarRight; char VarRep[1]; } VarEntry; +*/ /* Character types for tokenizer and write.c */ @@ -265,7 +264,7 @@ chtype(Int ch) /* parser stack, used to be AuxSp, now is ASP */ -#define ParserAuxSp ScannerStack +#define ParserAuxSp LOCAL_ScannerStack /* routines in parser.c */ VarEntry STD_PROTO(*Yap_LookupVar,(char *)); @@ -325,8 +324,7 @@ Atom STD_PROTO(Yap_LookupWideAtom,(wchar_t *)); #define Unfold_cyclics_f 0x20 #define Use_SWI_Stream_f 0x40 -/* write.c */ -void STD_PROTO(Yap_plwrite,(Term,int (*)(int, wchar_t), int, int)); + /* grow.c */ int STD_PROTO(Yap_growheap_in_parser, (tr_fr_ptr *, TokEntry **, VarEntry **)); @@ -386,32 +384,4 @@ WideHashFunction(wchar_t *CHP) #define CONTINUE_ON_PARSER_ERROR 2 #define EXCEPTION_ON_PARSER_ERROR 3 -#ifdef THREADS -#define Yap_IOBotch Yap_thread_gl[worker_id].io_botch -#define Yap_tokptr Yap_thread_gl[worker_id].tokptr -#define Yap_toktide Yap_thread_gl[worker_id].toktide -#define Yap_VarTable Yap_thread_gl[worker_id].var_table -#define Yap_AnonVarTable Yap_thread_gl[worker_id].anon_var_table -#define Yap_eot_before_eof Yap_thread_gl[worker_id].eot_before_eof -#define Yap_FileNameBuf Yap_thread_gl[worker_id].file_name_buf -#define Yap_FileNameBuf2 Yap_thread_gl[worker_id].file_name_buf2 -#else -extern jmp_buf Yap_IOBotch; - -/*************** variables concerned with parsing *********************/ -extern TokEntry *Yap_tokptr, *Yap_toktide; -extern VarEntry *Yap_VarTable, *Yap_AnonVarTable; -extern int Yap_eot_before_eof; - -extern char Yap_FileNameBuf[YAP_FILENAME_MAX], Yap_FileNameBuf2[YAP_FILENAME_MAX]; - -#endif - -#ifdef DEBUG -extern YP_FILE *Yap_logfile; -#endif - -#if USE_SOCKET -extern int Yap_sockets_io; -#endif diff --git a/MYDDAS/myddas_mysql.c b/MYDDAS/myddas_mysql.c index 68ad84e09..dc09b0911 100755 --- a/MYDDAS/myddas_mysql.c +++ b/MYDDAS/myddas_mysql.c @@ -45,18 +45,18 @@ static Int null_id = 0; -STATIC_PROTO(Int c_db_my_connect,(void)); -STATIC_PROTO(Int c_db_my_disconnect,(void)); -STATIC_PROTO(Int c_db_my_number_of_fields,(void)); -STATIC_PROTO(Int c_db_my_get_attributes_types,(void)); -STATIC_PROTO(Int c_db_my_query,(void)); -STATIC_PROTO(Int c_db_my_table_write,(void)); -STATIC_PROTO(Int c_db_my_row,(void)); -STATIC_PROTO(Int c_db_my_row_cut,(void)); -STATIC_PROTO(Int c_db_my_get_fields_properties,(void)); -STATIC_PROTO(Int c_db_my_get_next_result_set,(void)); -STATIC_PROTO(Int c_db_my_get_database,(void)); -STATIC_PROTO(Int c_db_my_change_database,(void)); +STATIC_PROTO(Int c_db_my_connect,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_disconnect,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_number_of_fields,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_get_attributes_types,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_query,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_table_write,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_row,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_row_cut,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_get_fields_properties,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_get_next_result_set,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_get_database,( USES_REGS1 )); +STATIC_PROTO(Int c_db_my_change_database,( USES_REGS1 )); void Yap_InitMYDDAS_MySQLPreds(void) { @@ -104,7 +104,7 @@ void Yap_InitBackMYDDAS_MySQLPreds(void) } static Int -c_db_my_connect(void) { +c_db_my_connect( USES_REGS1 ) { Term arg_host = Deref(ARG1); Term arg_user = Deref(ARG2); Term arg_passwd = Deref(ARG3); @@ -163,7 +163,7 @@ c_db_my_connect(void) { /* db_query: SQLQuery x ResultSet x Connection */ static Int -c_db_my_query(void) { +c_db_my_query( USES_REGS1 ) { Term arg_sql_query = Deref(ARG1); Term arg_result_set = Deref(ARG2); Term arg_conn = Deref(ARG3); @@ -337,7 +337,7 @@ c_db_my_query(void) { } static Int -c_db_my_number_of_fields(void) { +c_db_my_number_of_fields( USES_REGS1 ) { Term arg_relation = Deref(ARG1); Term arg_conn = Deref(ARG2); Term arg_fields = Deref(ARG3); @@ -381,7 +381,7 @@ c_db_my_number_of_fields(void) { /* db_get_attributes_types: RelName x Connection -> TypesList */ static Int -c_db_my_get_attributes_types(void) { +c_db_my_get_attributes_types( USES_REGS1 ) { Term arg_relation = Deref(ARG1); Term arg_conn = Deref(ARG2); Term arg_types_list = Deref(ARG3); @@ -442,7 +442,7 @@ c_db_my_get_attributes_types(void) { /* db_disconnect */ static Int -c_db_my_disconnect(void) { +c_db_my_disconnect( USES_REGS1 ) { Term arg_conn = Deref(ARG1); MYSQL *conn = (MYSQL *) IntegerOfTerm(arg_conn); @@ -461,7 +461,7 @@ c_db_my_disconnect(void) { /* db_table_write: Result Set */ static Int -c_db_my_table_write(void) { +c_db_my_table_write( USES_REGS1 ) { Term arg_res_set = Deref(ARG1); MYSQL_RES *res_set = (MYSQL_RES *) IntegerOfTerm(arg_res_set); @@ -473,7 +473,7 @@ c_db_my_table_write(void) { } static Int -c_db_my_row_cut(void) { +c_db_my_row_cut( USES_REGS1 ) { MYSQL_RES *mysql_res=NULL; mysql_res = (MYSQL_RES *) IntegerOfTerm(EXTRA_CBACK_CUT_ARG(Term,1)); @@ -483,7 +483,7 @@ c_db_my_row_cut(void) { /* db_row: ResultSet x Arity_ListOfArgs x ListOfArgs -> */ static Int -c_db_my_row(void) { +c_db_my_row( USES_REGS1 ) { #ifdef MYDDAS_STATS /* Measure time used by the */ /* c_db_my_row function */ @@ -598,7 +598,7 @@ c_db_my_row(void) { } static Int -c_db_my_get_fields_properties(void) { +c_db_my_get_fields_properties( USES_REGS1 ) { Term nome_relacao = Deref(ARG1); Term arg_conn = Deref(ARG2); Term fields_properties_list = Deref(ARG3); @@ -680,7 +680,7 @@ c_db_my_get_fields_properties(void) { /* c_db_my_get_next_result_set: Connection * NextResSet */ static Int -c_db_my_get_next_result_set(void) { +c_db_my_get_next_result_set( USES_REGS1 ) { Term arg_conn = Deref(ARG1); Term arg_next_res_set = Deref(ARG2); @@ -695,7 +695,7 @@ c_db_my_get_next_result_set(void) { } static Int -c_db_my_get_database(void) { +c_db_my_get_database( USES_REGS1 ) { Term arg_con = Deref(ARG1); Term arg_database = Deref(ARG2); @@ -709,7 +709,7 @@ c_db_my_get_database(void) { } static Int -c_db_my_change_database(void) { +c_db_my_change_database( USES_REGS1 ) { Term arg_con = Deref(ARG1); Term arg_database = Deref(ARG2); diff --git a/MYDDAS/myddas_wkb2prolog.c b/MYDDAS/myddas_wkb2prolog.c index f18bf8015..ff147fb9b 100644 --- a/MYDDAS/myddas_wkb2prolog.c +++ b/MYDDAS/myddas_wkb2prolog.c @@ -173,6 +173,8 @@ static Term get_point(char *func){ } static Term get_linestring(char *func){ + CACHE_REGS + Term *c_list; Term list; Functor functor; @@ -203,6 +205,8 @@ static Term get_linestring(char *func){ } static Term get_polygon(char *func){ + CACHE_REGS + uint32 r; int i; Functor functor; @@ -233,6 +237,8 @@ static Term get_polygon(char *func){ } static Term get_geometry(uint32 type){ + CACHE_REGS + switch(type) { case WKBPOINT: return get_point("point"); diff --git a/Makefile.in b/Makefile.in index 7004a0e57..c7605f31e 100755 --- a/Makefile.in +++ b/Makefile.in @@ -260,7 +260,7 @@ C_SOURCES= \ $(srcdir)/BEAM/eam_am.c $(srcdir)/BEAM/eam_showcode.c \ $(srcdir)/BEAM/eamindex.c $(srcdir)/BEAM/eamamasm.c \ $(srcdir)/BEAM/eam_gc.c $(srcdir)/BEAM/eam_split.c \ - $(srcdir)/OPTYap/opt.memory.c $(srcdir)/OPTYap/opt.init.c \ + $(srcdir)/OPTYap/or.memory.c $(srcdir)/OPTYap/opt.init.c \ $(srcdir)/OPTYap/opt.preds.c $(srcdir)/OPTYap/or.copy_engine.c \ $(srcdir)/OPTYap/or.cow_engine.c $(srcdir)/OPTYap/or.sba_engine.c \ $(srcdir)/OPTYap/or.thread_engine.c \ @@ -378,7 +378,7 @@ C_INTERFACE_OBJECTS = \ c_interface.o clause_list.o OR_OBJECTS = \ - opt.memory.o opt.init.o opt.preds.o \ + or.memory.o opt.init.o opt.preds.o \ or.copy_engine.o or.cow_engine.o or.sba_engine.o or.thread_engine.o \ or.scheduler.o or.cut.o \ tab.tries.o tab.completion.o @@ -489,8 +489,8 @@ myddas_wkb2prolog.o: $(srcdir)/MYDDAS/myddas_wkb2prolog.c config.h myddas_statistics.o: $(srcdir)/MYDDAS/myddas_statistics.c config.h $(CC) -c $(CFLAGS) $(srcdir)/MYDDAS/myddas_statistics.c -o $@ -opt.memory.o: $(srcdir)/OPTYap/opt.memory.c config.h - $(CC) -c $(CFLAGS) $(srcdir)/OPTYap/opt.memory.c -o $@ +or.memory.o: $(srcdir)/OPTYap/or.memory.c config.h + $(CC) -c $(CFLAGS) $(srcdir)/OPTYap/or.memory.c -o $@ opt.init.o: $(srcdir)/OPTYap/opt.init.c config.h $(CC) -c $(CFLAGS) $(srcdir)/OPTYap/opt.init.c -o $@ diff --git a/OPTYap/opt.config.h b/OPTYap/opt.config.h index e754769df..fc5ef710d 100644 --- a/OPTYap/opt.config.h +++ b/OPTYap/opt.config.h @@ -17,9 +17,9 @@ ** General Configuration Parameters ** ************************************************************************/ -/**************************************************************** -** use shared pages memory alloc scheme ? (optional) ** -****************************************************************/ +/****************************************************************************************** +** use shared pages memory alloc scheme for OPTYap data structures? (optional) ** +******************************************************************************************/ /* #define USE_PAGES_MALLOC 1 */ @@ -92,7 +92,7 @@ ** memory mapping scheme (mandatory, define one) ** ************************************************************/ #define MMAP_MEMORY_MAPPING_SCHEME 1 -/* #define SHM_MEMORY_MAPPING_SCHEME 1 */ +/* #define SHM_MEMORY_MAPPING_SCHEME 1 */ /************************************************* ** enable error checking ? (optional) ** diff --git a/OPTYap/opt.init.c b/OPTYap/opt.init.c index 547e42434..7ea4ef886 100644 --- a/OPTYap/opt.init.c +++ b/OPTYap/opt.init.c @@ -59,99 +59,100 @@ ** Global functions ** *******************************/ -void Yap_init_optyap_data(int max_table_size, int n_workers, int sch_loop, int delay_load) { +void Yap_init_global_optyap_data(int max_table_size, int n_workers, int sch_loop, int delay_load) { int i; /* global data related to memory management */ #ifdef LIMIT_TABLING if (max_table_size) - Yap_max_pages = ((max_table_size - 1) * 1024 * 1024 / SHMMAX + 1) * SHMMAX / Yap_page_size; + GLOBAL_max_pages = ((max_table_size - 1) * 1024 * 1024 / SHMMAX + 1) * SHMMAX / Yap_page_size; else - Yap_max_pages = -1; + GLOBAL_max_pages = -1; #endif /* LIMIT_TABLING */ - INIT_PAGES(Yap_pages_void, void *); + INIT_PAGES(GLOBAL_pages_void, void *); #ifdef YAPOR - INIT_PAGES(Yap_pages_or_fr , struct or_frame); - INIT_PAGES(Yap_pages_qg_sol_fr , struct query_goal_solution_frame); - INIT_PAGES(Yap_pages_qg_ans_fr, struct query_goal_answer_frame); + INIT_PAGES(GLOBAL_pages_or_fr, struct or_frame); + INIT_PAGES(GLOBAL_pages_qg_sol_fr, struct query_goal_solution_frame); + INIT_PAGES(GLOBAL_pages_qg_ans_fr, struct query_goal_answer_frame); #endif /* YAPOR */ #ifdef TABLING_INNER_CUTS - INIT_PAGES(Yap_pages_tg_sol_fr, struct table_subgoal_solution_frame); - INIT_PAGES(Yap_pages_tg_ans_fr, struct table_subgoal_answer_frame); + INIT_PAGES(GLOBAL_pages_tg_sol_fr, struct table_subgoal_solution_frame); + INIT_PAGES(GLOBAL_pages_tg_ans_fr, struct table_subgoal_answer_frame); #endif /* TABLING_INNER_CUTS */ #ifdef TABLING - INIT_PAGES(Yap_pages_tab_ent, struct table_entry); - INIT_PAGES(Yap_pages_sg_fr, struct subgoal_frame); - INIT_PAGES(Yap_pages_dep_fr, struct dependency_frame); - INIT_PAGES(Yap_pages_sg_node, struct subgoal_trie_node); - INIT_PAGES(Yap_pages_ans_node, struct answer_trie_node); - INIT_PAGES(Yap_pages_gt_node, struct global_trie_node); - INIT_PAGES(Yap_pages_sg_hash, struct subgoal_trie_hash); - INIT_PAGES(Yap_pages_ans_hash, struct answer_trie_hash); - INIT_PAGES(Yap_pages_gt_hash, struct global_trie_hash); + INIT_PAGES(GLOBAL_pages_tab_ent, struct table_entry); + INIT_PAGES(GLOBAL_pages_sg_fr, struct subgoal_frame); + INIT_PAGES(GLOBAL_pages_dep_fr, struct dependency_frame); + INIT_PAGES(GLOBAL_pages_sg_node, struct subgoal_trie_node); + INIT_PAGES(GLOBAL_pages_ans_node, struct answer_trie_node); + INIT_PAGES(GLOBAL_pages_gt_node, struct global_trie_node); + INIT_PAGES(GLOBAL_pages_sg_hash, struct subgoal_trie_hash); + INIT_PAGES(GLOBAL_pages_ans_hash, struct answer_trie_hash); + INIT_PAGES(GLOBAL_pages_gt_hash, struct global_trie_hash); #endif /* TABLING */ #if defined(YAPOR) && defined(TABLING) - INIT_PAGES(Yap_pages_susp_fr, struct suspension_frame); + INIT_PAGES(GLOBAL_pages_susp_fr, struct suspension_frame); #endif /* YAPOR && TABLING */ #ifdef YAPOR /* global static data */ - Yap_number_workers= n_workers; - Yap_worker_pid(0) = getpid(); - for (i = 1; i < Yap_number_workers; i++) Yap_worker_pid(i) = 0; - Yap_scheduler_loop = sch_loop; - Yap_delayed_release_load = delay_load; + GLOBAL_number_workers= n_workers; + GLOBAL_worker_pid(0) = getpid(); + for (i = 1; i < GLOBAL_number_workers; i++) GLOBAL_worker_pid(i) = 0; + GLOBAL_scheduler_loop = sch_loop; + GLOBAL_delayed_release_load = delay_load; /* global data related to or-performance */ - Yap_number_goals = 0; - Yap_best_times(0) = 0; - Yap_performance_mode = PERFORMANCE_OFF; + GLOBAL_number_goals = 0; + GLOBAL_best_times(0) = 0; + GLOBAL_performance_mode = PERFORMANCE_OFF; /* global data related to or-parallelism */ - BITMAP_clear(Yap_bm_present_workers); - for (i = 0; i < Yap_number_workers; i++) - BITMAP_insert(Yap_bm_present_workers, i); - BITMAP_copy(Yap_bm_idle_workers, Yap_bm_present_workers); - BITMAP_clear(Yap_bm_root_cp_workers); - BITMAP_clear(Yap_bm_invisible_workers); - BITMAP_clear(Yap_bm_requestable_workers); - BITMAP_clear(Yap_bm_executing_workers); - BITMAP_copy(Yap_bm_finished_workers, Yap_bm_present_workers); - INIT_LOCK(Yap_locks_bm_idle_workers); - INIT_LOCK(Yap_locks_bm_root_cp_workers); - INIT_LOCK(Yap_locks_bm_invisible_workers); - INIT_LOCK(Yap_locks_bm_requestable_workers); - INIT_LOCK(Yap_locks_bm_executing_workers); - INIT_LOCK(Yap_locks_bm_finished_workers); + ALLOC_OR_FRAME(GLOBAL_root_or_fr); + BITMAP_clear(GLOBAL_bm_present_workers); + for (i = 0; i < GLOBAL_number_workers; i++) + BITMAP_insert(GLOBAL_bm_present_workers, i); + BITMAP_copy(GLOBAL_bm_idle_workers, GLOBAL_bm_present_workers); + BITMAP_clear(GLOBAL_bm_root_cp_workers); + BITMAP_clear(GLOBAL_bm_invisible_workers); + BITMAP_clear(GLOBAL_bm_requestable_workers); + BITMAP_clear(GLOBAL_bm_executing_workers); + BITMAP_copy(GLOBAL_bm_finished_workers, GLOBAL_bm_present_workers); + INIT_LOCK(GLOBAL_locks_bm_idle_workers); + INIT_LOCK(GLOBAL_locks_bm_root_cp_workers); + INIT_LOCK(GLOBAL_locks_bm_invisible_workers); + INIT_LOCK(GLOBAL_locks_bm_requestable_workers); + INIT_LOCK(GLOBAL_locks_bm_executing_workers); + INIT_LOCK(GLOBAL_locks_bm_finished_workers); #ifdef TABLING_INNER_CUTS - INIT_LOCK(Yap_locks_bm_pruning_workers); + INIT_LOCK(GLOBAL_locks_bm_pruning_workers); #endif /* TABLING_INNER_CUTS */ - Yap_locks_who_locked_heap = MAX_WORKERS; - INIT_LOCK(Yap_locks_heap_access); - INIT_LOCK(Yap_locks_alloc_block); - if (Yap_number_workers== 1) - Yap_parallel_execution_mode = FALSE; + GLOBAL_locks_who_locked_heap = MAX_WORKERS; + INIT_LOCK(GLOBAL_locks_heap_access); + INIT_LOCK(GLOBAL_locks_alloc_block); + if (GLOBAL_number_workers== 1) + GLOBAL_parallel_execution_mode = FALSE; else - Yap_parallel_execution_mode = TRUE; + GLOBAL_parallel_execution_mode = TRUE; #endif /* YAPOR */ #ifdef TABLING /* global data related to tabling */ - new_global_trie_node(Yap_root_gt, 0, NULL, NULL, NULL); - Yap_root_tab_ent = NULL; + new_global_trie_node(GLOBAL_root_gt, 0, NULL, NULL, NULL); + GLOBAL_root_tab_ent = NULL; #ifdef LIMIT_TABLING - Yap_first_sg_fr = NULL; - Yap_last_sg_fr = NULL; - Yap_check_sg_fr = NULL; + GLOBAL_first_sg_fr = NULL; + GLOBAL_last_sg_fr = NULL; + GLOBAL_check_sg_fr = NULL; #endif /* LIMIT_TABLING */ - Yap_root_dep_fr = NULL; + new_dependency_frame(GLOBAL_root_dep_fr, FALSE, NULL, NULL, NULL, NULL, NULL); for (i = 0; i < MAX_TABLE_VARS; i++) { - CELL *pt = Yap_table_var_enumerator_addr(i); + CELL *pt = GLOBAL_table_var_enumerator_addr(i); RESET_VARIABLE(pt); } #ifdef TABLE_LOCK_AT_WRITE_LEVEL for (i = 0; i < TABLE_LOCK_BUCKETS; i++) - INIT_LOCK(Yap_table_lock(i)); + INIT_LOCK(GLOBAL_table_lock(i)); #endif /* TABLE_LOCK_AT_WRITE_LEVEL */ #endif /* TABLING */ @@ -159,47 +160,46 @@ void Yap_init_optyap_data(int max_table_size, int n_workers, int sch_loop, int d } -void Yap_init_local(void) { +void Yap_init_local_optyap_data(int wid) { #ifdef YAPOR CACHE_REGS /* local data related to or-parallelism */ - LOCAL = REMOTE + worker_id; - Set_LOCAL_top_cp((choiceptr) Yap_LocalBase); - LOCAL_top_or_fr = Yap_root_or_fr; - LOCAL_load = 0; - LOCAL_share_request = MAX_WORKERS; - LOCAL_reply_signal = worker_ready; + Set_REMOTE_top_cp(wid, (choiceptr) LOCAL_LocalBase); + REMOTE_top_or_fr(wid) = GLOBAL_root_or_fr; + REMOTE_load(wid) = 0; + REMOTE_share_request(wid) = MAX_WORKERS; + REMOTE_reply_signal(wid) = worker_ready; #ifdef YAPOR_COPY - INIT_LOCK(LOCAL_lock_signals); + INIT_LOCK(REMOTE_lock_signals(wid)); #endif /* YAPOR_COPY */ - Set_LOCAL_prune_request(NULL); + Set_REMOTE_prune_request(wid, NULL); + INIT_LOCK(REMOTE_lock(wid)); #endif /* YAPOR */ - INIT_LOCK(LOCAL_lock); + #ifdef TABLING /* local data related to tabling */ - LOCAL_next_free_ans_node = NULL; - LOCAL_top_sg_fr = NULL; - LOCAL_top_dep_fr = Yap_root_dep_fr; + REMOTE_next_free_ans_node(wid) = NULL; + REMOTE_top_sg_fr(wid) = NULL; + REMOTE_top_dep_fr(wid) = GLOBAL_root_dep_fr; #ifdef YAPOR - Set_LOCAL_top_cp_on_stack((choiceptr) Yap_LocalBase); /* ??? */ - LOCAL_top_susp_or_fr = Yap_root_or_fr; + Set_REMOTE_top_cp_on_stack(wid, (choiceptr) LOCAL_LocalBase); /* ??? */ + REMOTE_top_susp_or_fr(wid) = GLOBAL_root_or_fr; #endif /* YAPOR */ #endif /* TABLING */ return; } -void make_root_frames(void) { -#ifdef YAPOR +void Yap_init_root_frames(void) { CACHE_REGS - /* root or frame */ - or_fr_ptr or_fr; - ALLOC_OR_FRAME(or_fr); +#ifdef YAPOR + /* root or frame */ + or_fr_ptr or_fr = GLOBAL_root_or_fr; INIT_LOCK(OrFr_lock(or_fr)); OrFr_alternative(or_fr) = NULL; - BITMAP_copy(OrFr_members(or_fr), Yap_bm_present_workers); - SetOrFr_node(or_fr, (choiceptr) Yap_LocalBase); + BITMAP_copy(OrFr_members(or_fr), GLOBAL_bm_present_workers); + SetOrFr_node(or_fr, (choiceptr) LOCAL_LocalBase); OrFr_nearest_livenode(or_fr) = NULL; OrFr_depth(or_fr) = 0; Set_OrFr_pend_prune_cp(or_fr, NULL); @@ -209,69 +209,20 @@ void make_root_frames(void) { OrFr_tg_solutions(or_fr) = NULL; #endif /* TABLING_INNER_CUTS */ #ifdef TABLING - OrFr_owners(or_fr) = Yap_number_workers; + OrFr_owners(or_fr) = GLOBAL_number_workers; OrFr_next_on_stack(or_fr) = NULL; OrFr_suspensions(or_fr) = NULL; OrFr_nearest_suspnode(or_fr) = or_fr; #endif /* TABLING */ OrFr_next(or_fr) = NULL; - Yap_root_or_fr = or_fr; #endif /* YAPOR */ #ifdef TABLING /* root dependency frame */ - if (!Yap_root_dep_fr) { - new_dependency_frame(Yap_root_dep_fr, FALSE, NULL, NULL, NULL, NULL, NULL); -#ifdef TABLING - DepFr_cons_cp(Yap_root_dep_fr) = B; -#endif /* TABLING */ - } + DepFr_cons_cp(GLOBAL_root_dep_fr) = B; #endif /* TABLING */ } -#ifdef YAPOR -void init_workers(void) { - CACHE_REGS - int proc; -#ifdef YAPOR_THREADS - return; -#endif /* YAPOR_THREADS */ -#ifdef YAPOR_COW - if (Yap_number_workers> 1) { - int son; - son = fork(); - if (son == -1) - Yap_Error(FATAL_ERROR, TermNil, "fork error (init_workers)"); - if (son > 0) { - /* I am the father, I must stay here and wait for my children to all die */ - struct sigaction sigact; - - Yap_master_worker = getpid(); - sigact.sa_handler = SIG_DFL; - sigemptyset(&sigact.sa_mask); - sigact.sa_flags = SA_RESTART; - sigaction(SIGINT, &sigact, NULL); - pause(); - exit(0); - } else Yap_worker_pid(0) = getpid(); - } -#endif /* YAPOR_COW */ - for (proc = 1; proc < Yap_number_workers; proc++) { - int son; - son = fork(); - if (son == -1) - Yap_Error(FATAL_ERROR, TermNil, "fork error (init_workers)"); - if (son == 0) { - /* new worker */ - worker_id = proc; - Yap_remap_optyap_memory(); - break; - } - else Yap_worker_pid(proc) = son; - } -} -#endif /* YAPOR */ - void itos(int i, char *s) { int n,r,j; diff --git a/OPTYap/opt.macros.h b/OPTYap/opt.macros.h index 55ad8a4fe..937e0627d 100644 --- a/OPTYap/opt.macros.h +++ b/OPTYap/opt.macros.h @@ -86,11 +86,11 @@ extern int Yap_page_size; ** USE_PAGES_MALLOC ** *************************************************************************************************/ #define FREE_PAGE(PG_HD) \ - LOCK(Pg_lock(Yap_pages_void)); \ - UPDATE_STATS(Pg_str_in_use(Yap_pages_void), -1); \ - PgHd_next(PG_HD) = Pg_free_pg(Yap_pages_void); \ - Pg_free_pg(Yap_pages_void) = PG_HD; \ - UNLOCK(Pg_lock(Yap_pages_void)) + LOCK(Pg_lock(GLOBAL_pages_void)); \ + UPDATE_STATS(Pg_str_in_use(GLOBAL_pages_void), -1); \ + PgHd_next(PG_HD) = Pg_free_pg(GLOBAL_pages_void); \ + Pg_free_pg(GLOBAL_pages_void) = PG_HD; \ + UNLOCK(Pg_lock(GLOBAL_pages_void)) #define FREE_STRUCT(STR, STR_PAGES, STR_TYPE) \ { pg_hd_ptr pg_hd; \ @@ -152,28 +152,28 @@ extern int Yap_page_size; if (shmctl(shmid, IPC_RMID, 0) != 0) \ Yap_Error(FATAL_ERROR, TermNil, "shmctl error (ALLOC_PAGE)"); \ aux_pg_hd = (pg_hd_ptr)(((void *)PG_HD) + Yap_page_size); \ - Pg_free_pg(Yap_pages_void) = aux_pg_hd; \ + Pg_free_pg(GLOBAL_pages_void) = aux_pg_hd; \ for (i = 2; i < SHMMAX / Yap_page_size; i++) { \ PgHd_next(aux_pg_hd) = (pg_hd_ptr)(((void *)aux_pg_hd) + Yap_page_size); \ aux_pg_hd = PgHd_next(aux_pg_hd); \ } \ PgHd_next(aux_pg_hd) = NULL; \ - UPDATE_STATS(Pg_pg_alloc(Yap_pages_void), SHMMAX / Yap_page_size); \ + UPDATE_STATS(Pg_pg_alloc(GLOBAL_pages_void), SHMMAX / Yap_page_size); \ } #define RECOVER_UNUSED_SPACE(STR_PAGES) \ - { sg_fr_ptr sg_fr = Yap_check_sg_fr; \ + { sg_fr_ptr sg_fr = GLOBAL_check_sg_fr; \ do { \ if (sg_fr) \ sg_fr = SgFr_next(sg_fr); \ else \ - sg_fr = Yap_first_sg_fr; \ + sg_fr = GLOBAL_first_sg_fr; \ if (sg_fr == NULL) \ Yap_Error(FATAL_ERROR, TermNil, "no space left (RECOVER_UNUSED_SPACE)"); \ /* see function 'InteractSIGINT' in file 'sysbits.c' */ \ /* Yap_Error(PURE_ABORT, TermNil, ""); */ \ /* restore_absmi_regs(&Yap_standard_regs); */ \ - /* siglongjmp (Yap_RestartEnv, 1); */ \ + /* siglongjmp (LOCAL_RestartEnv, 1); */ \ if (SgFr_first_answer(sg_fr) && \ SgFr_first_answer(sg_fr) != SgFr_answer_trie(sg_fr)) { \ SgFr_state(sg_fr) = ready; \ @@ -185,8 +185,8 @@ extern int Yap_page_size; TRAVERSE_MODE_NORMAL, TRAVERSE_POSITION_FIRST); \ TrNode_child(SgFr_answer_trie(sg_fr)) = NULL; \ } \ - } while (Pg_free_pg(Yap_pages_void) == Pg_free_pg(STR_PAGES)); \ - Yap_check_sg_fr = sg_fr; \ + } while (Pg_free_pg(GLOBAL_pages_void) == Pg_free_pg(STR_PAGES)); \ + GLOBAL_check_sg_fr = sg_fr; \ } #define ALLOC_STRUCT(STR, STR_PAGES, STR_TYPE) \ @@ -195,20 +195,20 @@ extern int Yap_page_size; pg_hd = Pg_free_pg(STR_PAGES); \ while (pg_hd == NULL) { \ UNLOCK(Pg_lock(STR_PAGES)); \ - LOCK(Pg_lock(Yap_pages_void)); \ - if (Pg_free_pg(Yap_pages_void)) { \ - pg_hd = Pg_free_pg(Yap_pages_void); \ - Pg_free_pg(Yap_pages_void) = PgHd_next(pg_hd); \ - UPDATE_STATS(Pg_str_in_use(Yap_pages_void), 1); \ - UNLOCK(Pg_lock(Yap_pages_void)); \ + LOCK(Pg_lock(GLOBAL_pages_void)); \ + if (Pg_free_pg(GLOBAL_pages_void)) { \ + pg_hd = Pg_free_pg(GLOBAL_pages_void); \ + Pg_free_pg(GLOBAL_pages_void) = PgHd_next(pg_hd); \ + UPDATE_STATS(Pg_str_in_use(GLOBAL_pages_void), 1); \ + UNLOCK(Pg_lock(GLOBAL_pages_void)); \ INIT_PAGE(pg_hd, STR_PAGES, STR_TYPE); \ - } else if (Yap_max_pages != Pg_pg_alloc(Yap_pages_void)) { \ + } else if ( GLOBAL_max_pages != Pg_pg_alloc(GLOBAL_pages_void)) { \ ALLOC_PAGE(pg_hd); \ - UPDATE_STATS(Pg_str_in_use(Yap_pages_void), 1); \ - UNLOCK(Pg_lock(Yap_pages_void)); \ + UPDATE_STATS(Pg_str_in_use(GLOBAL_pages_void), 1); \ + UNLOCK(Pg_lock(GLOBAL_pages_void)); \ INIT_PAGE(pg_hd, STR_PAGES, STR_TYPE); \ } else { \ - UNLOCK(Pg_lock(Yap_pages_void)); \ + UNLOCK(Pg_lock(GLOBAL_pages_void)); \ RECOVER_UNUSED_SPACE(STR_PAGES); \ LOCK(Pg_lock(STR_PAGES)); \ pg_hd = Pg_free_pg(STR_PAGES); \ @@ -230,20 +230,20 @@ extern int Yap_page_size; pg_hd = Pg_free_pg(STR_PAGES); \ while (pg_hd == NULL) { \ UNLOCK(Pg_lock(STR_PAGES)); \ - LOCK(Pg_lock(Yap_pages_void)); \ - if (Pg_free_pg(Yap_pages_void)) { \ - pg_hd = Pg_free_pg(Yap_pages_void); \ - Pg_free_pg(Yap_pages_void) = PgHd_next(pg_hd); \ - UPDATE_STATS(Pg_str_in_use(Yap_pages_void), 1); \ - UNLOCK(Pg_lock(Yap_pages_void)); \ + LOCK(Pg_lock(GLOBAL_pages_void)); \ + if (Pg_free_pg(GLOBAL_pages_void)) { \ + pg_hd = Pg_free_pg(GLOBAL_pages_void); \ + Pg_free_pg(GLOBAL_pages_void) = PgHd_next(pg_hd); \ + UPDATE_STATS(Pg_str_in_use(GLOBAL_pages_void), 1); \ + UNLOCK(Pg_lock(GLOBAL_pages_void)); \ INIT_PAGE(pg_hd, STR_PAGES, STR_TYPE); \ - } else if (Yap_max_pages != Pg_pg_alloc(Yap_pages_void)) { \ + } else if ( GLOBAL_max_pages != Pg_pg_alloc(GLOBAL_pages_void)) { \ ALLOC_PAGE(pg_hd); \ - UPDATE_STATS(Pg_str_in_use(Yap_pages_void), 1); \ - UNLOCK(Pg_lock(Yap_pages_void)); \ + UPDATE_STATS(Pg_str_in_use(GLOBAL_pages_void), 1); \ + UNLOCK(Pg_lock(GLOBAL_pages_void)); \ INIT_PAGE(pg_hd, STR_PAGES, STR_TYPE); \ } else { \ - UNLOCK(Pg_lock(Yap_pages_void)); \ + UNLOCK(Pg_lock(GLOBAL_pages_void)); \ RECOVER_UNUSED_SPACE(STR_PAGES); \ LOCK(Pg_lock(STR_PAGES)); \ pg_hd = Pg_free_pg(STR_PAGES); \ @@ -263,8 +263,8 @@ extern int Yap_page_size; ** USE_PAGES_MALLOC && ! LIMIT_TABLING ** *************************************************************************************************/ #define ALLOC_PAGE(PG_HD) \ - LOCK(Pg_lock(Yap_pages_void)); \ - if (Pg_free_pg(Yap_pages_void) == NULL) { \ + LOCK(Pg_lock(GLOBAL_pages_void)); \ + if (Pg_free_pg(GLOBAL_pages_void) == NULL) { \ int i, shmid; \ pg_hd_ptr pg_hd, aux_pg_hd; \ if ((shmid = shmget(IPC_PRIVATE, SHMMAX, SHM_R|SHM_W)) == -1) \ @@ -273,19 +273,19 @@ extern int Yap_page_size; Yap_Error(FATAL_ERROR, TermNil, "shmat error (ALLOC_PAGE)"); \ if (shmctl(shmid, IPC_RMID, 0) != 0) \ Yap_Error(FATAL_ERROR, TermNil, "shmctl error (ALLOC_PAGE)"); \ - Pg_free_pg(Yap_pages_void) = pg_hd; \ + Pg_free_pg(GLOBAL_pages_void) = pg_hd; \ for (i = 1; i < SHMMAX / Yap_page_size; i++) { \ aux_pg_hd = (pg_hd_ptr)(((void *)pg_hd) + Yap_page_size); \ PgHd_next(pg_hd) = aux_pg_hd; \ pg_hd = aux_pg_hd; \ } \ PgHd_next(pg_hd) = NULL; \ - UPDATE_STATS(Pg_pg_alloc(Yap_pages_void), SHMMAX / Yap_page_size); \ + UPDATE_STATS(Pg_pg_alloc(GLOBAL_pages_void), SHMMAX / Yap_page_size); \ } \ - UPDATE_STATS(Pg_str_in_use(Yap_pages_void), 1); \ - PG_HD = Pg_free_pg(Yap_pages_void); \ - Pg_free_pg(Yap_pages_void) = PgHd_next(PG_HD); \ - UNLOCK(Pg_lock(Yap_pages_void)) + UPDATE_STATS(Pg_str_in_use(GLOBAL_pages_void), 1); \ + PG_HD = Pg_free_pg(GLOBAL_pages_void); \ + Pg_free_pg(GLOBAL_pages_void) = PgHd_next(PG_HD); \ + UNLOCK(Pg_lock(GLOBAL_pages_void)) #define ALLOC_STRUCT(STR, STR_PAGES, STR_TYPE) \ { pg_hd_ptr pg_hd; \ @@ -380,55 +380,55 @@ extern int Yap_page_size; } #define FREE_HASH_BUCKETS(BUCKET_PTR) FREE_BLOCK(BUCKET_PTR) -#define ALLOC_OR_FRAME(STR) ALLOC_STRUCT(STR, Yap_pages_or_fr , struct or_frame) -#define FREE_OR_FRAME(STR) FREE_STRUCT(STR, Yap_pages_or_fr , struct or_frame) +#define ALLOC_OR_FRAME(STR) ALLOC_STRUCT(STR, GLOBAL_pages_or_fr , struct or_frame) +#define FREE_OR_FRAME(STR) FREE_STRUCT(STR, GLOBAL_pages_or_fr , struct or_frame) -#define ALLOC_QG_SOLUTION_FRAME(STR) ALLOC_STRUCT(STR, Yap_pages_qg_sol_fr , struct query_goal_solution_frame) -#define FREE_QG_SOLUTION_FRAME(STR) FREE_STRUCT(STR, Yap_pages_qg_sol_fr , struct query_goal_solution_frame) +#define ALLOC_QG_SOLUTION_FRAME(STR) ALLOC_STRUCT(STR, GLOBAL_pages_qg_sol_fr , struct query_goal_solution_frame) +#define FREE_QG_SOLUTION_FRAME(STR) FREE_STRUCT(STR, GLOBAL_pages_qg_sol_fr , struct query_goal_solution_frame) -#define ALLOC_QG_ANSWER_FRAME(STR) ALLOC_STRUCT(STR, Yap_pages_qg_ans_fr, struct query_goal_answer_frame) -#define FREE_QG_ANSWER_FRAME(STR) FREE_STRUCT(STR, Yap_pages_qg_ans_fr, struct query_goal_answer_frame) +#define ALLOC_QG_ANSWER_FRAME(STR) ALLOC_STRUCT(STR, GLOBAL_pages_qg_ans_fr, struct query_goal_answer_frame) +#define FREE_QG_ANSWER_FRAME(STR) FREE_STRUCT(STR, GLOBAL_pages_qg_ans_fr, struct query_goal_answer_frame) -#define ALLOC_TG_SOLUTION_FRAME(STR) ALLOC_STRUCT(STR, Yap_pages_tg_sol_fr, struct table_subgoal_solution_frame) -#define FREE_TG_SOLUTION_FRAME(STR) FREE_STRUCT(STR, Yap_pages_tg_sol_fr, struct table_subgoal_solution_frame) +#define ALLOC_TG_SOLUTION_FRAME(STR) ALLOC_STRUCT(STR, GLOBAL_pages_tg_sol_fr, struct table_subgoal_solution_frame) +#define FREE_TG_SOLUTION_FRAME(STR) FREE_STRUCT(STR, GLOBAL_pages_tg_sol_fr, struct table_subgoal_solution_frame) -#define ALLOC_TG_ANSWER_FRAME(STR) ALLOC_STRUCT(STR, Yap_pages_tg_ans_fr, struct table_subgoal_answer_frame) -#define FREE_TG_ANSWER_FRAME(STR) FREE_STRUCT(STR, Yap_pages_tg_ans_fr, struct table_subgoal_answer_frame) +#define ALLOC_TG_ANSWER_FRAME(STR) ALLOC_STRUCT(STR, GLOBAL_pages_tg_ans_fr, struct table_subgoal_answer_frame) +#define FREE_TG_ANSWER_FRAME(STR) FREE_STRUCT(STR, GLOBAL_pages_tg_ans_fr, struct table_subgoal_answer_frame) -#define ALLOC_TABLE_ENTRY(STR) ALLOC_STRUCT(STR, Yap_pages_tab_ent, struct table_entry) -#define FREE_TABLE_ENTRY(STR) FREE_STRUCT(STR, Yap_pages_tab_ent, struct table_entry) +#define ALLOC_TABLE_ENTRY(STR) ALLOC_STRUCT(STR, GLOBAL_pages_tab_ent, struct table_entry) +#define FREE_TABLE_ENTRY(STR) FREE_STRUCT(STR, GLOBAL_pages_tab_ent, struct table_entry) -#define ALLOC_SUBGOAL_FRAME(STR) ALLOC_STRUCT(STR, Yap_pages_sg_fr, struct subgoal_frame) -#define FREE_SUBGOAL_FRAME(STR) FREE_STRUCT(STR, Yap_pages_sg_fr, struct subgoal_frame) +#define ALLOC_SUBGOAL_FRAME(STR) ALLOC_STRUCT(STR, GLOBAL_pages_sg_fr, struct subgoal_frame) +#define FREE_SUBGOAL_FRAME(STR) FREE_STRUCT(STR, GLOBAL_pages_sg_fr, struct subgoal_frame) -#define ALLOC_DEPENDENCY_FRAME(STR) ALLOC_STRUCT(STR, Yap_pages_dep_fr, struct dependency_frame) -#define FREE_DEPENDENCY_FRAME(STR) FREE_STRUCT(STR, Yap_pages_dep_fr, struct dependency_frame) +#define ALLOC_DEPENDENCY_FRAME(STR) ALLOC_STRUCT(STR, GLOBAL_pages_dep_fr, struct dependency_frame) +#define FREE_DEPENDENCY_FRAME(STR) FREE_STRUCT(STR, GLOBAL_pages_dep_fr, struct dependency_frame) -#define ALLOC_SUSPENSION_FRAME(STR) ALLOC_STRUCT(STR, Yap_pages_susp_fr, struct suspension_frame) +#define ALLOC_SUSPENSION_FRAME(STR) ALLOC_STRUCT(STR, GLOBAL_pages_susp_fr, struct suspension_frame) #define FREE_SUSPENSION_FRAME(STR) FREE_BLOCK(SuspFr_global_start(STR)); \ - FREE_STRUCT(STR, Yap_pages_susp_fr, struct suspension_frame) + FREE_STRUCT(STR, GLOBAL_pages_susp_fr, struct suspension_frame) -#define ALLOC_GLOBAL_TRIE_NODE(STR) ALLOC_STRUCT(STR, Yap_pages_gt_node, struct global_trie_node) -#define FREE_GLOBAL_TRIE_NODE(STR) FREE_STRUCT(STR, Yap_pages_gt_node, struct global_trie_node) +#define ALLOC_GLOBAL_TRIE_NODE(STR) ALLOC_STRUCT(STR, GLOBAL_pages_gt_node, struct global_trie_node) +#define FREE_GLOBAL_TRIE_NODE(STR) FREE_STRUCT(STR, GLOBAL_pages_gt_node, struct global_trie_node) -#define ALLOC_SUBGOAL_TRIE_NODE(STR) ALLOC_STRUCT(STR, Yap_pages_sg_node, struct subgoal_trie_node) -#define FREE_SUBGOAL_TRIE_NODE(STR) FREE_STRUCT(STR, Yap_pages_sg_node, struct subgoal_trie_node) +#define ALLOC_SUBGOAL_TRIE_NODE(STR) ALLOC_STRUCT(STR, GLOBAL_pages_sg_node, struct subgoal_trie_node) +#define FREE_SUBGOAL_TRIE_NODE(STR) FREE_STRUCT(STR, GLOBAL_pages_sg_node, struct subgoal_trie_node) #ifdef YAPOR -#define ALLOC_ANSWER_TRIE_NODE(STR) ALLOC_NEXT_FREE_STRUCT(STR, Yap_pages_ans_node, struct answer_trie_node) +#define ALLOC_ANSWER_TRIE_NODE(STR) ALLOC_NEXT_FREE_STRUCT(STR, GLOBAL_pages_ans_node, struct answer_trie_node) #else /* TABLING */ -#define ALLOC_ANSWER_TRIE_NODE(STR) ALLOC_STRUCT(STR, Yap_pages_ans_node, struct answer_trie_node) +#define ALLOC_ANSWER_TRIE_NODE(STR) ALLOC_STRUCT(STR, GLOBAL_pages_ans_node, struct answer_trie_node) #endif /* YAPOR - TABLING */ -#define FREE_ANSWER_TRIE_NODE(STR) FREE_STRUCT(STR, Yap_pages_ans_node, struct answer_trie_node) +#define FREE_ANSWER_TRIE_NODE(STR) FREE_STRUCT(STR, GLOBAL_pages_ans_node, struct answer_trie_node) -#define ALLOC_GLOBAL_TRIE_HASH(STR) ALLOC_STRUCT(STR, Yap_pages_gt_hash, struct global_trie_hash) -#define FREE_GLOBAL_TRIE_HASH(STR) FREE_STRUCT(STR, Yap_pages_gt_hash, struct global_trie_hash) +#define ALLOC_GLOBAL_TRIE_HASH(STR) ALLOC_STRUCT(STR, GLOBAL_pages_gt_hash, struct global_trie_hash) +#define FREE_GLOBAL_TRIE_HASH(STR) FREE_STRUCT(STR, GLOBAL_pages_gt_hash, struct global_trie_hash) -#define ALLOC_SUBGOAL_TRIE_HASH(STR) ALLOC_STRUCT(STR, Yap_pages_sg_hash, struct subgoal_trie_hash) -#define FREE_SUBGOAL_TRIE_HASH(STR) FREE_STRUCT(STR, Yap_pages_sg_hash, struct subgoal_trie_hash) +#define ALLOC_SUBGOAL_TRIE_HASH(STR) ALLOC_STRUCT(STR, GLOBAL_pages_sg_hash, struct subgoal_trie_hash) +#define FREE_SUBGOAL_TRIE_HASH(STR) FREE_STRUCT(STR, GLOBAL_pages_sg_hash, struct subgoal_trie_hash) -#define ALLOC_ANSWER_TRIE_HASH(STR) ALLOC_STRUCT(STR, Yap_pages_ans_hash, struct answer_trie_hash) -#define FREE_ANSWER_TRIE_HASH(STR) FREE_STRUCT(STR, Yap_pages_ans_hash, struct answer_trie_hash) +#define ALLOC_ANSWER_TRIE_HASH(STR) ALLOC_STRUCT(STR, GLOBAL_pages_ans_hash, struct answer_trie_hash) +#define FREE_ANSWER_TRIE_HASH(STR) FREE_STRUCT(STR, GLOBAL_pages_ans_hash, struct answer_trie_hash) @@ -457,7 +457,7 @@ extern int Yap_page_size; ************************************************************************/ #define INFORMATION_MESSAGE(MESSAGE,ARGS...) \ - fprintf(stderr, "[ " MESSAGE " ]\n", ##ARGS) + Sfprintf(Serror, "[ " MESSAGE " ]\n", ##ARGS) #ifdef YAPOR #define ERROR_MESSAGE(MESSAGE) \ diff --git a/OPTYap/opt.memory.c b/OPTYap/opt.memory.c deleted file mode 100644 index a83bf895b..000000000 --- a/OPTYap/opt.memory.c +++ /dev/null @@ -1,274 +0,0 @@ -/************************************************************************ -** ** -** The YapTab/YapOr/OPTYap systems ** -** ** -** YapTab extends the Yap Prolog engine to support sequential tabling ** -** YapOr extends the Yap Prolog engine to support or-parallelism ** -** OPTYap extends the Yap Prolog engine to support or-parallel tabling ** -** ** -** ** -** Yap Prolog was developed at University of Porto, Portugal ** -** ** -************************************************************************/ - -/************************************** -** Includes & Declarations ** -**************************************/ - -#include "Yap.h" -#if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA) -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Yatom.h" -#include "YapHeap.h" -#include "alloc.h" -#include "heapgc.h" -#include "or.macros.h" - - - -/************************************ -** Macros & Declarations ** -************************************/ - -#define KBYTES 1024 - -#ifdef MMAP_MEMORY_MAPPING_SCHEME -int fd_mapfile; -#else /* SHM_MEMORY_MAPPING_SCHEME */ -int shm_mapid[MAX_WORKERS + 1]; -#endif /* MEMORY_MAPPING_SCHEME */ - - - -/****************************************** -** Local functions declaration ** -******************************************/ - -#ifdef MMAP_MEMORY_MAPPING_SCHEME -void open_mapfile(long TotalArea); -#else /* SHM_MEMORY_MAPPING_SCHEME */ -void shm_map_memory(int id, int size, void *shmaddr); -#endif /* MEMORY_MAPPING_SCHEME */ - - - -/******************************** -** Global functions ** -********************************/ - -void Yap_init_optyap_memory(long TrailAuxArea, long HeapArea, long GlobalLocalArea, int n_workers) { -#ifdef YAPOR_COW - int private_fd_mapfile; -#if MMAP_MEMORY_MAPPING_SCHEME - long TotalArea; -#endif /* MMAP_MEMORY_MAPPING_SCHEME */ -#else /* YAPOR_COPY || YAPOR_SBA */ - long TotalArea; -#endif - long ExtraArea; - - HeapArea = ADJUST_SIZE_TO_PAGE(HeapArea); - GlobalLocalArea = ADJUST_SIZE(GlobalLocalArea); - TrailAuxArea = ADJUST_SIZE(TrailAuxArea); - - /* initial allocation - model independent */ - ExtraArea = ADJUST_SIZE_TO_PAGE(sizeof(struct global_data) + MAX_WORKERS * sizeof(struct worker_local)); - Yap_WLocal = (struct worker_local *)(MMAP_ADDR - ExtraArea); - Yap_global = (struct global_data *)(MMAP_ADDR - sizeof(struct global_data)); - Yap_HeapBase = (ADDR) MMAP_ADDR; - Yap_GlobalBase = (ADDR) (MMAP_ADDR + HeapArea); - - /* shared memory allocation - model dependent */ -#ifdef YAPOR_COW - /* acow just needs one stack */ -#ifdef MMAP_MEMORY_MAPPING_SCHEME - /* I need this for MMAP to know what it must allocate */ - TotalArea = HeapArea; -#endif /* MMAP_MEMORY_MAPPING_SCHEME */ -#else /* YAPOR_COPY || YAPOR_SBA */ - /* the others need n stacks */ - Yap_worker_area_size = ADJUST_SIZE_TO_PAGE(GlobalLocalArea + TrailAuxArea); - TotalArea = ExtraArea + HeapArea + Yap_worker_area_size * n_workers; -#endif - -#ifdef MMAP_MEMORY_MAPPING_SCHEME - /* map total area in a single go */ - open_mapfile(TotalArea); - if (mmap((void *) Yap_WLocal, (size_t) TotalArea, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_FIXED, fd_mapfile, 0) == (void *) -1) - Yap_Error(FATAL_ERROR, TermNil, "mmap error (Yap_init_optyap_memory)"); -#else /* SHM_MEMORY_MAPPING_SCHEME */ - /* most systems are limited regarding what we can allocate */ -#ifdef YAPOR_COW - /* single shared segment in ACOW */ - shm_map_memory(0, ExtraArea + HeapArea, (void *) MMAP_ADDR); -#else /* YAPOR_COPY || YAPOR_SBA */ - /* place as segment n otherwise (0..n-1 reserved for worker areas */ - shm_map_memory(n_workers, ExtraArea + HeapArea, (void *) Yap_WLocal); - { int i; - for (i = 0; i < n_workers; i++) - shm_map_memory(i, Yap_worker_area_size, Yap_GlobalBase + Yap_worker_area_size * i); - } -#endif -#endif /* MEMORY_MAPPING_SCHEME */ - -#ifdef YAPOR_COW - /* just allocate local space for stacks */ - if ((private_fd_mapfile = open("/dev/zero", O_RDWR)) < 0) - Yap_Error(FATAL_ERROR, TermNil, "open error (Yap_init_optyap_memory)"); - if (mmap(Yap_GlobalBase, GlobalLocalArea + TrailAuxArea, PROT_READ|PROT_WRITE, - MAP_PRIVATE|MAP_FIXED, private_fd_mapfile, 0) == (void *) -1) - Yap_Error(FATAL_ERROR, TermNil, "mmap error (Yap_init_optyap_memory)"); - close(private_fd_mapfile); -#endif /* YAPOR_COW */ - -#ifdef YAPOR_SBA - /* alloc space for the sparse binding array */ - sba_size = Yap_worker_area_size * n_workers; - if ((binding_array = (char *)malloc(sba_size)) == NULL) - Yap_Error(FATAL_ERROR, TermNil, "malloc error (Yap_init_optyap_memory)"); - if ((CELL)binding_array & MBIT) { - Yap_Error(INTERNAL_ERROR, TermNil, "binding_array start address conflicts with tag used in IDB (Yap_init_optyap_memory)"); - } - sba_offset = binding_array - Yap_GlobalBase; - sba_end = (int)binding_array + sba_size; -#endif /* YAPOR_SBA */ - - Yap_TrailBase = Yap_GlobalBase + GlobalLocalArea; - Yap_LocalBase = Yap_TrailBase - CellSize; - if (TrailAuxArea > 262144) /* 262144 = 256 * 1024 */ - Yap_TrailTop = Yap_TrailBase + (TrailAuxArea - 131072); /* 131072 = 262144 / 2 */ - else - Yap_TrailTop = Yap_TrailBase + (TrailAuxArea / 2); - HeapMax = (CELL)(Yap_TrailBase + (TrailAuxArea - CellSize)); - - Yap_InitHeap(Yap_HeapBase); -} - - - -void Yap_remap_optyap_memory(void) { -#ifdef YAPOR_SBA - /* setup workers so that they have different areas */ - Yap_GlobalBase += worker_id * Yap_worker_area_size; - Yap_TrailBase += worker_id * Yap_worker_area_size; - Yap_LocalBase += worker_id * Yap_worker_area_size; - Yap_TrailTop += worker_id * Yap_worker_area_size; -#endif /* YAPOR_SBA */ - -#ifdef YAPOR_COPY - int i; - void *remap_addr = Yap_GlobalBase; -#ifdef MMAP_MEMORY_MAPPING_SCHEME - long remap_offset = (ADDR) remap_addr - (ADDR) Yap_WLocal; - if (munmap(remap_addr, (size_t)(Yap_worker_area_size * Yap_number_workers)) == -1) - Yap_Error(FATAL_ERROR, TermNil, "munmap error (Yap_remap_optyap_memory)"); - for (i = 0; i < Yap_number_workers; i++) - if (mmap(remap_addr + worker_offset(i), (size_t)Yap_worker_area_size, PROT_READ|PROT_WRITE, - MAP_SHARED|MAP_FIXED, fd_mapfile, remap_offset + i * Yap_worker_area_size) == (void *) -1) - Yap_Error(FATAL_ERROR, TermNil, "mmap error (Yap_remap_optyap_memory)"); -#else /* SHM_MEMORY_MAPPING_SCHEME */ - for (i = 0; i < Yap_number_workers; i++) - if (shmdt(remap_addr + Yap_worker_area_size * i) == -1) - Yap_Error(FATAL_ERROR, TermNil, "shmdt error (Yap_remap_optyap_memory)"); - for (i = 0; i < Yap_number_workers; i++) - if(shmat(shm_mapid[i], remap_addr + worker_offset(i), 0) == (void *) -1) - Yap_Error(FATAL_ERROR, TermNil, "shmat error (Yap_remap_optyap_memory)"); -#endif /* MEMORY_MAPPING_SCHEME */ -#endif /* YAPOR_COPY */ -} - - -void Yap_unmap_optyap_memory (void) { -#ifdef MMAP_MEMORY_MAPPING_SCHEME - char MapFile[20]; -#else /* SHM_MEMORY_MAPPING_SCHEME */ - int i; -#endif /* MEMORY_MAPPING_SCHEME */ - int proc; - - INFORMATION_MESSAGE("Worker %d exiting...", worker_id); - for (proc = 0; proc < Yap_number_workers; proc++) { - if (proc != worker_id && Yap_worker_pid(proc) != 0) { - if (kill(Yap_worker_pid(proc), SIGKILL) != 0) - INFORMATION_MESSAGE("Can't kill process %d", Yap_worker_pid(proc)); - else - INFORMATION_MESSAGE("Killing process %d", Yap_worker_pid(proc)); - } - } - -#ifdef YAPOR_COW - if (Yap_number_workers > 1) { - if (kill(Yap_master_worker, SIGINT) != 0) - INFORMATION_MESSAGE("Can't kill process %d", Yap_master_worker); - else - INFORMATION_MESSAGE("Killing process %d", Yap_master_worker); - } -#endif /* YAPOR_COW */ - - -#ifdef MMAP_MEMORY_MAPPING_SCHEME - strcpy(MapFile,"./mapfile"); -#ifdef YAPOR_COW - itos(Yap_master_worker, &MapFile[9]); -#else /* YAPOR_COPY || YAPOR_SBA */ - itos(Yap_worker_pid(0), &MapFile[9]); -#endif - if (remove(MapFile) == 0) - INFORMATION_MESSAGE("Removing mapfile \"%s\"", MapFile); - else - INFORMATION_MESSAGE("Can't remove mapfile \"%s\"", MapFile); -#else /* SHM_MEMORY_MAPPING_SCHEME */ -#ifdef YAPOR_COW - i = 0; -#else /* YAPOR_COPY || YAPOR_SBA */ - for (i = 0; i < Yap_number_workers + 1; i++) -#endif - { - if (shmctl(shm_mapid[i], IPC_RMID, 0) == 0) - INFORMATION_MESSAGE("Removing shared memory segment %d", shm_mapid[i]); - else - INFORMATION_MESSAGE("Can't remove shared memory segment %d", shm_mapid[i]); - } -#endif /* MEMORY_MAPPING_SCHEME */ - return; -} - - - -/* ------------------------- ** -** Local functions ** -** ------------------------- */ - -#ifdef MMAP_MEMORY_MAPPING_SCHEME -void open_mapfile(long TotalArea) { - char mapfile[20]; - strcpy(mapfile,"./mapfile"); - itos(getpid(), &mapfile[9]); - if ((fd_mapfile = open(mapfile, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0) - Yap_Error(FATAL_ERROR, TermNil, "open error (open_mapfile)"); - if (lseek(fd_mapfile, TotalArea, SEEK_SET) < 0) - Yap_Error(FATAL_ERROR, TermNil, "lseek error (open_mapfile)"); - if (write(fd_mapfile, "", 1) < 0) - Yap_Error(FATAL_ERROR, TermNil, "write error (open_mapfile)"); - return; -} -#else /* SHM_MEMORY_MAPPING_SCHEME */ -void shm_map_memory(int id, int size, void *shmaddr) { - if (size > SHMMAX) - Yap_Error(FATAL_ERROR, TermNil, "maximum size for a shm segment exceeded (shm_map_memory)"); - if ((shm_mapid[id] = shmget(IPC_PRIVATE, size, SHM_R|SHM_W)) == -1) - Yap_Error(FATAL_ERROR, TermNil, "shmget error (shm_map_memory)"); - if (shmat(shm_mapid[id], shmaddr, 0) == (void *) -1) - Yap_Error(FATAL_ERROR, TermNil, "shmat error (shm_map_memory)"); - return; -} -#endif /* MMAP_MEMORY_MAPPING_SCHEME */ -#endif /* YAPOR_COPY || YAPOR_COW || YAPOR_SBA */ diff --git a/OPTYap/opt.preds.c b/OPTYap/opt.preds.c index 0be55697c..3e23b36f1 100644 --- a/OPTYap/opt.preds.c +++ b/OPTYap/opt.preds.c @@ -17,14 +17,13 @@ #include "Yap.h" #if defined(YAPOR) || defined(TABLING) -#include +#include "Yatom.h" +#include "YapHeap.h" +#include "SWI-Prolog.h" +#ifdef YAPOR #if HAVE_STRING_H #include #endif /* HAVE_STRING_H */ -#include "Yatom.h" -#include "YapHeap.h" -#include "yapio.h" -#ifdef YAPOR #if HAVE_SYS_TIME_H #include #endif /* HAVE_SYS_TIME_H */ @@ -43,9 +42,11 @@ static Int p_table( USES_REGS1 ); static Int p_tabling_mode( USES_REGS1 ); static Int p_abolish_table( USES_REGS1 ); static Int p_abolish_all_tables( USES_REGS1 ); +static Int p_abolish_all_local_tables( USES_REGS1 ); static Int p_show_tabled_predicates( USES_REGS1 ); static Int p_show_table( USES_REGS1 ); static Int p_show_all_tables( USES_REGS1 ); +static Int p_show_all_local_tables( USES_REGS1 ); static Int p_show_global_trie( USES_REGS1 ); static Int p_show_statistics_table( USES_REGS1 ); static Int p_show_statistics_tabling( USES_REGS1 ); @@ -76,26 +77,26 @@ static inline void answer_to_stdout(char *answer); #endif /* YAPOR */ #ifdef TABLING -static inline long show_statistics_table_entries(void); -static inline long show_statistics_subgoal_frames(void); -static inline long show_statistics_dependency_frames(void); -static inline long show_statistics_subgoal_trie_nodes(void); -static inline long show_statistics_answer_trie_nodes(void); -static inline long show_statistics_subgoal_trie_hashes(void); -static inline long show_statistics_answer_trie_hashes(void); -static inline long show_statistics_global_trie_nodes(void); -static inline long show_statistics_global_trie_hashes(void); +static inline long show_statistics_table_entries(IOSTREAM *out); +static inline long show_statistics_subgoal_frames(IOSTREAM *out); +static inline long show_statistics_dependency_frames(IOSTREAM *out); +static inline long show_statistics_subgoal_trie_nodes(IOSTREAM *out); +static inline long show_statistics_answer_trie_nodes(IOSTREAM *out); +static inline long show_statistics_subgoal_trie_hashes(IOSTREAM *out); +static inline long show_statistics_answer_trie_hashes(IOSTREAM *out); +static inline long show_statistics_global_trie_nodes(IOSTREAM *out); +static inline long show_statistics_global_trie_hashes(IOSTREAM *out); #endif /* TABLING */ #ifdef YAPOR -static inline long show_statistics_or_frames(void); -static inline long show_statistics_query_goal_solution_frames(void); -static inline long show_statistics_query_goal_answer_frames(void); +static inline long show_statistics_or_frames(IOSTREAM *out); +static inline long show_statistics_query_goal_solution_frames(IOSTREAM *out); +static inline long show_statistics_query_goal_answer_frames(IOSTREAM *out); #endif /* YAPOR */ #if defined(YAPOR) && defined(TABLING) -static inline long show_statistics_suspension_frames(void); +static inline long show_statistics_suspension_frames(IOSTREAM *out); #ifdef TABLING_INNER_CUTS -static inline long show_statistics_table_subgoal_solution_frames(void); -static inline long show_statistics_table_subgoal_answer_frames(void); +static inline long show_statistics_table_subgoal_solution_frames(IOSTREAM *out); +static inline long show_statistics_table_subgoal_answer_frames(IOSTREAM *out); #endif /* TABLING_INNER_CUTS */ #endif /* YAPOR && TABLING */ @@ -129,13 +130,15 @@ void Yap_init_optyap_preds(void) { Yap_InitCPred("$c_tabling_mode", 3, p_tabling_mode, SafePredFlag|SyncPredFlag|HiddenPredFlag); Yap_InitCPred("$c_abolish_table", 2, p_abolish_table, SafePredFlag|SyncPredFlag|HiddenPredFlag); Yap_InitCPred("abolish_all_tables", 0, p_abolish_all_tables, SafePredFlag|SyncPredFlag); - Yap_InitCPred("show_tabled_predicates", 0, p_show_tabled_predicates, SafePredFlag|SyncPredFlag); - Yap_InitCPred("$c_show_table", 2, p_show_table, SafePredFlag|SyncPredFlag|HiddenPredFlag); - Yap_InitCPred("show_all_tables", 0, p_show_all_tables, SafePredFlag|SyncPredFlag); - Yap_InitCPred("show_global_trie", 0, p_show_global_trie, SafePredFlag|SyncPredFlag); - Yap_InitCPred("$c_table_statistics", 2, p_show_statistics_table, SafePredFlag|SyncPredFlag|HiddenPredFlag); - Yap_InitCPred("tabling_statistics", 0, p_show_statistics_tabling, SafePredFlag|SyncPredFlag); - Yap_InitCPred("global_trie_statistics", 0, p_show_statistics_global_trie, SafePredFlag|SyncPredFlag); + Yap_InitCPred("abolish_all_local_tables", 0, p_abolish_all_local_tables, SafePredFlag|SyncPredFlag); + Yap_InitCPred("show_tabled_predicates", 1, p_show_tabled_predicates, SafePredFlag|SyncPredFlag); + Yap_InitCPred("$c_show_table", 3, p_show_table, SafePredFlag|SyncPredFlag|HiddenPredFlag); + Yap_InitCPred("show_all_tables", 1, p_show_all_tables, SafePredFlag|SyncPredFlag); + Yap_InitCPred("show_all_local_tables", 1, p_show_all_local_tables, SafePredFlag|SyncPredFlag); + Yap_InitCPred("show_global_trie", 1, p_show_global_trie, SafePredFlag|SyncPredFlag); + Yap_InitCPred("$c_table_statistics", 3, p_show_statistics_table, SafePredFlag|SyncPredFlag|HiddenPredFlag); + Yap_InitCPred("tabling_statistics", 1, p_show_statistics_tabling, SafePredFlag|SyncPredFlag); + Yap_InitCPred("global_trie_statistics", 1, p_show_statistics_global_trie, SafePredFlag|SyncPredFlag); #endif /* TABLING */ Yap_InitCPred("$c_yapor_threads", 1, p_yapor_threads, SafePredFlag|SyncPredFlag|HiddenPredFlag); #ifdef YAPOR @@ -147,10 +150,10 @@ void Yap_init_optyap_preds(void) { Yap_InitCPred("performance", 1, p_performance, SafePredFlag|SyncPredFlag); Yap_InitCPred("$c_parallel_new_answer", 1, p_parallel_new_answer, SafePredFlag|SyncPredFlag|HiddenPredFlag); Yap_InitCPred("$c_parallel_yes_answer", 0, p_parallel_yes_answer, SafePredFlag|SyncPredFlag|HiddenPredFlag); - Yap_InitCPred("or_statistics", 0, p_show_statistics_or, SafePredFlag|SyncPredFlag); + Yap_InitCPred("or_statistics", 1, p_show_statistics_or, SafePredFlag|SyncPredFlag); #endif /* YAPOR */ #if defined(YAPOR) && defined(TABLING) - Yap_InitCPred("opt_statistics", 0, p_show_statistics_opt, SafePredFlag|SyncPredFlag); + Yap_InitCPred("opt_statistics", 1, p_show_statistics_opt, SafePredFlag|SyncPredFlag); #endif /* YAPOR && TABLING */ Yap_InitCPred("$c_get_optyap_statistics", 3, p_get_optyap_statistics, SafePredFlag|SyncPredFlag|HiddenPredFlag); } @@ -158,7 +161,7 @@ void Yap_init_optyap_preds(void) { #ifdef YAPOR void finish_yapor(void) { - Yap_execution_time = current_time() - Yap_execution_time; + GLOBAL_execution_time = current_time() - GLOBAL_execution_time; show_answers(); return; } @@ -359,7 +362,7 @@ static Int p_abolish_all_tables( USES_REGS1 ) { sg_hash_ptr hash; sg_node_ptr sg_node; - tab_ent = Yap_root_tab_ent; + tab_ent = GLOBAL_root_tab_ent; while(tab_ent) { hash = TabEnt_hash_chain(tab_ent); TabEnt_hash_chain(tab_ent) = NULL; @@ -384,16 +387,29 @@ static Int p_abolish_all_tables( USES_REGS1 ) { } +static Int p_abolish_all_local_tables( USES_REGS1 ) { +#ifdef THREADS + +#else + p_abolish_all_tables(); +#endif /* THREADS */ + return (TRUE); +} + + static Int p_show_tabled_predicates( USES_REGS1 ) { + IOSTREAM *out; tab_ent_ptr tab_ent; - tab_ent = Yap_root_tab_ent; - fprintf(Yap_stdout, "Tabled predicates\n"); + if ((out = YAP_TermToStream(Deref(ARG1))) == NULL) + return (FALSE); + tab_ent = GLOBAL_root_tab_ent; + Sfprintf(out, "Tabled predicates\n"); if (tab_ent == NULL) - fprintf(Yap_stdout, " NONE\n"); + Sfprintf(out, " NONE\n"); else while(tab_ent) { - fprintf(Yap_stdout, " %s/%d\n", AtomName(TabEnt_atom(tab_ent)), TabEnt_arity(tab_ent)); + Sfprintf(out, " %s/%d\n", AtomName(TabEnt_atom(tab_ent)), TabEnt_arity(tab_ent)); tab_ent = TabEnt_next(tab_ent); } return (TRUE); @@ -401,95 +417,124 @@ static Int p_show_tabled_predicates( USES_REGS1 ) { static Int p_show_table( USES_REGS1 ) { + IOSTREAM *out; Term mod, t; tab_ent_ptr tab_ent; - mod = Deref(ARG1); - t = Deref(ARG2); + if ((out = YAP_TermToStream(Deref(ARG1))) == NULL) + return (FALSE); + mod = Deref(ARG2); + t = Deref(ARG3); if (IsAtomTerm(t)) tab_ent = RepPredProp(PredPropByAtom(AtomOfTerm(t), mod))->TableOfPred; else if (IsApplTerm(t)) tab_ent = RepPredProp(PredPropByFunc(FunctorOfTerm(t), mod))->TableOfPred; else return (FALSE); - show_table(tab_ent, SHOW_MODE_STRUCTURE); + show_table(tab_ent, SHOW_MODE_STRUCTURE, out); return (TRUE); } static Int p_show_all_tables( USES_REGS1 ) { + IOSTREAM *out; tab_ent_ptr tab_ent; - tab_ent = Yap_root_tab_ent; + if ((out = YAP_TermToStream(Deref(ARG1))) == NULL) + return (FALSE); + tab_ent = GLOBAL_root_tab_ent; while(tab_ent) { - show_table(tab_ent, SHOW_MODE_STRUCTURE); + show_table(tab_ent, SHOW_MODE_STRUCTURE, out); tab_ent = TabEnt_next(tab_ent); } return (TRUE); } +static Int p_show_all_local_tables( USES_REGS1 ) { +#ifdef THREADS + +#else + p_show_all_tables(); +#endif /* THREADS */ + return (TRUE); +} + + static Int p_show_global_trie( USES_REGS1 ) { - show_global_trie(SHOW_MODE_STRUCTURE); + IOSTREAM *out; + + if ((out = YAP_TermToStream(Deref(ARG1))) == NULL) + return (FALSE); + show_global_trie(SHOW_MODE_STRUCTURE, out); return (TRUE); } static Int p_show_statistics_table( USES_REGS1 ) { + IOSTREAM *out; Term mod, t; tab_ent_ptr tab_ent; - mod = Deref(ARG1); - t = Deref(ARG2); + if ((out = YAP_TermToStream(Deref(ARG1))) == NULL) + return (FALSE); + mod = Deref(ARG2); + t = Deref(ARG3); if (IsAtomTerm(t)) tab_ent = RepPredProp(PredPropByAtom(AtomOfTerm(t), mod))->TableOfPred; else if (IsApplTerm(t)) tab_ent = RepPredProp(PredPropByFunc(FunctorOfTerm(t), mod))->TableOfPred; else return (FALSE); - show_table(tab_ent, SHOW_MODE_STATISTICS); + show_table(tab_ent, SHOW_MODE_STATISTICS, out); return (TRUE); } static Int p_show_statistics_tabling( USES_REGS1 ) { + IOSTREAM *out; long total_bytes = 0, aux_bytes; + if ((out = YAP_TermToStream(Deref(ARG1))) == NULL) + return (FALSE); aux_bytes = 0; - fprintf(Yap_stdout, "Execution data structures\n"); - aux_bytes += show_statistics_table_entries(); - aux_bytes += show_statistics_subgoal_frames(); - aux_bytes += show_statistics_dependency_frames(); - fprintf(Yap_stdout, " Memory in use (I): %10ld bytes\n\n", aux_bytes); + Sfprintf(out, "Execution data structures\n"); + aux_bytes += show_statistics_table_entries(out); + aux_bytes += show_statistics_subgoal_frames(out); + aux_bytes += show_statistics_dependency_frames(out); + Sfprintf(out, " Memory in use (I): %10ld bytes\n\n", aux_bytes); total_bytes += aux_bytes; aux_bytes = 0; - fprintf(Yap_stdout, "Local trie data structures\n"); - aux_bytes += show_statistics_subgoal_trie_nodes(); - aux_bytes += show_statistics_answer_trie_nodes(); - aux_bytes += show_statistics_subgoal_trie_hashes(); - aux_bytes += show_statistics_answer_trie_hashes(); - fprintf(Yap_stdout, " Memory in use (II): %10ld bytes\n\n", aux_bytes); + Sfprintf(out, "Local trie data structures\n"); + aux_bytes += show_statistics_subgoal_trie_nodes(out); + aux_bytes += show_statistics_answer_trie_nodes(out); + aux_bytes += show_statistics_subgoal_trie_hashes(out); + aux_bytes += show_statistics_answer_trie_hashes(out); + Sfprintf(out, " Memory in use (II): %10ld bytes\n\n", aux_bytes); total_bytes += aux_bytes; aux_bytes = 0; - fprintf(Yap_stdout, "Global trie data structures\n"); - aux_bytes += show_statistics_global_trie_nodes(); - aux_bytes += show_statistics_global_trie_hashes(); - fprintf(Yap_stdout, " Memory in use (III): %10ld bytes\n\n", aux_bytes); + Sfprintf(out, "Global trie data structures\n"); + aux_bytes += show_statistics_global_trie_nodes(out); + aux_bytes += show_statistics_global_trie_hashes(out); + Sfprintf(out, " Memory in use (III): %10ld bytes\n\n", aux_bytes); total_bytes += aux_bytes; #ifdef USE_PAGES_MALLOC - fprintf(Yap_stdout, "Total memory in use (I+II+III): %10ld bytes (%ld pages in use)\n", - total_bytes, Pg_str_in_use(Yap_pages_void)); - fprintf(Yap_stdout, "Total memory allocated: %10ld bytes (%ld pages in total)\n", - Pg_pg_alloc(Yap_pages_void) * Yap_page_size, Pg_pg_alloc(Yap_pages_void)); + Sfprintf(out, "Total memory in use (I+II+III): %10ld bytes (%ld pages in use)\n", + total_bytes, Pg_str_in_use(GLOBAL_pages_void)); + Sfprintf(out, "Total memory allocated: %10ld bytes (%ld pages in total)\n", + Pg_pg_alloc(GLOBAL_pages_void) * Yap_page_size, Pg_pg_alloc(GLOBAL_pages_void)); #else - fprintf(Yap_stdout, "Total memory in use (I+II+III): %10ld bytes\n", total_bytes); + Sfprintf(out, "Total memory in use (I+II+III): %10ld bytes\n", total_bytes); #endif /* USE_PAGES_MALLOC */ - return (TRUE); } static Int p_show_statistics_global_trie( USES_REGS1 ) { - show_global_trie(SHOW_MODE_STATISTICS); + IOSTREAM *out; + + if ((out = YAP_TermToStream(Deref(ARG1))) == NULL) + return (FALSE); + show_global_trie(SHOW_MODE_STATISTICS, out); return (TRUE); } #endif /* TABLING */ @@ -501,7 +546,7 @@ static Int p_show_statistics_global_trie( USES_REGS1 ) { static Int p_yapor_threads( USES_REGS1 ) { #ifdef YAPOR_THREADS - return Yap_unify(MkIntegerTerm(Yap_number_workers),ARG1); + return Yap_unify(MkIntegerTerm(GLOBAL_number_workers),ARG1); #else return FALSE; #endif @@ -517,25 +562,25 @@ static Int p_worker( USES_REGS1 ) { static Int p_yapor_on( USES_REGS1 ) { - return (Yap_parallel_execution_mode); + return (GLOBAL_parallel_execution_mode); } static Int p_start_yapor( USES_REGS1 ) { #ifdef TIMESTAMP_CHECK - Yap_timestamp = 0; + GLOBAL_timestamp = 0; #endif /* TIMESTAMP_CHECK */ - Yap_answers = NO_ANSWER; - BITMAP_delete(Yap_bm_idle_workers, 0); - BITMAP_clear(Yap_bm_invisible_workers); - BITMAP_clear(Yap_bm_requestable_workers); + GLOBAL_answers = NO_ANSWER; + BITMAP_delete(GLOBAL_bm_idle_workers, 0); + BITMAP_clear(GLOBAL_bm_invisible_workers); + BITMAP_clear(GLOBAL_bm_requestable_workers); #ifdef TABLING_INNER_CUTS - BITMAP_clear(Yap_bm_pruning_workers); + BITMAP_clear(GLOBAL_bm_pruning_workers); #endif /* TABLING_INNER_CUTS */ make_root_choice_point(); - Yap_performance_mode &= ~PERFORMANCE_IN_EXECUTION; - Yap_execution_time = current_time(); - BITMAP_clear(Yap_bm_finished_workers); + GLOBAL_performance_mode &= ~PERFORMANCE_IN_EXECUTION; + GLOBAL_execution_time = current_time(); + BITMAP_clear(GLOBAL_bm_finished_workers); PUT_IN_EXECUTING(worker_id); return (TRUE); } @@ -574,7 +619,7 @@ static Int p_execution_mode( USES_REGS1 ) { t = Deref(ARG1); if (IsVarTerm(t)) { Term ta; - if (Yap_parallel_execution_mode) + if (GLOBAL_parallel_execution_mode) ta = MkAtomTerm(Yap_LookupAtom("parallel")); else ta = MkAtomTerm(Yap_LookupAtom("sequential")); @@ -585,11 +630,11 @@ static Int p_execution_mode( USES_REGS1 ) { char *s; s = RepAtom(AtomOfTerm(t))->StrOfAE; if (strcmp(s,"parallel") == 0) { - Yap_parallel_execution_mode = TRUE; + GLOBAL_parallel_execution_mode = TRUE; return(TRUE); } if (strcmp(s,"sequential") == 0) { - Yap_parallel_execution_mode = FALSE; + GLOBAL_parallel_execution_mode = FALSE; return(TRUE); } } @@ -602,11 +647,11 @@ static Int p_performance( USES_REGS1 ) { realtime one_worker_execution_time = 0; int i; - Yap_performance_mode |= PERFORMANCE_IN_EXECUTION; + GLOBAL_performance_mode |= PERFORMANCE_IN_EXECUTION; t = Deref(ARG1); if (IsVarTerm(t)) { Term ta; - if (Yap_performance_mode & PERFORMANCE_ON) { + if (GLOBAL_performance_mode & PERFORMANCE_ON) { ta = MkAtomTerm(Yap_LookupAtom("on")); } else { ta = MkAtomTerm(Yap_LookupAtom("off")); @@ -618,16 +663,16 @@ static Int p_performance( USES_REGS1 ) { char *s; s = RepAtom(AtomOfTerm(t))->StrOfAE; if (strcmp(s, "on") == 0) { - Yap_performance_mode |= PERFORMANCE_ON; + GLOBAL_performance_mode |= PERFORMANCE_ON; return(TRUE); } if (strcmp(s,"off") == 0) { - Yap_performance_mode &= ~PERFORMANCE_ON; + GLOBAL_performance_mode &= ~PERFORMANCE_ON; return(TRUE); } if (strcmp(s,"clear") == 0) { - Yap_number_goals = 0; - Yap_best_times(0) = 0; + GLOBAL_number_goals = 0; + GLOBAL_best_times(0) = 0; return(TRUE); } } @@ -638,33 +683,34 @@ static Int p_performance( USES_REGS1 ) { else return(FALSE); - if (Yap_number_goals) { - fprintf(Yap_stdout, "[\n Best execution times:\n"); - for (i = 1; i <= Yap_number_goals; i++) { - fprintf(Yap_stdout, " %d. time: %f seconds", i, Yap_best_times(i)); + if (GLOBAL_number_goals) { + Sfprintf(Soutput, "[\n Best execution times:\n"); + for (i = 1; i <= GLOBAL_number_goals; i++) { + Sfprintf(Soutput, " %d. time: %f seconds", i, GLOBAL_best_times(i)); if (one_worker_execution_time != 0) - fprintf(Yap_stdout, " --> speedup %f (%6.2f %% )\n", - one_worker_execution_time / Yap_best_times(i), - one_worker_execution_time / Yap_best_times(i) / Yap_number_workers* 100 ); - else fprintf(Yap_stdout, "\n"); + Sfprintf(Soutput, " --> speedup %f (%6.2f %% )\n", + one_worker_execution_time / GLOBAL_best_times(i), + one_worker_execution_time / GLOBAL_best_times(i) / GLOBAL_number_workers* 100 ); + else Sfprintf(Soutput, "\n"); } - fprintf(Yap_stdout, " Average : %f seconds", - Yap_best_times(0) / Yap_number_goals); + Sfprintf(Soutput, " Average : %f seconds", + GLOBAL_best_times(0) / GLOBAL_number_goals); if (one_worker_execution_time != 0) - fprintf(Yap_stdout, " --> speedup %f (%6.2f %% )", - one_worker_execution_time * Yap_number_goals / Yap_best_times(0), - one_worker_execution_time * Yap_number_goals / Yap_best_times(0) / Yap_number_workers* 100 ); + Sfprintf(Soutput, " --> speedup %f (%6.2f %% )", + one_worker_execution_time * GLOBAL_number_goals / GLOBAL_best_times(0), + one_worker_execution_time * GLOBAL_number_goals / GLOBAL_best_times(0) / GLOBAL_number_workers* 100 ); - if (Yap_number_goals >= 3) { - fprintf(Yap_stdout, "\n Average (best three): %f seconds", - (Yap_best_times(1) + Yap_best_times(2) + Yap_best_times(3)) / 3); + if (GLOBAL_number_goals >= 3) { + Sfprintf(Soutput, "\n Average (best three): %f seconds", + (GLOBAL_best_times(1) + GLOBAL_best_times(2) + GLOBAL_best_times(3)) / 3); if (one_worker_execution_time != 0) - fprintf(Yap_stdout, " --> speedup %f (%6.2f %% ) ]\n\n", - one_worker_execution_time * 3 / (Yap_best_times(1) + Yap_best_times(2) + Yap_best_times(3)), - one_worker_execution_time * 3 / (Yap_best_times(1) + Yap_best_times(2) + Yap_best_times(3)) / Yap_number_workers* 100 ); - else fprintf(Yap_stdout, "\n]\n\n"); - } else fprintf(Yap_stdout, "\n]\n\n"); + Sfprintf(Soutput, " --> speedup %f (%6.2f %% ) ]\n\n", + one_worker_execution_time * 3 / (GLOBAL_best_times(1) + GLOBAL_best_times(2) + GLOBAL_best_times(3)), + one_worker_execution_time * 3 / (GLOBAL_best_times(1) + GLOBAL_best_times(2) + GLOBAL_best_times(3)) / GLOBAL_number_workers* 100 ); + else Sfprintf(Soutput, "\n]\n\n"); + } else Sfprintf(Soutput, "\n]\n\n"); + Sflush(Soutput); return (TRUE); } return (FALSE); @@ -693,34 +739,36 @@ static Int p_parallel_new_answer( USES_REGS1 ) { static Int p_parallel_yes_answer( USES_REGS1 ) { - Yap_answers = YES_ANSWER; + GLOBAL_answers = YES_ANSWER; return (TRUE); } static Int p_show_statistics_or( USES_REGS1 ) { + IOSTREAM *out; long total_bytes = 0, aux_bytes; + if ((out = YAP_TermToStream(Deref(ARG1))) == NULL) + return (FALSE); aux_bytes = 0; - fprintf(Yap_stdout, "Execution data structures\n"); - aux_bytes += show_statistics_or_frames(); - fprintf(Yap_stdout, " Memory in use (I): %10ld bytes\n\n", aux_bytes); + Sfprintf(out, "Execution data structures\n"); + aux_bytes += show_statistics_or_frames(out); + Sfprintf(out, " Memory in use (I): %10ld bytes\n\n", aux_bytes); total_bytes += aux_bytes; aux_bytes = 0; - fprintf(Yap_stdout, "Cut support data structures\n"); - aux_bytes += show_statistics_query_goal_solution_frames(); - aux_bytes += show_statistics_query_goal_answer_frames(); - fprintf(Yap_stdout, " Memory in use (II): %10ld bytes\n\n", aux_bytes); + Sfprintf(out, "Cut support data structures\n"); + aux_bytes += show_statistics_query_goal_solution_frames(out); + aux_bytes += show_statistics_query_goal_answer_frames(out); + Sfprintf(out, " Memory in use (II): %10ld bytes\n\n", aux_bytes); total_bytes += aux_bytes; #ifdef USE_PAGES_MALLOC - fprintf(Yap_stdout, "Total memory in use (I+II+III): %10ld bytes (%ld pages in use)\n", - total_bytes, Pg_str_in_use(Yap_pages_void)); - fprintf(Yap_stdout, "Total memory allocated: %10ld bytes (%ld pages in total)\n", - Pg_pg_alloc(Yap_pages_void) * Yap_page_size, Pg_pg_alloc(Yap_pages_void)); + Sfprintf(out, "Total memory in use (I+II): %10ld bytes (%ld pages in use)\n", + total_bytes, Pg_str_in_use(GLOBAL_pages_void)); + Sfprintf(out, "Total memory allocated: %10ld bytes (%ld pages in total)\n", + Pg_pg_alloc(GLOBAL_pages_void) * Yap_page_size, Pg_pg_alloc(GLOBAL_pages_void)); #else - fprintf(Yap_stdout, "Total memory in use (I+II+III): %10ld bytes\n", total_bytes); + Sfprintf(out, "Total memory in use (I+II): %10ld bytes\n", total_bytes); #endif /* USE_PAGES_MALLOC */ - return (TRUE); } #endif /* YAPOR */ @@ -733,50 +781,52 @@ static Int p_show_statistics_or( USES_REGS1 ) { #if defined(YAPOR) && defined(TABLING) static Int p_show_statistics_opt( USES_REGS1 ) { + IOSTREAM *out; long total_bytes = 0, aux_bytes; + if ((out = YAP_TermToStream(Deref(ARG1))) == NULL) + return (FALSE); aux_bytes = 0; - fprintf(Yap_stdout, "Execution data structures\n"); - aux_bytes += show_statistics_table_entries(); - aux_bytes += show_statistics_subgoal_frames(); - aux_bytes += show_statistics_dependency_frames(); - aux_bytes += show_statistics_or_frames(); - aux_bytes += show_statistics_suspension_frames(); - fprintf(Yap_stdout, " Memory in use (I): %10ld bytes\n\n", aux_bytes); + Sfprintf(out, "Execution data structures\n"); + aux_bytes += show_statistics_table_entries(out); + aux_bytes += show_statistics_subgoal_frames(out); + aux_bytes += show_statistics_dependency_frames(out); + aux_bytes += show_statistics_or_frames(out); + aux_bytes += show_statistics_suspension_frames(out); + Sfprintf(out, " Memory in use (I): %10ld bytes\n\n", aux_bytes); total_bytes += aux_bytes; aux_bytes = 0; - fprintf(Yap_stdout, "Local trie data structures\n"); - aux_bytes += show_statistics_subgoal_trie_nodes(); - aux_bytes += show_statistics_answer_trie_nodes(); - aux_bytes += show_statistics_subgoal_trie_hashes(); - aux_bytes += show_statistics_answer_trie_hashes(); - fprintf(Yap_stdout, " Memory in use (II): %10ld bytes\n\n", aux_bytes); + Sfprintf(out, "Local trie data structures\n"); + aux_bytes += show_statistics_subgoal_trie_nodes(out); + aux_bytes += show_statistics_answer_trie_nodes(out); + aux_bytes += show_statistics_subgoal_trie_hashes(out); + aux_bytes += show_statistics_answer_trie_hashes(out); + Sfprintf(out, " Memory in use (II): %10ld bytes\n\n", aux_bytes); total_bytes += aux_bytes; aux_bytes = 0; - fprintf(Yap_stdout, "Global trie data structures\n"); - aux_bytes += show_statistics_global_trie_nodes(); - aux_bytes += show_statistics_global_trie_hashes(); - fprintf(Yap_stdout, " Memory in use (III): %10ld bytes\n\n", aux_bytes); + Sfprintf(out, "Global trie data structures\n"); + aux_bytes += show_statistics_global_trie_nodes(out); + aux_bytes += show_statistics_global_trie_hashes(out); + Sfprintf(out, " Memory in use (III): %10ld bytes\n\n", aux_bytes); total_bytes += aux_bytes; aux_bytes = 0; - fprintf(Yap_stdout, "Cut support data structures\n"); - aux_bytes += show_statistics_query_goal_solution_frames(); - aux_bytes += show_statistics_query_goal_answer_frames(); + Sfprintf(out, "Cut support data structures\n"); + aux_bytes += show_statistics_query_goal_solution_frames(out); + aux_bytes += show_statistics_query_goal_answer_frames(out); #ifdef TABLING_INNER_CUTS - aux_bytes += show_statistics_table_subgoal_solution_frames(); - aux_bytes += show_statistics_table_subgoal_answer_frames(); + aux_bytes += show_statistics_table_subgoal_solution_frames(out); + aux_bytes += show_statistics_table_subgoal_answer_frames(out); #endif /* TABLING_INNER_CUTS */ - fprintf(Yap_stdout, " Memory in use (IV): %10ld bytes\n\n", aux_bytes); + Sfprintf(out, " Memory in use (IV): %10ld bytes\n\n", aux_bytes); total_bytes += aux_bytes; #ifdef USE_PAGES_MALLOC - fprintf(Yap_stdout, "Total memory in use (I+II+III+IV): %10ld bytes (%ld pages in use)\n", - total_bytes, Pg_str_in_use(Yap_pages_void)); - fprintf(Yap_stdout, "Total memory allocated: %10ld bytes (%ld pages in total)\n", - Pg_pg_alloc(Yap_pages_void) * Yap_page_size, Pg_pg_alloc(Yap_pages_void)); + Sfprintf(out, "Total memory in use (I+II+III+IV): %10ld bytes (%ld pages in use)\n", + total_bytes, Pg_str_in_use(GLOBAL_pages_void)); + Sfprintf(out, "Total memory allocated: %10ld bytes (%ld pages in total)\n", + Pg_pg_alloc(GLOBAL_pages_void) * Yap_page_size, Pg_pg_alloc(GLOBAL_pages_void)); #else - fprintf(Yap_stdout, "Total memory in use (I+II+III+IV): %10ld bytes\n", total_bytes); + Sfprintf(out, "Total memory in use (I+II+III+IV): %10ld bytes\n", total_bytes); #endif /* USE_PAGES_MALLOC */ - return (TRUE); } #endif /* YAPOR && TABLING */ @@ -790,99 +840,99 @@ static Int p_get_optyap_statistics( USES_REGS1 ) { if (value == 0) { /* total_memory */ bytes = 0; #ifdef TABLING - bytes += Pg_str_in_use(Yap_pages_tab_ent) * sizeof(struct table_entry); - bytes += Pg_str_in_use(Yap_pages_sg_fr) * sizeof(struct subgoal_frame); - bytes += Pg_str_in_use(Yap_pages_dep_fr) * sizeof(struct dependency_frame); - bytes += Pg_str_in_use(Yap_pages_sg_node) * sizeof(struct subgoal_trie_node); - bytes += Pg_str_in_use(Yap_pages_ans_node) * sizeof(struct answer_trie_node); - bytes += Pg_str_in_use(Yap_pages_sg_hash) * sizeof(struct subgoal_trie_hash); - bytes += Pg_str_in_use(Yap_pages_ans_hash) * sizeof(struct answer_trie_hash); - bytes += Pg_str_in_use(Yap_pages_gt_node) * sizeof(struct global_trie_node); - bytes += Pg_str_in_use(Yap_pages_gt_hash) * sizeof(struct global_trie_hash); + bytes += Pg_str_in_use(GLOBAL_pages_tab_ent) * sizeof(struct table_entry); + bytes += Pg_str_in_use(GLOBAL_pages_sg_fr) * sizeof(struct subgoal_frame); + bytes += Pg_str_in_use(GLOBAL_pages_dep_fr) * sizeof(struct dependency_frame); + bytes += Pg_str_in_use(GLOBAL_pages_sg_node) * sizeof(struct subgoal_trie_node); + bytes += Pg_str_in_use(GLOBAL_pages_ans_node) * sizeof(struct answer_trie_node); + bytes += Pg_str_in_use(GLOBAL_pages_sg_hash) * sizeof(struct subgoal_trie_hash); + bytes += Pg_str_in_use(GLOBAL_pages_ans_hash) * sizeof(struct answer_trie_hash); + bytes += Pg_str_in_use(GLOBAL_pages_gt_node) * sizeof(struct global_trie_node); + bytes += Pg_str_in_use(GLOBAL_pages_gt_hash) * sizeof(struct global_trie_hash); #endif /* TABLING */ #ifdef YAPOR - bytes += Pg_str_in_use(Yap_pages_or_fr ) * sizeof(struct or_frame); - bytes += Pg_str_in_use(Yap_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame); - bytes += Pg_str_in_use(Yap_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame); + bytes += Pg_str_in_use(GLOBAL_pages_or_fr ) * sizeof(struct or_frame); + bytes += Pg_str_in_use(GLOBAL_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame); + bytes += Pg_str_in_use(GLOBAL_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame); #endif /* YAPOR */ #if defined(YAPOR) && defined(TABLING) - bytes += Pg_str_in_use(Yap_pages_susp_fr) * sizeof(struct suspension_frame); + bytes += Pg_str_in_use(GLOBAL_pages_susp_fr) * sizeof(struct suspension_frame); #ifdef TABLING_INNER_CUTS - bytes += Pg_str_in_use(Yap_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame); - bytes += Pg_str_in_use(Yap_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame); + bytes += Pg_str_in_use(GLOBAL_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame); + bytes += Pg_str_in_use(GLOBAL_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame); #endif /* TABLING_INNER_CUTS */ #endif /* YAPOR && TABLING */ #ifdef USE_PAGES_MALLOC - structs = Pg_pg_alloc(Yap_pages_void) * Yap_page_size; + structs = Pg_pg_alloc(GLOBAL_pages_void) * Yap_page_size; #else structs = bytes; #endif /* USE_PAGES_MALLOC */ } #ifdef TABLING if (value == 1) { /* table_entries */ - bytes = Pg_str_in_use(Yap_pages_tab_ent) * sizeof(struct table_entry); - structs = Pg_str_in_use(Yap_pages_tab_ent); + bytes = Pg_str_in_use(GLOBAL_pages_tab_ent) * sizeof(struct table_entry); + structs = Pg_str_in_use(GLOBAL_pages_tab_ent); } if (value == 2) { /* subgoal_frames */ - bytes = Pg_str_in_use(Yap_pages_sg_fr) * sizeof(struct subgoal_frame); - structs = Pg_str_in_use(Yap_pages_sg_fr); + bytes = Pg_str_in_use(GLOBAL_pages_sg_fr) * sizeof(struct subgoal_frame); + structs = Pg_str_in_use(GLOBAL_pages_sg_fr); } if (value == 3) { /* dependency_frames */ - bytes = Pg_str_in_use(Yap_pages_dep_fr) * sizeof(struct dependency_frame); - structs = Pg_str_in_use(Yap_pages_dep_fr); + bytes = Pg_str_in_use(GLOBAL_pages_dep_fr) * sizeof(struct dependency_frame); + structs = Pg_str_in_use(GLOBAL_pages_dep_fr); } if (value == 6) { /* subgoal_trie_nodes */ - bytes = Pg_str_in_use(Yap_pages_sg_node) * sizeof(struct subgoal_trie_node); - structs = Pg_str_in_use(Yap_pages_sg_node); + bytes = Pg_str_in_use(GLOBAL_pages_sg_node) * sizeof(struct subgoal_trie_node); + structs = Pg_str_in_use(GLOBAL_pages_sg_node); } if (value == 7) { /* answer_trie_nodes */ - bytes = Pg_str_in_use(Yap_pages_ans_node) * sizeof(struct answer_trie_node); - structs = Pg_str_in_use(Yap_pages_ans_node); + bytes = Pg_str_in_use(GLOBAL_pages_ans_node) * sizeof(struct answer_trie_node); + structs = Pg_str_in_use(GLOBAL_pages_ans_node); } if (value == 8) { /* subgoal_trie_hashes */ - bytes = Pg_str_in_use(Yap_pages_sg_hash) * sizeof(struct subgoal_trie_hash); - structs = Pg_str_in_use(Yap_pages_sg_hash); + bytes = Pg_str_in_use(GLOBAL_pages_sg_hash) * sizeof(struct subgoal_trie_hash); + structs = Pg_str_in_use(GLOBAL_pages_sg_hash); } if (value == 9) { /* answer_trie_hashes */ - bytes = Pg_str_in_use(Yap_pages_ans_hash) * sizeof(struct answer_trie_hash); - structs = Pg_str_in_use(Yap_pages_ans_hash); + bytes = Pg_str_in_use(GLOBAL_pages_ans_hash) * sizeof(struct answer_trie_hash); + structs = Pg_str_in_use(GLOBAL_pages_ans_hash); } if (value == 10) { /* global_trie_nodes */ - bytes = Pg_str_in_use(Yap_pages_gt_node) * sizeof(struct global_trie_node); - structs = Pg_str_in_use(Yap_pages_gt_node); + bytes = Pg_str_in_use(GLOBAL_pages_gt_node) * sizeof(struct global_trie_node); + structs = Pg_str_in_use(GLOBAL_pages_gt_node); } if (value == 11) { /* global_trie_hashes */ - bytes = Pg_str_in_use(Yap_pages_gt_hash) * sizeof(struct global_trie_hash); - structs = Pg_str_in_use(Yap_pages_gt_hash); + bytes = Pg_str_in_use(GLOBAL_pages_gt_hash) * sizeof(struct global_trie_hash); + structs = Pg_str_in_use(GLOBAL_pages_gt_hash); } #endif /* TABLING */ #ifdef YAPOR if (value == 4) { /* or_frames */ - bytes = Pg_str_in_use(Yap_pages_or_fr ) * sizeof(struct or_frame); - structs = Pg_str_in_use(Yap_pages_or_fr ); + bytes = Pg_str_in_use(GLOBAL_pages_or_fr ) * sizeof(struct or_frame); + structs = Pg_str_in_use(GLOBAL_pages_or_fr ); } if (value == 12) { /* query_goal_solution_frames */ - bytes = Pg_str_in_use(Yap_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame); - structs = Pg_str_in_use(Yap_pages_qg_sol_fr ); + bytes = Pg_str_in_use(GLOBAL_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame); + structs = Pg_str_in_use(GLOBAL_pages_qg_sol_fr ); } if (value == 13) { /* query_goal_answer_frames */ - bytes = Pg_str_in_use(Yap_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame); - structs = Pg_str_in_use(Yap_pages_qg_ans_fr); + bytes = Pg_str_in_use(GLOBAL_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame); + structs = Pg_str_in_use(GLOBAL_pages_qg_ans_fr); } #endif /* YAPOR */ #if defined(YAPOR) && defined(TABLING) if (value == 5) { /* suspension_frames */ - bytes = Pg_str_in_use(Yap_pages_susp_fr) * sizeof(struct suspension_frame); - structs = Pg_str_in_use(Yap_pages_susp_fr); + bytes = Pg_str_in_use(GLOBAL_pages_susp_fr) * sizeof(struct suspension_frame); + structs = Pg_str_in_use(GLOBAL_pages_susp_fr); } #ifdef TABLING_INNER_CUTS if (value == 14) { /* table_subgoal_solution_frames */ - bytes = Pg_str_in_use(Yap_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame); - structs = Pg_str_in_use(Yap_pages_tg_sol_fr); + bytes = Pg_str_in_use(GLOBAL_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame); + structs = Pg_str_in_use(GLOBAL_pages_tg_sol_fr); } if (value == 15) { /* table_subgoal_answer_frames */ - bytes = Pg_str_in_use(Yap_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame); - structs = Pg_str_in_use(Yap_pages_tg_ans_fr); + bytes = Pg_str_in_use(GLOBAL_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame); + structs = Pg_str_in_use(GLOBAL_pages_tg_ans_fr); } #endif /* TABLING_INNER_CUTS */ #endif /* YAPOR && TABLING */ @@ -937,43 +987,44 @@ static inline void show_answers(void) { aux_answer2 = aux_answer1; aux_answer1 = AnsFr_next(aux_answer1); FREE_QG_ANSWER_FRAME(aux_answer2); - Yap_answers++; + GLOBAL_answers++; } FREE_QG_SOLUTION_FRAME(OrFr_qg_solutions(LOCAL_top_or_fr)); OrFr_qg_solutions(LOCAL_top_or_fr) = NULL; } - switch(Yap_answers) { + switch(GLOBAL_answers) { case YES_ANSWER: - fprintf(Yap_stderr, "[ yes"); + Sfprintf(Serror, "[ yes"); break; case NO_ANSWER: - fprintf(Yap_stderr, "[ no"); + Sfprintf(Serror, "[ no"); break; case 1: - fprintf(Yap_stderr, "[ 1 answer found"); + Sfprintf(Serror, "[ 1 answer found"); break; default: - fprintf(Yap_stderr, "[ %d answers found", Yap_answers); + Sfprintf(Serror, "[ %d answers found", GLOBAL_answers); break; } - fprintf(Yap_stderr, " (in %f seconds) ]\n\n", Yap_execution_time); + Sfprintf(Serror, " (in %f seconds) ]\n\n", GLOBAL_execution_time); + Sflush(Serror); - if (Yap_performance_mode == PERFORMANCE_ON) { - for (i = Yap_number_goals; i > 0; i--) { - if (Yap_best_times(i) > Yap_execution_time) { + if (GLOBAL_performance_mode == PERFORMANCE_ON) { + for (i = GLOBAL_number_goals; i > 0; i--) { + if (GLOBAL_best_times(i) > GLOBAL_execution_time) { if (i + 1 < MAX_BEST_TIMES) - Yap_best_times(i + 1) = Yap_best_times(i); + GLOBAL_best_times(i + 1) = GLOBAL_best_times(i); else { - Yap_best_times(0) -= Yap_best_times(i); + GLOBAL_best_times(0) -= GLOBAL_best_times(i); } } else break; } if (i + 1 < MAX_BEST_TIMES) { - Yap_best_times(0) += Yap_execution_time; - Yap_best_times(i + 1) = Yap_execution_time; - if (Yap_number_goals + 1 < MAX_BEST_TIMES) - Yap_number_goals++; + GLOBAL_best_times(0) += GLOBAL_execution_time; + GLOBAL_best_times(i + 1) = GLOBAL_execution_time; + if (GLOBAL_number_goals + 1 < MAX_BEST_TIMES) + GLOBAL_number_goals++; } } @@ -1016,21 +1067,22 @@ static inline void answer_to_stdout(char *answer) { else break; } output[length_output] = 0; - fprintf(Yap_stderr, " %s\n", output); + Sfprintf(Serror, " %s\n", output); + Sflush(Serror); return; } #endif /* YAPOR */ #ifdef TABLING -static inline long show_statistics_table_entries(void) { +static inline long show_statistics_table_entries(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_TABLING pg_hd_ptr pg_hd; tab_ent_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_tab_ent); + pg_hd = Pg_free_pg(GLOBAL_pages_tab_ent); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1039,26 +1091,26 @@ static inline long show_statistics_table_entries(void) { } pg_hd = PgHd_next(pg_hd); } - TABLING_ERROR_CHECKING(statistics_table_entries, Pg_str_free(Yap_pages_tab_ent) != cont); + TABLING_ERROR_CHECKING(statistics_table_entries, Pg_str_free(GLOBAL_pages_tab_ent) != cont); #endif /* DEBUG_TABLING */ - fprintf(Yap_stdout, " Table entries: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_tab_ent) * sizeof(struct table_entry), Pg_pg_alloc(Yap_pages_tab_ent), Pg_str_in_use(Yap_pages_tab_ent)); + Sfprintf(out, " Table entries: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_tab_ent) * sizeof(struct table_entry), Pg_pg_alloc(GLOBAL_pages_tab_ent), Pg_str_in_use(GLOBAL_pages_tab_ent)); #else - fprintf(Yap_stdout, " Table entries: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_tab_ent) * sizeof(struct table_entry), Pg_str_in_use(Yap_pages_tab_ent)); + Sfprintf(out, " Table entries: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_tab_ent) * sizeof(struct table_entry), Pg_str_in_use(GLOBAL_pages_tab_ent)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_tab_ent) * sizeof(struct table_entry); + return Pg_str_in_use(GLOBAL_pages_tab_ent) * sizeof(struct table_entry); } -static inline long show_statistics_subgoal_frames(void) { +static inline long show_statistics_subgoal_frames(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_TABLING pg_hd_ptr pg_hd; sg_fr_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_sg_fr); + pg_hd = Pg_free_pg(GLOBAL_pages_sg_fr); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1067,26 +1119,26 @@ static inline long show_statistics_subgoal_frames(void) { } pg_hd = PgHd_next(pg_hd); } - TABLING_ERROR_CHECKING(statistics_subgoal_frames, Pg_str_free(Yap_pages_sg_fr) != cont); + TABLING_ERROR_CHECKING(statistics_subgoal_frames, Pg_str_free(GLOBAL_pages_sg_fr) != cont); #endif /* DEBUG_TABLING */ - fprintf(Yap_stdout, " Subgoal frames: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_sg_fr) * sizeof(struct subgoal_frame), Pg_pg_alloc(Yap_pages_sg_fr), Pg_str_in_use(Yap_pages_sg_fr)); + Sfprintf(out, " Subgoal frames: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_sg_fr) * sizeof(struct subgoal_frame), Pg_pg_alloc(GLOBAL_pages_sg_fr), Pg_str_in_use(GLOBAL_pages_sg_fr)); #else - fprintf(Yap_stdout, " Subgoal frames: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_sg_fr) * sizeof(struct subgoal_frame), Pg_str_in_use(Yap_pages_sg_fr)); + Sfprintf(out, " Subgoal frames: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_sg_fr) * sizeof(struct subgoal_frame), Pg_str_in_use(GLOBAL_pages_sg_fr)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_sg_fr) * sizeof(struct subgoal_frame); + return Pg_str_in_use(GLOBAL_pages_sg_fr) * sizeof(struct subgoal_frame); } -static inline long show_statistics_dependency_frames(void) { +static inline long show_statistics_dependency_frames(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_TABLING pg_hd_ptr pg_hd; dep_fr_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_dep_fr); + pg_hd = Pg_free_pg(GLOBAL_pages_dep_fr); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1095,26 +1147,26 @@ static inline long show_statistics_dependency_frames(void) { } pg_hd = PgHd_next(pg_hd); } - TABLING_ERROR_CHECKING(statistics_dependency_frames, Pg_str_free(Yap_pages_dep_fr) != cont); + TABLING_ERROR_CHECKING(statistics_dependency_frames, Pg_str_free(GLOBAL_pages_dep_fr) != cont); #endif /* DEBUG_TABLING */ - fprintf(Yap_stdout, " Dependency frames: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_dep_fr) * sizeof(struct dependency_frame), Pg_pg_alloc(Yap_pages_dep_fr), Pg_str_in_use(Yap_pages_dep_fr)); + Sfprintf(out, " Dependency frames: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_dep_fr) * sizeof(struct dependency_frame), Pg_pg_alloc(GLOBAL_pages_dep_fr), Pg_str_in_use(GLOBAL_pages_dep_fr)); #else - fprintf(Yap_stdout, " Dependency frames: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_dep_fr) * sizeof(struct dependency_frame), Pg_str_in_use(Yap_pages_dep_fr)); + Sfprintf(out, " Dependency frames: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_dep_fr) * sizeof(struct dependency_frame), Pg_str_in_use(GLOBAL_pages_dep_fr)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_dep_fr) * sizeof(struct dependency_frame); + return Pg_str_in_use(GLOBAL_pages_dep_fr) * sizeof(struct dependency_frame); } -static inline long show_statistics_subgoal_trie_nodes(void) { +static inline long show_statistics_subgoal_trie_nodes(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_TABLING pg_hd_ptr pg_hd; sg_node_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_sg_node); + pg_hd = Pg_free_pg(GLOBAL_pages_sg_node); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1123,26 +1175,26 @@ static inline long show_statistics_subgoal_trie_nodes(void) { } pg_hd = PgHd_next(pg_hd); } - TABLING_ERROR_CHECKING(statistics_subgoal_trie_nodes, Pg_str_free(Yap_pages_sg_node) != cont); + TABLING_ERROR_CHECKING(statistics_subgoal_trie_nodes, Pg_str_free(GLOBAL_pages_sg_node) != cont); #endif /* DEBUG_TABLING */ - fprintf(Yap_stdout, " Subgoal trie nodes: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_sg_node) * sizeof(struct subgoal_trie_node), Pg_pg_alloc(Yap_pages_sg_node), Pg_str_in_use(Yap_pages_sg_node)); + Sfprintf(out, " Subgoal trie nodes: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_sg_node) * sizeof(struct subgoal_trie_node), Pg_pg_alloc(GLOBAL_pages_sg_node), Pg_str_in_use(GLOBAL_pages_sg_node)); #else - fprintf(Yap_stdout, " Subgoal trie nodes: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_sg_node) * sizeof(struct subgoal_trie_node), Pg_str_in_use(Yap_pages_sg_node)); + Sfprintf(out, " Subgoal trie nodes: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_sg_node) * sizeof(struct subgoal_trie_node), Pg_str_in_use(GLOBAL_pages_sg_node)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_sg_node) * sizeof(struct subgoal_trie_node); + return Pg_str_in_use(GLOBAL_pages_sg_node) * sizeof(struct subgoal_trie_node); } -static inline long show_statistics_answer_trie_nodes(void) { +static inline long show_statistics_answer_trie_nodes(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_TABLING pg_hd_ptr pg_hd; ans_node_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_ans_node); + pg_hd = Pg_free_pg(GLOBAL_pages_ans_node); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1151,26 +1203,26 @@ static inline long show_statistics_answer_trie_nodes(void) { } pg_hd = PgHd_next(pg_hd); } - TABLING_ERROR_CHECKING(statistics_answer_trie_nodes, Pg_str_free(Yap_pages_ans_node) != cont); + TABLING_ERROR_CHECKING(statistics_answer_trie_nodes, Pg_str_free(GLOBAL_pages_ans_node) != cont); #endif /* DEBUG_TABLING */ - fprintf(Yap_stdout, " Answer trie nodes: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_ans_node) * sizeof(struct answer_trie_node), Pg_pg_alloc(Yap_pages_ans_node), Pg_str_in_use(Yap_pages_ans_node)); + Sfprintf(out, " Answer trie nodes: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_ans_node) * sizeof(struct answer_trie_node), Pg_pg_alloc(GLOBAL_pages_ans_node), Pg_str_in_use(GLOBAL_pages_ans_node)); #else - fprintf(Yap_stdout, " Answer trie nodes: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_ans_node) * sizeof(struct answer_trie_node), Pg_str_in_use(Yap_pages_ans_node)); + Sfprintf(out, " Answer trie nodes: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_ans_node) * sizeof(struct answer_trie_node), Pg_str_in_use(GLOBAL_pages_ans_node)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_ans_node) * sizeof(struct answer_trie_node); + return Pg_str_in_use(GLOBAL_pages_ans_node) * sizeof(struct answer_trie_node); } -static inline long show_statistics_subgoal_trie_hashes(void) { +static inline long show_statistics_subgoal_trie_hashes(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_TABLING pg_hd_ptr pg_hd; sg_hash_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_sg_hash); + pg_hd = Pg_free_pg(GLOBAL_pages_sg_hash); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1179,26 +1231,26 @@ static inline long show_statistics_subgoal_trie_hashes(void) { } pg_hd = PgHd_next(pg_hd); } - TABLING_ERROR_CHECKING(statistics_subgoal_trie_hashes, Pg_str_free(Yap_pages_sg_hash) != cont); + TABLING_ERROR_CHECKING(statistics_subgoal_trie_hashes, Pg_str_free(GLOBAL_pages_sg_hash) != cont); #endif /* DEBUG_TABLING */ - fprintf(Yap_stdout, " Subgoal trie hashes: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_sg_hash) * sizeof(struct subgoal_trie_hash), Pg_pg_alloc(Yap_pages_sg_hash), Pg_str_in_use(Yap_pages_sg_hash)); + Sfprintf(out, " Subgoal trie hashes: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_sg_hash) * sizeof(struct subgoal_trie_hash), Pg_pg_alloc(GLOBAL_pages_sg_hash), Pg_str_in_use(GLOBAL_pages_sg_hash)); #else - fprintf(Yap_stdout, " Subgoal trie hashes: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_sg_hash) * sizeof(struct subgoal_trie_hash), Pg_str_in_use(Yap_pages_sg_hash)); + Sfprintf(out, " Subgoal trie hashes: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_sg_hash) * sizeof(struct subgoal_trie_hash), Pg_str_in_use(GLOBAL_pages_sg_hash)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_sg_hash) * sizeof(struct subgoal_trie_hash); + return Pg_str_in_use(GLOBAL_pages_sg_hash) * sizeof(struct subgoal_trie_hash); } -static inline long show_statistics_answer_trie_hashes(void) { +static inline long show_statistics_answer_trie_hashes(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_TABLING pg_hd_ptr pg_hd; ans_hash_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_ans_hash); + pg_hd = Pg_free_pg(GLOBAL_pages_ans_hash); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1207,26 +1259,26 @@ static inline long show_statistics_answer_trie_hashes(void) { } pg_hd = PgHd_next(pg_hd); } - TABLING_ERROR_CHECKING(statistics_answer_trie_hashes, Pg_str_free(Yap_pages_ans_hash) != cont); + TABLING_ERROR_CHECKING(statistics_answer_trie_hashes, Pg_str_free(GLOBAL_pages_ans_hash) != cont); #endif /* DEBUG_TABLING */ - fprintf(Yap_stdout, " Answer trie hashes: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_ans_hash) * sizeof(struct answer_trie_hash), Pg_pg_alloc(Yap_pages_ans_hash), Pg_str_in_use(Yap_pages_ans_hash)); + Sfprintf(out, " Answer trie hashes: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_ans_hash) * sizeof(struct answer_trie_hash), Pg_pg_alloc(GLOBAL_pages_ans_hash), Pg_str_in_use(GLOBAL_pages_ans_hash)); #else - fprintf(Yap_stdout, " Answer trie hashes: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_ans_hash) * sizeof(struct answer_trie_hash), Pg_str_in_use(Yap_pages_ans_hash)); + Sfprintf(out, " Answer trie hashes: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_ans_hash) * sizeof(struct answer_trie_hash), Pg_str_in_use(GLOBAL_pages_ans_hash)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_ans_hash) * sizeof(struct answer_trie_hash); + return Pg_str_in_use(GLOBAL_pages_ans_hash) * sizeof(struct answer_trie_hash); } -static inline long show_statistics_global_trie_nodes(void) { +static inline long show_statistics_global_trie_nodes(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_TABLING pg_hd_ptr pg_hd; gt_node_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_gt_node); + pg_hd = Pg_free_pg(GLOBAL_pages_gt_node); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1235,26 +1287,27 @@ static inline long show_statistics_global_trie_nodes(void) { } pg_hd = PgHd_next(pg_hd); } - TABLING_ERROR_CHECKING(statistics_global_trie_nodes, Pg_str_free(Yap_pages_gt_node) != cont); + TABLING_ERROR_CHECKING(statistics_global_trie_nodes, Pg_str_free(GLOBAL_pages_gt_node) != cont); #endif /* DEBUG_TABLING */ - fprintf(Yap_stdout, " Global trie nodes: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_gt_node) * sizeof(struct global_trie_node), Pg_pg_alloc(Yap_pages_gt_node), Pg_str_in_use(Yap_pages_gt_node)); + Sfprintf(out, " Global trie nodes: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_gt_node) * sizeof(struct global_trie_node), Pg_pg_alloc(GLOBAL_pages_gt_node), Pg_str_in_use(GLOBAL_pages_gt_node)); #else - fprintf(Yap_stdout, " Global trie nodes: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_gt_node) * sizeof(struct global_trie_node), Pg_str_in_use(Yap_pages_gt_node)); + Sfprintf(out, " Global trie nodes: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_gt_node) * sizeof(struct global_trie_node), Pg_str_in_use(GLOBAL_pages_gt_node)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_gt_node) * sizeof(struct global_trie_node); + return Pg_str_in_use(GLOBAL_pages_gt_node) * sizeof(struct global_trie_node); } -static inline long show_statistics_global_trie_hashes(void) { +static inline long show_statistics_global_trie_hashes(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_TABLING + /* suport not yet implemented :( pg_hd_ptr pg_hd; gt_hash_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_gt_hash); + pg_hd = Pg_free_pg(GLOBAL_pages_gt_hash); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1263,28 +1316,29 @@ static inline long show_statistics_global_trie_hashes(void) { } pg_hd = PgHd_next(pg_hd); } - TABLING_ERROR_CHECKING(statistics_global_trie_hashes, Pg_str_free(Yap_pages_gt_hash) != cont); + TABLING_ERROR_CHECKING(statistics_global_trie_hashes, Pg_str_free(GLOBAL_pages_gt_hash) != cont); + */ #endif /* DEBUG_TABLING */ - fprintf(Yap_stdout, " Global trie hashes: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_gt_hash) * sizeof(struct global_trie_hash), Pg_pg_alloc(Yap_pages_gt_hash), Pg_str_in_use(Yap_pages_gt_hash)); + Sfprintf(out, " Global trie hashes: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_gt_hash) * sizeof(struct global_trie_hash), Pg_pg_alloc(GLOBAL_pages_gt_hash), Pg_str_in_use(GLOBAL_pages_gt_hash)); #else - fprintf(Yap_stdout, " Global trie hashes: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_gt_hash) * sizeof(struct global_trie_hash), Pg_str_in_use(Yap_pages_gt_hash)); + Sfprintf(out, " Global trie hashes: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_gt_hash) * sizeof(struct global_trie_hash), Pg_str_in_use(GLOBAL_pages_gt_hash)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_gt_hash) * sizeof(struct global_trie_hash); + return Pg_str_in_use(GLOBAL_pages_gt_hash) * sizeof(struct global_trie_hash); } #endif /* TABLING */ #ifdef YAPOR -static inline long show_statistics_or_frames(void) { +static inline long show_statistics_or_frames(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_YAPOR pg_hd_ptr pg_hd; or_fr_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_or_fr ); + pg_hd = Pg_free_pg(GLOBAL_pages_or_fr ); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1293,26 +1347,26 @@ static inline long show_statistics_or_frames(void) { } pg_hd = PgHd_next(pg_hd); } - YAPOR_ERROR_CHECKING(statistics_or_frames, Pg_str_free(Yap_pages_or_fr ) != cont); + YAPOR_ERROR_CHECKING(statistics_or_frames, Pg_str_free(GLOBAL_pages_or_fr ) != cont); #endif /* DEBUG_YAPOR */ - fprintf(Yap_stdout, " Or-frames: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_or_fr ) * sizeof(struct or_frame), Pg_pg_alloc(Yap_pages_or_fr ), Pg_str_in_use(Yap_pages_or_fr )); + Sfprintf(out, " Or-frames: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_or_fr ) * sizeof(struct or_frame), Pg_pg_alloc(GLOBAL_pages_or_fr ), Pg_str_in_use(GLOBAL_pages_or_fr )); #else - fprintf(Yap_stdout, " Or-frames: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_or_fr ) * sizeof(struct or_frame), Pg_str_in_use(Yap_pages_or_fr )); + Sfprintf(out, " Or-frames: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_or_fr ) * sizeof(struct or_frame), Pg_str_in_use(GLOBAL_pages_or_fr )); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_or_fr ) * sizeof(struct or_frame); + return Pg_str_in_use(GLOBAL_pages_or_fr ) * sizeof(struct or_frame); } -static inline long show_statistics_query_goal_solution_frames(void) { +static inline long show_statistics_query_goal_solution_frames(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_YAPOR pg_hd_ptr pg_hd; qg_sol_fr_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_qg_sol_fr ); + pg_hd = Pg_free_pg(GLOBAL_pages_qg_sol_fr ); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1321,26 +1375,26 @@ static inline long show_statistics_query_goal_solution_frames(void) { } pg_hd = PgHd_next(pg_hd); } - YAPOR_ERROR_CHECKING(statistics_query_goal_solution_frames, Pg_str_free(Yap_pages_qg_sol_fr ) != cont); + YAPOR_ERROR_CHECKING(statistics_query_goal_solution_frames, Pg_str_free(GLOBAL_pages_qg_sol_fr ) != cont); #endif /* DEBUG_YAPOR */ - fprintf(Yap_stdout, " Query goal solution frames: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame), Pg_pg_alloc(Yap_pages_qg_sol_fr ), Pg_str_in_use(Yap_pages_qg_sol_fr )); + Sfprintf(out, " Query goal solution frames: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame), Pg_pg_alloc(GLOBAL_pages_qg_sol_fr ), Pg_str_in_use(GLOBAL_pages_qg_sol_fr )); #else - fprintf(Yap_stdout, " Query goal solution frames: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame), Pg_str_in_use(Yap_pages_qg_sol_fr )); + Sfprintf(out, " Query goal solution frames: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame), Pg_str_in_use(GLOBAL_pages_qg_sol_fr )); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame); + return Pg_str_in_use(GLOBAL_pages_qg_sol_fr ) * sizeof(struct query_goal_solution_frame); } -static inline long show_statistics_query_goal_answer_frames(void) { +static inline long show_statistics_query_goal_answer_frames(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_YAPOR pg_hd_ptr pg_hd; qg_ans_fr_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_qg_ans_fr); + pg_hd = Pg_free_pg(GLOBAL_pages_qg_ans_fr); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1349,28 +1403,28 @@ static inline long show_statistics_query_goal_answer_frames(void) { } pg_hd = PgHd_next(pg_hd); } - YAPOR_ERROR_CHECKING(statistics_query_goal_answer_frames, Pg_str_free(Yap_pages_qg_ans_fr) != cont); + YAPOR_ERROR_CHECKING(statistics_query_goal_answer_frames, Pg_str_free(GLOBAL_pages_qg_ans_fr) != cont); #endif /* DEBUG_YAPOR */ - fprintf(Yap_stdout, " Query goal answer frames: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame), Pg_pg_alloc(Yap_pages_qg_ans_fr), Pg_str_in_use(Yap_pages_qg_ans_fr)); + Sfprintf(out, " Query goal answer frames: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame), Pg_pg_alloc(GLOBAL_pages_qg_ans_fr), Pg_str_in_use(GLOBAL_pages_qg_ans_fr)); #else - fprintf(Yap_stdout, " Query goal answer frames: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame), Pg_str_in_use(Yap_pages_qg_ans_fr)); + Sfprintf(out, " Query goal answer frames: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame), Pg_str_in_use(GLOBAL_pages_qg_ans_fr)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame); + return Pg_str_in_use(GLOBAL_pages_qg_ans_fr) * sizeof(struct query_goal_answer_frame); } #endif /* YAPOR */ #if defined(YAPOR) && defined(TABLING) -static inline long show_statistics_suspension_frames(void) { +static inline long show_statistics_suspension_frames(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_OPTYAP pg_hd_ptr pg_hd; susp_fr_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_susp_fr); + pg_hd = Pg_free_pg(GLOBAL_pages_susp_fr); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1379,27 +1433,27 @@ static inline long show_statistics_suspension_frames(void) { } pg_hd = PgHd_next(pg_hd); } - OPTYAP_ERROR_CHECKING(statistics_suspension_frames, Pg_str_free(Yap_pages_susp_fr) != cont); + OPTYAP_ERROR_CHECKING(statistics_suspension_frames, Pg_str_free(GLOBAL_pages_susp_fr) != cont); #endif /* DEBUG_OPTYAP */ - fprintf(Yap_stdout, " Suspension frames: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_susp_fr) * sizeof(struct suspension_frame), Pg_pg_alloc(Yap_pages_susp_fr), Pg_str_in_use(Yap_pages_susp_fr)); + Sfprintf(out, " Suspension frames: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_susp_fr) * sizeof(struct suspension_frame), Pg_pg_alloc(GLOBAL_pages_susp_fr), Pg_str_in_use(GLOBAL_pages_susp_fr)); #else - fprintf(Yap_stdout, " Suspension frames: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_susp_fr) * sizeof(struct suspension_frame), Pg_str_in_use(Yap_pages_susp_fr)); + Sfprintf(out, " Suspension frames: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_susp_fr) * sizeof(struct suspension_frame), Pg_str_in_use(GLOBAL_pages_susp_fr)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_susp_fr) * sizeof(struct suspension_frame); + return Pg_str_in_use(GLOBAL_pages_susp_fr) * sizeof(struct suspension_frame); } #ifdef TABLING_INNER_CUTS -static inline long show_statistics_table_subgoal_solution_frames(void) { +static inline long show_statistics_table_subgoal_solution_frames(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_OPTYAP pg_hd_ptr pg_hd; tg_sol_fr_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_tg_sol_fr); + pg_hd = Pg_free_pg(GLOBAL_pages_tg_sol_fr); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1408,26 +1462,26 @@ static inline long show_statistics_table_subgoal_solution_frames(void) { } pg_hd = PgHd_next(pg_hd); } - OPTYAP_ERROR_CHECKING(statistics_table_subgoal_solution_frames, Pg_str_free(Yap_pages_tg_sol_fr) != cont); + OPTYAP_ERROR_CHECKING(statistics_table_subgoal_solution_frames, Pg_str_free(GLOBAL_pages_tg_sol_fr) != cont); #endif /* DEBUG_OPTYAP */ - fprintf(Yap_stdout, " Table subgoal solution frames: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame), Pg_pg_alloc(Yap_pages_tg_sol_fr), Pg_str_in_use(Yap_pages_tg_sol_fr)); + Sfprintf(out, " Table subgoal solution frames: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame), Pg_pg_alloc(GLOBAL_pages_tg_sol_fr), Pg_str_in_use(GLOBAL_pages_tg_sol_fr)); #else - fprintf(Yap_stdout, " Table subgoal solution frames: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame), Pg_str_in_use(Yap_pages_tg_sol_fr)); + Sfprintf(out, " Table subgoal solution frames: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame), Pg_str_in_use(GLOBAL_pages_tg_sol_fr)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame); + return Pg_str_in_use(GLOBAL_pages_tg_sol_fr) * sizeof(struct table_subgoal_solution_frame); } -static inline long show_statistics_table_subgoal_answer_frames(void) { +static inline long show_statistics_table_subgoal_answer_frames(IOSTREAM *out) { #ifdef USE_PAGES_MALLOC #ifdef DEBUG_OPTYAP pg_hd_ptr pg_hd; tg_ans_fr_ptr aux_ptr; long cont = 0; - pg_hd = Pg_free_pg(Yap_pages_tg_ans_fr); + pg_hd = Pg_free_pg(GLOBAL_pages_tg_ans_fr); while (pg_hd) { aux_ptr = PgHd_free_str(pg_hd); while (aux_ptr) { @@ -1436,15 +1490,15 @@ static inline long show_statistics_table_subgoal_answer_frames(void) { } pg_hd = PgHd_next(pg_hd); } - OPTYAP_ERROR_CHECKING(statistics_table_subgoal_answer_frames, Pg_str_free(Yap_pages_tg_ans_fr) != cont); + OPTYAP_ERROR_CHECKING(statistics_table_subgoal_answer_frames, Pg_str_free(GLOBAL_pages_tg_ans_fr) != cont); #endif /* DEBUG_OPTYAP */ - fprintf(Yap_stdout, " Table subgoal answer frames: %10ld bytes (%ld pages and %ld structs in use)\n", - Pg_str_in_use(Yap_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame), Pg_pg_alloc(Yap_pages_tg_ans_fr), Pg_str_in_use(Yap_pages_tg_ans_fr)); + Sfprintf(out, " Table subgoal answer frames: %10ld bytes (%ld pages and %ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame), Pg_pg_alloc(GLOBAL_pages_tg_ans_fr), Pg_str_in_use(GLOBAL_pages_tg_ans_fr)); #else - fprintf(Yap_stdout, " Table subgoal answer frames: %10ld bytes (%ld structs in use)\n", - Pg_str_in_use(Yap_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame), Pg_str_in_use(Yap_pages_tg_ans_fr)); + Sfprintf(out, " Table subgoal answer frames: %10ld bytes (%ld structs in use)\n", + Pg_str_in_use(GLOBAL_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame), Pg_str_in_use(GLOBAL_pages_tg_ans_fr)); #endif /* USE_PAGES_MALLOC */ - return Pg_str_in_use(Yap_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame); + return Pg_str_in_use(GLOBAL_pages_tg_ans_fr) * sizeof(struct table_subgoal_answer_frame); } #endif /* TABLING_INNER_CUTS */ #endif /* YAPOR && TABLING */ diff --git a/OPTYap/opt.proto.h b/OPTYap/opt.proto.h index 2502b9b4a..b954016dc 100644 --- a/OPTYap/opt.proto.h +++ b/OPTYap/opt.proto.h @@ -11,15 +11,9 @@ ** ** ************************************************************************/ -/*************************** -** opt.memory.c ** -***************************/ - -#ifdef YAPOR -void Yap_init_optyap_memory(long, long, long, int); -void Yap_unmap_optyap_memory(void); -void Yap_remap_optyap_memory(void); -#endif /* YAPOR */ +#if defined(TABLING) || defined(YAPOR) +#include "SWI-Stream.h" +#endif /* TABLING || YAPOR */ @@ -27,12 +21,9 @@ void Yap_remap_optyap_memory(void); ** opt.init.c ** *************************/ -void Yap_init_optyap_data(int, int, int, int); -void Yap_init_local(void); -void make_root_frames(void); -#ifdef YAPOR -void init_workers(void); -#endif /* YAPOR */ +void Yap_init_global_optyap_data(int, int, int, int); +void Yap_init_local_optyap_data(int); +void Yap_init_root_frames(void); void itos(int, char *); @@ -61,8 +52,8 @@ void free_subgoal_trie(sg_node_ptr, int, int); void free_answer_trie(ans_node_ptr, int, int); void free_subgoal_hash_chain(sg_hash_ptr); void free_answer_hash_chain(ans_hash_ptr); -void show_table(tab_ent_ptr, int); -void show_global_trie(int); +void show_table(tab_ent_ptr, int, IOSTREAM *); +void show_global_trie(int, IOSTREAM *); #endif /* TABLING */ @@ -84,9 +75,22 @@ void resume_suspension_frame(susp_fr_ptr, or_fr_ptr); /************************** -** or.copy_engine.c ** +** or.memory.c ** **************************/ +#ifdef YAPOR +void Yap_init_yapor_global_local_memory(void); +void Yap_init_yapor_stacks_memory(long, long, long, int); +void Yap_unmap_yapor_memory(void); +void Yap_remap_yapor_memory(void); +#endif /* YAPOR */ + + + +/******************************* +** or.copy_engine.c ** +*******************************/ + #ifdef YAPOR void make_root_choice_point(void); void free_root_choice_point(void); diff --git a/OPTYap/opt.structs.h b/OPTYap/opt.structs.h index 06c6d7c7e..762d2a66d 100644 --- a/OPTYap/opt.structs.h +++ b/OPTYap/opt.structs.h @@ -57,6 +57,7 @@ cptr_to_offset_with_null(choiceptr node) ** Struct page_header ** *********************************/ +#ifdef USE_PAGES_MALLOC typedef struct page_header { volatile int structs_in_use; void *first_free_struct; @@ -68,6 +69,7 @@ typedef struct page_header { #define PgHd_free_str(X) ((X)->first_free_struct) #define PgHd_previous(X) ((X)->previous) #define PgHd_next(X) ((X)->next) +#endif /* USE_PAGES_MALLOC */ @@ -132,12 +134,12 @@ struct global_pages { -/********************************** -** Struct global_locks ** -**********************************/ +/***************************************** +** Struct global_optyap_locks ** +*****************************************/ #ifdef YAPOR -struct global_locks { +struct global_optyap_locks { lockvar bitmap_idle_workers; lockvar bitmap_root_cp_workers; lockvar bitmap_invisible_workers; @@ -160,7 +162,7 @@ struct global_locks { * Struct global_optyap_data ** *********************************/ -struct global_optyap_data{ +struct global_optyap_data { /* global data related to memory management */ struct global_pages pages; @@ -198,7 +200,7 @@ struct global_optyap_data{ #ifdef TABLING_INNER_CUTS volatile bitmap pruning_workers; #endif /* TABLING_INNER_CUTS */ - struct global_locks locks; + struct global_optyap_locks locks; volatile unsigned int branch[MAX_WORKERS][MAX_BRANCH_DEPTH]; volatile char parallel_execution_mode; /* TRUE / FALSE */ volatile int answers; @@ -224,81 +226,81 @@ struct global_optyap_data{ #endif /* TABLING */ }; -#define Yap_max_pages (Yap_optyap_data.pages.max_pages) -#define Yap_pages_void (Yap_optyap_data.pages.void_pages) -#define Yap_pages_or_fr (Yap_optyap_data.pages.or_frame_pages) -#define Yap_pages_qg_sol_fr (Yap_optyap_data.pages.query_goal_solution_frame_pages) -#define Yap_pages_qg_ans_fr (Yap_optyap_data.pages.query_goal_answer_frame_pages) -#define Yap_pages_tg_sol_fr (Yap_optyap_data.pages.table_subgoal_solution_frame_pages) -#define Yap_pages_tg_ans_fr (Yap_optyap_data.pages.table_subgoal_answer_frame_pages) -#define Yap_pages_tab_ent (Yap_optyap_data.pages.table_entry_pages) -#define Yap_pages_sg_fr (Yap_optyap_data.pages.subgoal_frame_pages) -#define Yap_pages_dep_fr (Yap_optyap_data.pages.dependency_frame_pages) -#define Yap_pages_sg_node (Yap_optyap_data.pages.subgoal_trie_node_pages) -#define Yap_pages_ans_node (Yap_optyap_data.pages.answer_trie_node_pages) -#define Yap_pages_gt_node (Yap_optyap_data.pages.global_trie_node_pages) -#define Yap_pages_sg_hash (Yap_optyap_data.pages.subgoal_trie_hash_pages) -#define Yap_pages_ans_hash (Yap_optyap_data.pages.answer_trie_hash_pages) -#define Yap_pages_gt_hash (Yap_optyap_data.pages.global_trie_hash_pages) -#define Yap_pages_susp_fr (Yap_optyap_data.pages.suspension_frame_pages) -#define Yap_scheduler_loop (Yap_optyap_data.scheduler_loop) -#define Yap_delayed_release_load (Yap_optyap_data.delayed_release_load) -#define Yap_number_workers (Yap_optyap_data.number_workers) -#define Yap_worker_pid(worker) (Yap_optyap_data.worker_pid[worker]) -#define Yap_master_worker (Yap_optyap_data.master_worker) -#define Yap_execution_time (Yap_optyap_data.execution_time) -#define Yap_best_times(time) (Yap_optyap_data.best_execution_times[time]) -#define Yap_number_goals (Yap_optyap_data.number_of_executed_goals) -#define Yap_performance_mode (Yap_optyap_data.performance_mode) +#define GLOBAL_max_pages (GLOBAL_optyap_data.pages.max_pages) +#define GLOBAL_pages_void (GLOBAL_optyap_data.pages.void_pages) +#define GLOBAL_pages_or_fr (GLOBAL_optyap_data.pages.or_frame_pages) +#define GLOBAL_pages_qg_sol_fr (GLOBAL_optyap_data.pages.query_goal_solution_frame_pages) +#define GLOBAL_pages_qg_ans_fr (GLOBAL_optyap_data.pages.query_goal_answer_frame_pages) +#define GLOBAL_pages_tg_sol_fr (GLOBAL_optyap_data.pages.table_subgoal_solution_frame_pages) +#define GLOBAL_pages_tg_ans_fr (GLOBAL_optyap_data.pages.table_subgoal_answer_frame_pages) +#define GLOBAL_pages_tab_ent (GLOBAL_optyap_data.pages.table_entry_pages) +#define GLOBAL_pages_sg_fr (GLOBAL_optyap_data.pages.subgoal_frame_pages) +#define GLOBAL_pages_dep_fr (GLOBAL_optyap_data.pages.dependency_frame_pages) +#define GLOBAL_pages_sg_node (GLOBAL_optyap_data.pages.subgoal_trie_node_pages) +#define GLOBAL_pages_ans_node (GLOBAL_optyap_data.pages.answer_trie_node_pages) +#define GLOBAL_pages_gt_node (GLOBAL_optyap_data.pages.global_trie_node_pages) +#define GLOBAL_pages_sg_hash (GLOBAL_optyap_data.pages.subgoal_trie_hash_pages) +#define GLOBAL_pages_ans_hash (GLOBAL_optyap_data.pages.answer_trie_hash_pages) +#define GLOBAL_pages_gt_hash (GLOBAL_optyap_data.pages.global_trie_hash_pages) +#define GLOBAL_pages_susp_fr (GLOBAL_optyap_data.pages.suspension_frame_pages) +#define GLOBAL_scheduler_loop (GLOBAL_optyap_data.scheduler_loop) +#define GLOBAL_delayed_release_load (GLOBAL_optyap_data.delayed_release_load) +#define GLOBAL_number_workers (GLOBAL_optyap_data.number_workers) +#define GLOBAL_worker_pid(worker) (GLOBAL_optyap_data.worker_pid[worker]) +#define GLOBAL_master_worker (GLOBAL_optyap_data.master_worker) +#define GLOBAL_execution_time (GLOBAL_optyap_data.execution_time) +#define GLOBAL_best_times(time) (GLOBAL_optyap_data.best_execution_times[time]) +#define GLOBAL_number_goals (GLOBAL_optyap_data.number_of_executed_goals) +#define GLOBAL_performance_mode (GLOBAL_optyap_data.performance_mode) #ifdef YAPOR_THREADS -#define Get_Yap_root_cp() offset_to_cptr(Yap_optyap_data.root_choice_point_offset) -#define Set_Yap_root_cp(bptr) (Yap_optyap_data.root_choice_point_offset = cptr_to_offset(bptr)) +#define Get_GLOBAL_root_cp() offset_to_cptr(GLOBAL_optyap_data.root_choice_point_offset) +#define Set_GLOBAL_root_cp(bptr) (GLOBAL_optyap_data.root_choice_point_offset = cptr_to_offset(bptr)) #else -#define Yap_root_cp (Yap_optyap_data.root_choice_point) -#define Get_Yap_root_cp() (Yap_optyap_data.root_choice_point) -#define Set_Yap_root_cp(bptr) (Yap_optyap_data.root_choice_point = (bptr)) +#define GLOBAL_root_cp (GLOBAL_optyap_data.root_choice_point) +#define Get_GLOBAL_root_cp() (GLOBAL_optyap_data.root_choice_point) +#define Set_GLOBAL_root_cp(bptr) (GLOBAL_optyap_data.root_choice_point = (bptr)) #endif -#define Yap_root_or_fr (Yap_optyap_data.root_or_frame) -#define Yap_bm_present_workers (Yap_optyap_data.present_workers) -#define Yap_bm_idle_workers (Yap_optyap_data.idle_workers) -#define Yap_bm_root_cp_workers (Yap_optyap_data.root_cp_workers) -#define Yap_bm_invisible_workers (Yap_optyap_data.invisible_workers) -#define Yap_bm_requestable_workers (Yap_optyap_data.requestable_workers) -#define Yap_bm_executing_workers (Yap_optyap_data.executing_workers) -#define Yap_bm_finished_workers (Yap_optyap_data.finished_workers) -#define Yap_bm_pruning_workers (Yap_optyap_data.pruning_workers) -#define Yap_locks_bm_idle_workers (Yap_optyap_data.locks.bitmap_idle_workers) -#define Yap_locks_bm_root_cp_workers (Yap_optyap_data.locks.bitmap_root_cp_workers) -#define Yap_locks_bm_invisible_workers (Yap_optyap_data.locks.bitmap_invisible_workers) -#define Yap_locks_bm_requestable_workers (Yap_optyap_data.locks.bitmap_requestable_workers) -#define Yap_locks_bm_executing_workers (Yap_optyap_data.locks.bitmap_executing_workers) -#define Yap_locks_bm_finished_workers (Yap_optyap_data.locks.bitmap_finished_workers) -#define Yap_locks_bm_pruning_workers (Yap_optyap_data.locks.bitmap_pruning_workers) -#define Yap_locks_who_locked_heap (Yap_optyap_data.locks.who_locked_heap) -#define Yap_locks_heap_access (Yap_optyap_data.locks.heap_access) -#define Yap_locks_alloc_block (Yap_optyap_data.locks.alloc_block) -#define Yap_branch(worker, depth) (Yap_optyap_data.branch[worker][depth]) -#define Yap_parallel_execution_mode (Yap_optyap_data.parallel_execution_mode) -#define Yap_answers (Yap_optyap_data.answers) -#define Yap_root_gt (Yap_optyap_data.root_global_trie) -#define Yap_root_tab_ent (Yap_optyap_data.root_table_entry) -#define Yap_first_sg_fr (Yap_optyap_data.first_subgoal_frame) -#define Yap_last_sg_fr (Yap_optyap_data.last_subgoal_frame) -#define Yap_check_sg_fr (Yap_optyap_data.check_subgoal_frame) -#define Yap_root_dep_fr (Yap_optyap_data.root_dependency_frame) -#define Yap_table_var_enumerator(index) (Yap_optyap_data.table_var_enumerator[index]) -#define Yap_table_var_enumerator_addr(index) (Yap_optyap_data.table_var_enumerator + (index)) -#define Yap_table_lock(index) (Yap_optyap_data.table_lock[index]) -#define Yap_timestamp (Yap_optyap_data.timestamp) +#define GLOBAL_root_or_fr (GLOBAL_optyap_data.root_or_frame) +#define GLOBAL_bm_present_workers (GLOBAL_optyap_data.present_workers) +#define GLOBAL_bm_idle_workers (GLOBAL_optyap_data.idle_workers) +#define GLOBAL_bm_root_cp_workers (GLOBAL_optyap_data.root_cp_workers) +#define GLOBAL_bm_invisible_workers (GLOBAL_optyap_data.invisible_workers) +#define GLOBAL_bm_requestable_workers (GLOBAL_optyap_data.requestable_workers) +#define GLOBAL_bm_executing_workers (GLOBAL_optyap_data.executing_workers) +#define GLOBAL_bm_finished_workers (GLOBAL_optyap_data.finished_workers) +#define GLOBAL_bm_pruning_workers (GLOBAL_optyap_data.pruning_workers) +#define GLOBAL_locks_bm_idle_workers (GLOBAL_optyap_data.locks.bitmap_idle_workers) +#define GLOBAL_locks_bm_root_cp_workers (GLOBAL_optyap_data.locks.bitmap_root_cp_workers) +#define GLOBAL_locks_bm_invisible_workers (GLOBAL_optyap_data.locks.bitmap_invisible_workers) +#define GLOBAL_locks_bm_requestable_workers (GLOBAL_optyap_data.locks.bitmap_requestable_workers) +#define GLOBAL_locks_bm_executing_workers (GLOBAL_optyap_data.locks.bitmap_executing_workers) +#define GLOBAL_locks_bm_finished_workers (GLOBAL_optyap_data.locks.bitmap_finished_workers) +#define GLOBAL_locks_bm_pruning_workers (GLOBAL_optyap_data.locks.bitmap_pruning_workers) +#define GLOBAL_locks_who_locked_heap (GLOBAL_optyap_data.locks.who_locked_heap) +#define GLOBAL_locks_heap_access (GLOBAL_optyap_data.locks.heap_access) +#define GLOBAL_locks_alloc_block (GLOBAL_optyap_data.locks.alloc_block) +#define GLOBAL_branch(worker, depth) (GLOBAL_optyap_data.branch[worker][depth]) +#define GLOBAL_parallel_execution_mode (GLOBAL_optyap_data.parallel_execution_mode) +#define GLOBAL_answers (GLOBAL_optyap_data.answers) +#define GLOBAL_root_gt (GLOBAL_optyap_data.root_global_trie) +#define GLOBAL_root_tab_ent (GLOBAL_optyap_data.root_table_entry) +#define GLOBAL_first_sg_fr (GLOBAL_optyap_data.first_subgoal_frame) +#define GLOBAL_last_sg_fr (GLOBAL_optyap_data.last_subgoal_frame) +#define GLOBAL_check_sg_fr (GLOBAL_optyap_data.check_subgoal_frame) +#define GLOBAL_root_dep_fr (GLOBAL_optyap_data.root_dependency_frame) +#define GLOBAL_table_var_enumerator(index) (GLOBAL_optyap_data.table_var_enumerator[index]) +#define GLOBAL_table_var_enumerator_addr(index) (GLOBAL_optyap_data.table_var_enumerator + (index)) +#define GLOBAL_table_lock(index) (GLOBAL_optyap_data.table_lock[index]) +#define GLOBAL_timestamp (GLOBAL_optyap_data.timestamp) -/*********************************** -** Struct local_signals ** -***********************************/ +/****************************************** +** Struct local_optyap_signals ** +******************************************/ #ifdef YAPOR -struct local_signals{ +struct local_optyap_signals{ #if defined(YAPOR_COPY) || defined(YAPOR_THREADS) lockvar lock; volatile enum { @@ -341,11 +343,11 @@ typedef struct { -/******************************** -** Struct local_data ** -********************************/ +/*************************************** +** Struct local_optyap_data ** +***************************************/ -struct local_data{ +struct local_optyap_data { #ifdef YAPOR lockvar lock; /* local data related to or-parallelism */ @@ -362,7 +364,7 @@ struct local_data{ choiceptr prune_request; #endif volatile int share_request; - struct local_signals share_signals; + struct local_optyap_signals share_signals; volatile struct { CELL start; CELL end; @@ -394,95 +396,95 @@ struct local_data{ #endif /* (TABLING || !YAPOR_COW) && MULTI_ASSIGNMENT_VARIABLES */ }; -#define LOCAL_lock (LOCAL->lock) -#define LOCAL_load (LOCAL->load) +#define LOCAL_lock (LOCAL_optyap_data.lock) +#define LOCAL_load (LOCAL_optyap_data.load) #ifdef YAPOR_THREADS -#define Get_LOCAL_top_cp() offset_to_cptr(LOCAL->top_choice_point_offset) -#define Set_LOCAL_top_cp(cpt) (LOCAL->top_choice_point_offset = cptr_to_offset(cpt)) +#define Get_LOCAL_top_cp() offset_to_cptr(LOCAL_optyap_data.top_choice_point_offset) +#define Set_LOCAL_top_cp(cpt) (LOCAL_optyap_data.top_choice_point_offset = cptr_to_offset(cpt)) #else -#define LOCAL_top_cp (LOCAL->top_choice_point) -#define Get_LOCAL_top_cp() (LOCAL->top_choice_point) -#define Set_LOCAL_top_cp(cpt) (LOCAL->top_choice_point = cpt) -#endif -#define LOCAL_top_or_fr (LOCAL->top_or_frame) +#define LOCAL_top_cp (LOCAL_optyap_data.top_choice_point) +#define Get_LOCAL_top_cp() (LOCAL_optyap_data.top_choice_point) +#define Set_LOCAL_top_cp(cpt) (LOCAL_optyap_data.top_choice_point = cpt) +#endif /* YAPOR_THREADS */ +#define LOCAL_top_or_fr (LOCAL_optyap_data.top_or_frame) #ifdef YAPOR_THREADS -#define Get_LOCAL_prune_request() offset_to_cptr_with_null(LOCAL->prune_request_offset) -#define Set_LOCAL_prune_request(cpt) (LOCAL->prune_request_offset = cptr_to_offset_with_null(cpt)) +#define Get_LOCAL_prune_request() offset_to_cptr_with_null(LOCAL_optyap_data.prune_request_offset) +#define Set_LOCAL_prune_request(cpt) (LOCAL_optyap_data.prune_request_offset = cptr_to_offset_with_null(cpt)) #else -#define LOCAL_prune_request (LOCAL->prune_request) -#define Get_LOCAL_prune_request() (LOCAL->prune_request) -#define Set_LOCAL_prune_request(cpt) (LOCAL->prune_request = cpt) -#endif -#define LOCAL_share_request (LOCAL->share_request) -#define LOCAL_reply_signal (LOCAL->share_signals.reply_signal) -#define LOCAL_p_fase_signal (LOCAL->share_signals.P_fase) -#define LOCAL_q_fase_signal (LOCAL->share_signals.Q_fase) -#define LOCAL_lock_signals (LOCAL->share_signals.lock) -#define LOCAL_start_global_copy (LOCAL->global_copy.start) -#define LOCAL_end_global_copy (LOCAL->global_copy.end) -#define LOCAL_start_local_copy (LOCAL->local_copy.start) -#define LOCAL_end_local_copy (LOCAL->local_copy.end) -#define LOCAL_start_trail_copy (LOCAL->trail_copy.start) -#define LOCAL_end_trail_copy (LOCAL->trail_copy.end) -#define LOCAL_next_free_ans_node (LOCAL->next_free_answer_trie_node) -#define LOCAL_top_sg_fr (LOCAL->top_subgoal_frame) -#define LOCAL_top_dep_fr (LOCAL->top_dependency_frame) -#define LOCAL_pruning_scope (LOCAL->bottom_pruning_scope) +#define LOCAL_prune_request (LOCAL_optyap_data.prune_request) +#define Get_LOCAL_prune_request() (LOCAL_optyap_data.prune_request) +#define Set_LOCAL_prune_request(cpt) (LOCAL_optyap_data.prune_request = cpt) +#endif /* YAPOR_THREADS */ +#define LOCAL_share_request (LOCAL_optyap_data.share_request) +#define LOCAL_reply_signal (LOCAL_optyap_data.share_signals.reply_signal) +#define LOCAL_p_fase_signal (LOCAL_optyap_data.share_signals.P_fase) +#define LOCAL_q_fase_signal (LOCAL_optyap_data.share_signals.Q_fase) +#define LOCAL_lock_signals (LOCAL_optyap_data.share_signals.lock) +#define LOCAL_start_global_copy (LOCAL_optyap_data.global_copy.start) +#define LOCAL_end_global_copy (LOCAL_optyap_data.global_copy.end) +#define LOCAL_start_local_copy (LOCAL_optyap_data.local_copy.start) +#define LOCAL_end_local_copy (LOCAL_optyap_data.local_copy.end) +#define LOCAL_start_trail_copy (LOCAL_optyap_data.trail_copy.start) +#define LOCAL_end_trail_copy (LOCAL_optyap_data.trail_copy.end) +#define LOCAL_next_free_ans_node (LOCAL_optyap_data.next_free_answer_trie_node) +#define LOCAL_top_sg_fr (LOCAL_optyap_data.top_subgoal_frame) +#define LOCAL_top_dep_fr (LOCAL_optyap_data.top_dependency_frame) +#define LOCAL_pruning_scope (LOCAL_optyap_data.bottom_pruning_scope) #ifdef YAPOR_THREADS -#define Get_LOCAL_top_cp_on_stack() offset_to_cptr(LOCAL->top_choice_point_on_stack_offset) -#define Set_LOCAL_top_cp_on_stack(cpt) (LOCAL->top_choice_point_on_stack_offset = cptr_to_offset(cpt)) +#define Get_LOCAL_top_cp_on_stack() offset_to_cptr(LOCAL_optyap_data.top_choice_point_on_stack_offset) +#define Set_LOCAL_top_cp_on_stack(cpt) (LOCAL_optyap_data.top_choice_point_on_stack_offset = cptr_to_offset(cpt)) #else -#define LOCAL_top_cp_on_stack (LOCAL->top_choice_point_on_stack) -#define Get_LOCAL_top_cp_on_stack() (LOCAL->top_choice_point_on_stack) -#define Set_LOCAL_top_cp_on_stack(cpt) (LOCAL->top_choice_point_on_stack = cpt) -#endif -#define LOCAL_top_susp_or_fr (LOCAL->top_or_frame_with_suspensions) -#define LOCAL_ma_timestamp (LOCAL->ma_timestamp) -#define LOCAL_ma_h_top (LOCAL->ma_h_top) -#define LOCAL_ma_hash_table (LOCAL->ma_hash_table) +#define LOCAL_top_cp_on_stack (LOCAL_optyap_data.top_choice_point_on_stack) +#define Get_LOCAL_top_cp_on_stack() (LOCAL_optyap_data.top_choice_point_on_stack) +#define Set_LOCAL_top_cp_on_stack(cpt) (LOCAL_optyap_data.top_choice_point_on_stack = cpt) +#endif /* YAPOR_THREADS */ +#define LOCAL_top_susp_or_fr (LOCAL_optyap_data.top_or_frame_with_suspensions) +#define LOCAL_ma_timestamp (LOCAL_optyap_data.ma_timestamp) +#define LOCAL_ma_h_top (LOCAL_optyap_data.ma_h_top) +#define LOCAL_ma_hash_table (LOCAL_optyap_data.ma_hash_table) -#define REMOTE_lock(worker) (REMOTE[worker].lock) -#define REMOTE_load(worker) (REMOTE[worker].load) +#define REMOTE_lock(wid) (REMOTE(wid)->optyap_data_.lock) +#define REMOTE_load(wid) (REMOTE(wid)->optyap_data_.load) #ifdef YAPOR_THREADS -#define REMOTE_top_cp(worker) offset_to_cptr(REMOTE[worker].top_choice_point_offset) -#define Set_REMOTE_top_cp(worker, bptr) (REMOTE[worker].top_choice_point_offset = cptr_to_offset(bptr)) +#define REMOTE_top_cp(wid) offset_to_cptr(REMOTE(wid)->optyap_data_.top_choice_point_offset) +#define Set_REMOTE_top_cp(wid, bptr) (REMOTE(wid)->optyap_data_.top_choice_point_offset = cptr_to_offset(bptr)) #else -#define REMOTE_top_cp(worker) (REMOTE[worker].top_choice_point) -#define Set_REMOTE_top_cp(worker, bptr) (REMOTE[worker].top_choice_point = (bptr)) -#endif -#define REMOTE_top_or_fr(worker) (REMOTE[worker].top_or_frame) +#define REMOTE_top_cp(wid) (REMOTE(wid)->optyap_data_.top_choice_point) +#define Set_REMOTE_top_cp(wid, bptr) (REMOTE(wid)->optyap_data_.top_choice_point = (bptr)) +#endif /* YAPOR_THREADS */ +#define REMOTE_top_or_fr(wid) (REMOTE(wid)->optyap_data_.top_or_frame) #ifdef YAPOR_THREADS -#define Get_REMOTE_prune_request(worker) offset_to_cptr_with_null(REMOTE[worker].prune_request_offset) -#define Set_REMOTE_prune_request(worker,cp) (REMOTE[worker].prune_request_offset = cptr_to_offset_with_null(cp)) +#define Get_REMOTE_prune_request(wid) offset_to_cptr_with_null(REMOTE(wid)->optyap_data_.prune_request_offset) +#define Set_REMOTE_prune_request(wid,cp) (REMOTE(wid)->optyap_data_.prune_request_offset = cptr_to_offset_with_null(cp)) #else -#define REMOTE_prune_request(worker) (REMOTE[worker].prune_request) -#define Get_REMOTE_prune_request(worker) (REMOTE[worker].prune_request) -#define Set_REMOTE_prune_request(worker,cp) (REMOTE[worker].prune_request = cp) -#endif -#define REMOTE_share_request(worker) (REMOTE[worker].share_request) -#define REMOTE_reply_signal(worker) (REMOTE[worker].share_signals.reply_signal) -#define REMOTE_p_fase_signal(worker) (REMOTE[worker].share_signals.P_fase) -#define REMOTE_q_fase_signal(worker) (REMOTE[worker].share_signals.Q_fase) -#define REMOTE_lock_signals(worker) (REMOTE[worker].share_signals.lock) -#define REMOTE_start_global_copy(worker) (REMOTE[worker].global_copy.start) -#define REMOTE_end_global_copy(worker) (REMOTE[worker].global_copy.end) -#define REMOTE_start_local_copy(worker) (REMOTE[worker].local_copy.start) -#define REMOTE_end_local_copy(worker) (REMOTE[worker].local_copy.end) -#define REMOTE_start_trail_copy(worker) (REMOTE[worker].trail_copy.start) -#define REMOTE_end_trail_copy(worker) (REMOTE[worker].trail_copy.end) -#define REMOTE_next_free_ans_node(worker) (REMOTE[worker].next_free_answer_trie_node) -#define REMOTE_top_sg_fr(worker) (REMOTE[worker].top_subgoal_frame) -#define REMOTE_top_dep_fr(worker) (REMOTE[worker].top_dependency_frame) -#define REMOTE_pruning_scope(worker) (REMOTE[worker].bottom_pruning_scope) +#define REMOTE_prune_request(wid) (REMOTE(wid)->optyap_data_.prune_request) +#define Get_REMOTE_prune_request(wid) (REMOTE(wid)->optyap_data_.prune_request) +#define Set_REMOTE_prune_request(wid,cp) (REMOTE(wid)->optyap_data_.prune_request = cp) +#endif /* YAPOR_THREADS */ +#define REMOTE_share_request(wid) (REMOTE(wid)->optyap_data_.share_request) +#define REMOTE_reply_signal(wid) (REMOTE(wid)->optyap_data_.share_signals.reply_signal) +#define REMOTE_p_fase_signal(wid) (REMOTE(wid)->optyap_data_.share_signals.P_fase) +#define REMOTE_q_fase_signal(wid) (REMOTE(wid)->optyap_data_.share_signals.Q_fase) +#define REMOTE_lock_signals(wid) (REMOTE(wid)->optyap_data_.share_signals.lock) +#define REMOTE_start_global_copy(wid) (REMOTE(wid)->optyap_data_.global_copy.start) +#define REMOTE_end_global_copy(wid) (REMOTE(wid)->optyap_data_.global_copy.end) +#define REMOTE_start_local_copy(wid) (REMOTE(wid)->optyap_data_.local_copy.start) +#define REMOTE_end_local_copy(wid) (REMOTE(wid)->optyap_data_.local_copy.end) +#define REMOTE_start_trail_copy(wid) (REMOTE(wid)->optyap_data_.trail_copy.start) +#define REMOTE_end_trail_copy(wid) (REMOTE(wid)->optyap_data_.trail_copy.end) +#define REMOTE_next_free_ans_node(wid) (REMOTE(wid)->optyap_data_.next_free_answer_trie_node) +#define REMOTE_top_sg_fr(wid) (REMOTE(wid)->optyap_data_.top_subgoal_frame) +#define REMOTE_top_dep_fr(wid) (REMOTE(wid)->optyap_data_.top_dependency_frame) +#define REMOTE_pruning_scope(wid) (REMOTE(wid)->optyap_data_.bottom_pruning_scope) #ifdef YAPOR_THREADS -#define REMOTE_top_cp_on_stack(worker) offset_to_cptr(REMOTE[worker].top_choice_point_on_stack_offset) -#define Set_REMOTE_top_cp_on_stack(worker, bptr) (REMOTE[worker].top_choice_point_on_stack_offset = cptr_to_offset(bptr)) +#define REMOTE_top_cp_on_stack(wid) offset_to_cptr(REMOTE(wid)->optyap_data_.top_choice_point_on_stack_offset) +#define Set_REMOTE_top_cp_on_stack(wid, bptr) (REMOTE(wid)->optyap_data_.top_choice_point_on_stack_offset = cptr_to_offset(bptr)) #else -#define REMOTE_top_cp_on_stack(worker) (REMOTE[worker].top_choice_point_on_stack) -#define Set_REMOTE_top_cp_on_stack(worker, bptr) (REMOTE[worker].top_choice_point_on_stack = (bptr)) -#endif -#define REMOTE_top_susp_or_fr(worker) (REMOTE[worker].top_or_frame_with_suspensions) +#define REMOTE_top_cp_on_stack(wid) (REMOTE(wid)->optyap_data_.top_choice_point_on_stack) +#define Set_REMOTE_top_cp_on_stack(wid, bptr) (REMOTE(wid)->optyap_data_.top_choice_point_on_stack = (bptr)) +#endif /* YAPOR_THREADS */ +#define REMOTE_top_susp_or_fr(wid) (REMOTE(wid)->optyap_data_.top_or_frame_with_suspensions) #ifdef YAPOR diff --git a/OPTYap/or.copy_engine.c b/OPTYap/or.copy_engine.c index 84675a5e1..4f0e6b0c2 100644 --- a/OPTYap/or.copy_engine.c +++ b/OPTYap/or.copy_engine.c @@ -58,7 +58,7 @@ static void share_private_nodes(int worker_q); REMOTE_end_global_copy(Q) = (CELL) (H); \ REMOTE_start_local_copy(Q) = (CELL) (B); \ REMOTE_end_local_copy(Q) = (CELL) (LCL0); \ - REMOTE_start_trail_copy(Q) = (CELL) (Yap_TrailBase); \ + REMOTE_start_trail_copy(Q) = (CELL) (LOCAL_TrailBase); \ REMOTE_end_trail_copy(Q) = (CELL) (TR) #endif @@ -97,15 +97,15 @@ static void share_private_nodes(int worker_q); void make_root_choice_point(void) { if (worker_id == 0) { - LOCAL_top_cp = Yap_root_cp = OrFr_node(Yap_root_or_fr) = B; + LOCAL_top_cp = GLOBAL_root_cp = OrFr_node(GLOBAL_root_or_fr) = B; } else { - B = LOCAL_top_cp = Yap_root_cp; + B = LOCAL_top_cp = GLOBAL_root_cp; B->cp_tr = TR = ((choiceptr) (worker_offset(0) + (CELL)(B)))->cp_tr; } B->cp_h = H0; B->cp_ap = GETWORK; - B->cp_or_fr = Yap_root_or_fr; - LOCAL_top_or_fr = Yap_root_or_fr; + B->cp_or_fr = GLOBAL_root_or_fr; + LOCAL_top_or_fr = GLOBAL_root_or_fr; LOCAL_load = 0; Set_LOCAL_prune_request(NULL); BRANCH(worker_id, 0) = 0; @@ -125,7 +125,7 @@ void free_root_choice_point(void) { #ifdef TABLING LOCAL_top_cp_on_stack = #endif /* TABLING */ - LOCAL_top_cp = Yap_root_cp = OrFr_node(Yap_root_or_fr) = (choiceptr) Yap_LocalBase; + LOCAL_top_cp = GLOBAL_root_cp = OrFr_node(GLOBAL_root_or_fr) = (choiceptr) LOCAL_LocalBase; return; } @@ -135,7 +135,7 @@ int p_share_work(void) { if (! BITMAP_member(OrFr_members(REMOTE_top_or_fr(worker_q)), worker_id) || B == REMOTE_top_cp(worker_q) || - (LOCAL_load <= Yap_delayed_release_load && OrFr_nearest_livenode(LOCAL_top_or_fr) == NULL)) { + (LOCAL_load <= GLOBAL_delayed_release_load && OrFr_nearest_livenode(LOCAL_top_or_fr) == NULL)) { /* refuse sharing request */ REMOTE_reply_signal(LOCAL_share_request) = no_sharing; LOCAL_share_request = MAX_WORKERS; @@ -220,10 +220,10 @@ int q_share_work(int worker_p) { #ifdef TABLING } else if (IsPairTerm(aux_cell)) { aux_cell = (CELL) RepPair(aux_cell); - if (IN_BETWEEN(Yap_TrailBase, aux_cell, Yap_TrailTop)) { + if (IN_BETWEEN(LOCAL_TrailBase, aux_cell, LOCAL_TrailTop)) { /* avoid frozen segments */ TR = (tr_fr_ptr) aux_cell; - TABLING_ERROR_CHECKING(q_share_work, TR > (tr_fr_ptr) Yap_TrailTop); + TABLING_ERROR_CHECKING(q_share_work, TR > (tr_fr_ptr) LOCAL_TrailTop); TABLING_ERROR_CHECKING(q_share_work, TR < aux_tr); } #endif /* TABLING */ @@ -242,7 +242,7 @@ int q_share_work(int worker_p) { /* make sharing request */ LOCK_WORKER(worker_p); - if (BITMAP_member(Yap_bm_idle_workers, worker_p) || + if (BITMAP_member(GLOBAL_bm_idle_workers, worker_p) || REMOTE_share_request(worker_p) != MAX_WORKERS) { /* worker p is idle or has another request */ UNLOCK_WORKER(worker_p); @@ -308,7 +308,7 @@ sync_with_p: if (IsVarTerm(aux_cell)) { if (aux_cell < LOCAL_start_global_copy || EQUAL_OR_YOUNGER_CP((choiceptr)LOCAL_end_local_copy, (choiceptr)aux_cell)) { YAPOR_ERROR_CHECKING(q_share_work, (CELL *)aux_cell < H0); - YAPOR_ERROR_CHECKING(q_share_work, (ADDR)aux_cell > Yap_LocalBase); + YAPOR_ERROR_CHECKING(q_share_work, (ADDR)aux_cell > LOCAL_LocalBase); #ifdef TABLING *((CELL *) aux_cell) = TrailVal(aux_tr); #else @@ -318,7 +318,7 @@ sync_with_p: #ifdef TABLING } else if (IsPairTerm(aux_cell)) { aux_cell = (CELL) RepPair(aux_cell); - if (IN_BETWEEN(Yap_TrailBase, aux_cell, Yap_TrailTop)) { + if (IN_BETWEEN(LOCAL_TrailBase, aux_cell, LOCAL_TrailTop)) { /* avoid frozen segments */ aux_tr = (tr_fr_ptr) aux_cell; } @@ -443,7 +443,7 @@ void share_private_nodes(int worker_q) { consumer_cp = DepFr_cons_cp(dep_frame); next_node_on_branch = NULL; stack_limit = (CELL *)TR; - stack = (CELL *)Yap_TrailTop; + stack = (CELL *)LOCAL_TrailTop; #endif /* TABLING */ /* initialize auxiliary variables */ @@ -549,7 +549,7 @@ void share_private_nodes(int worker_q) { #ifdef TABLING /* update or-frames stored in auxiliary stack */ - while (STACK_NOT_EMPTY(stack, (CELL *)Yap_TrailTop)) { + while (STACK_NOT_EMPTY(stack, (CELL *)LOCAL_TrailTop)) { next_node_on_branch = (choiceptr) STACK_POP_DOWN(stack); or_frame = (or_fr_ptr) STACK_POP_DOWN(stack); OrFr_nearest_livenode(or_frame) = OrFr_next(or_frame) = next_node_on_branch->cp_or_fr; @@ -658,7 +658,7 @@ void share_private_nodes(int worker_q) { #ifdef DEBUG_OPTYAP { dep_fr_ptr aux_dep_fr = LOCAL_top_dep_fr; - while(aux_dep_fr != Yap_root_dep_fr) { + while(aux_dep_fr != GLOBAL_root_dep_fr) { choiceptr top_cp_on_branch; top_cp_on_branch = DepFr_cons_cp(aux_dep_fr); while (YOUNGER_CP(top_cp_on_branch, B)) { diff --git a/OPTYap/or.cow_engine.c b/OPTYap/or.cow_engine.c index b53477f41..e88017000 100644 --- a/OPTYap/or.cow_engine.c +++ b/OPTYap/or.cow_engine.c @@ -43,9 +43,9 @@ STD_PROTO(static inline void PUT_BUSY, (int)); static inline void PUT_BUSY(int worker_num) { - LOCK(Yap_locks_bm_idle_workers); - BITMAP_delete(Yap_bm_idle_workers, worker_num); - UNLOCK(Yap_locks_bm_idle_workers); + LOCK(GLOBAL_locks_bm_idle_workers); + BITMAP_delete(GLOBAL_bm_idle_workers, worker_num); + UNLOCK(GLOBAL_locks_bm_idle_workers); return; } @@ -57,15 +57,15 @@ void PUT_BUSY(int worker_num) { void make_root_choice_point(void) { if (worker_id == 0) { - LOCAL_top_cp = Yap_root_cp = OrFr_node(Yap_root_or_fr) = B; + LOCAL_top_cp = GLOBAL_root_cp = OrFr_node(GLOBAL_root_or_fr) = B; } else { - B = LOCAL_top_cp = Yap_root_cp; + B = LOCAL_top_cp = GLOBAL_root_cp; B->cp_tr = TR = ((choiceptr) (worker_offset(0) + (CELL)(B)))->cp_tr; } B->cp_h = H0; B->cp_ap = GETWORK; - B->cp_or_fr = Yap_root_or_fr; - LOCAL_top_or_fr = Yap_root_or_fr; + B->cp_or_fr = GLOBAL_root_or_fr; + LOCAL_top_or_fr = GLOBAL_root_or_fr; LOCAL_load = 0; LOCAL_prune_request = NULL; BRANCH(worker_id, 0) = 0; @@ -75,7 +75,7 @@ void make_root_choice_point(void) { void free_root_choice_point(void) { B = LOCAL_top_cp->cp_b; - LOCAL_top_cp = (choiceptr) Yap_LocalBase; + LOCAL_top_cp = (choiceptr) LOCAL_LocalBase; return; } @@ -86,7 +86,7 @@ int p_share_work(void) { if (! BITMAP_member(OrFr_members(REMOTE_top_or_fr(worker_q)), worker_id) || B == REMOTE_top_cp(worker_q) || - (LOCAL_load <= Yap_delayed_release_load && OrFr_nearest_livenode(LOCAL_top_or_fr) == NULL)) { + (LOCAL_load <= GLOBAL_delayed_release_load && OrFr_nearest_livenode(LOCAL_top_or_fr) == NULL)) { /* refuse sharing request */ REMOTE_reply_signal(LOCAL_share_request) = no_sharing; LOCAL_share_request = MAX_WORKERS; @@ -98,14 +98,14 @@ int p_share_work(void) { share_private_nodes(worker_q); if ((son = fork()) == 0) { worker_id = worker_q; /* child becomes requesting worker */ - LOCAL = REMOTE + worker_id; + LOCAL = REMOTE(worker_id); LOCAL_reply_signal = worker_ready; PUT_IN_REQUESTABLE(worker_id); PUT_BUSY(worker_id); return FALSE; } else { - Yap_worker_pid(worker_q) = son; + GLOBAL_worker_pid(worker_q) = son; LOCAL_share_request = MAX_WORKERS; PUT_IN_REQUESTABLE(worker_id); @@ -129,7 +129,7 @@ int q_share_work(int worker_p) { /* make sharing request */ LOCK_WORKER(worker_p); - if (BITMAP_member(Yap_bm_idle_workers, worker_p) || + if (BITMAP_member(GLOBAL_bm_idle_workers, worker_p) || REMOTE_share_request(worker_p) != MAX_WORKERS) { /* worker p is idle or has another request */ UNLOCK_WORKER(worker_p); diff --git a/OPTYap/or.cut.c b/OPTYap/or.cut.c index 0b6088237..479a70e74 100644 --- a/OPTYap/or.cut.c +++ b/OPTYap/or.cut.c @@ -40,7 +40,6 @@ void prune_shared_branch(choiceptr prune_cp) { #ifdef TABLING_INNER_CUTS tg_sol_fr_ptr tg_solutions, aux_tg_solutions; #endif /* TABLING_INNER_CUTS */ - leftmost_or_fr = CUT_leftmost_or_frame(); leftmost_cp = GetOrFr_node(leftmost_or_fr); qg_solutions = NULL; @@ -58,7 +57,7 @@ void prune_shared_branch(choiceptr prune_cp) { LOCK_OR_FRAME(prune_or_fr); members = OrFr_members(prune_or_fr); BITMAP_delete(members, worker_id); - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(members, i) && ltt == BRANCH_LTT(i, depth)) { CUT_send_prune_request(i, prune_cp); } @@ -139,7 +138,7 @@ void prune_shared_branch(choiceptr prune_cp) { LOCK_OR_FRAME(leftmost_or_fr); members = OrFr_members(leftmost_or_fr); BITMAP_delete(members, worker_id); - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(members, i)) { if (ltt >= BRANCH_LTT(i, depth)) { CUT_send_prune_request(i, leftmost_cp->cp_b); @@ -231,7 +230,7 @@ void prune_shared_branch(choiceptr prune_cp) { ltt = BRANCH_LTT(worker_id, depth); LOCK_OR_FRAME(leftmost_or_fr); BITMAP_difference(members, OrFr_members(leftmost_or_fr), members); - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(members, i)) { if (ltt > BRANCH_LTT(i, depth)) { CUT_send_prune_request(i, leftmost_cp->cp_b); diff --git a/OPTYap/or.insts.i b/OPTYap/or.insts.i index 666a23763..e918e75cd 100644 --- a/OPTYap/or.insts.i +++ b/OPTYap/or.insts.i @@ -17,22 +17,22 @@ PBOp(getwork_first_time,e) /* wait for a new parallel goal */ - while (BITMAP_same(Yap_bm_present_workers, Yap_bm_finished_workers)); + while (BITMAP_same(GLOBAL_bm_present_workers, GLOBAL_bm_finished_workers)); make_root_choice_point(); PUT_IN_EXECUTING(worker_id); /* wait until everyone else is executing! */ - while (! BITMAP_same(Yap_bm_present_workers, Yap_bm_executing_workers)); + while (! BITMAP_same(GLOBAL_bm_present_workers, GLOBAL_bm_executing_workers)); SCHEDULER_GET_WORK(); shared_end: PUT_IN_FINISHED(worker_id); /* wait until everyone else is finished! */ - while (! BITMAP_same(Yap_bm_present_workers, Yap_bm_finished_workers)); + while (! BITMAP_same(GLOBAL_bm_present_workers, GLOBAL_bm_finished_workers)); PUT_OUT_EXECUTING(worker_id); if (worker_id == 0) { finish_yapor(); free_root_choice_point(); /* wait until no one is executing */ - while (! BITMAP_empty(Yap_bm_executing_workers)); + while (! BITMAP_empty(GLOBAL_bm_executing_workers)); goto fail; } else { PREG = GETWORK_FIRST_TIME; diff --git a/OPTYap/or.macros.h b/OPTYap/or.macros.h index 636dc1c0e..86413e474 100644 --- a/OPTYap/or.macros.h +++ b/OPTYap/or.macros.h @@ -88,7 +88,7 @@ STD_PROTO(static inline qg_sol_fr_ptr CUT_prune_solution_frames, (qg_sol_fr_ptr, #define PUT_YAMOP_SEQ(INST) (INST)->u.Otapl.or_arg |= YAMOP_SEQ_FLAG #define PUT_YAMOP_CUT(INST) (INST)->u.Otapl.or_arg |= YAMOP_CUT_FLAG -#define BRANCH(WORKER, DEPTH) Yap_branch(WORKER, DEPTH) +#define BRANCH(WORKER, DEPTH) GLOBAL_branch(WORKER, DEPTH) #define BRANCH_LTT(WORKER, DEPTH) (BRANCH(WORKER, DEPTH) & YAMOP_LTT_BITS) #define BRANCH_CUT(WORKER, DEPTH) (BRANCH(WORKER, DEPTH) & YAMOP_CUT_FLAG) @@ -108,7 +108,7 @@ STD_PROTO(static inline qg_sol_fr_ptr CUT_prune_solution_frames, (qg_sol_fr_ptr, ** Engine Macros ** ** ----------------------- */ -#define worker_offset(X) ((Yap_number_workers + X - worker_id) % Yap_number_workers * Yap_worker_area_size) +#define worker_offset(X) ((GLOBAL_number_workers + X - worker_id) % GLOBAL_number_workers * Yap_worker_area_size) #define LOCK_OR_FRAME(fr) LOCK(OrFr_lock(fr)) #define UNLOCK_OR_FRAME(fr) UNLOCK(OrFr_lock(fr)) @@ -177,7 +177,7 @@ STD_PROTO(static inline qg_sol_fr_ptr CUT_prune_solution_frames, (qg_sol_fr_ptr, } #define CUT_wait_leftmost() \ - if (Yap_parallel_execution_mode) { \ + if (GLOBAL_parallel_execution_mode) { \ /* parallel execution mode --> wait until leftmost */ \ int i, loop, depth, ltt; \ bitmap members; \ @@ -191,13 +191,13 @@ STD_PROTO(static inline qg_sol_fr_ptr CUT_prune_solution_frames, (qg_sol_fr_ptr, SCH_check_requests(); \ BITMAP_copy(members, OrFr_members(leftmost_or_fr)); \ BITMAP_delete(members, worker_id); \ - for (i = 0; i < Yap_number_workers; i++) { \ + for (i = 0; i < GLOBAL_number_workers; i++) { \ /* not leftmost in current frame if there is a */ \ /* worker in a left branch and it is not idle or */ \ /* if it is idle it is in a younger node */ \ if (BITMAP_member(members, i) && \ BRANCH_LTT(i, depth) > ltt && \ - (! BITMAP_member(Yap_bm_idle_workers, i) || \ + (! BITMAP_member(GLOBAL_bm_idle_workers, i) || \ leftmost_or_fr != REMOTE_top_or_fr(i))) { \ loop = TRUE; \ break; \ @@ -205,7 +205,7 @@ STD_PROTO(static inline qg_sol_fr_ptr CUT_prune_solution_frames, (qg_sol_fr_ptr, } \ } while (loop); \ leftmost_or_fr = OrFr_nearest_leftnode(leftmost_or_fr); \ - } while (leftmost_or_fr != Yap_root_or_fr); \ + } while (leftmost_or_fr != GLOBAL_root_or_fr); \ } @@ -216,27 +216,27 @@ STD_PROTO(static inline qg_sol_fr_ptr CUT_prune_solution_frames, (qg_sol_fr_ptr, static inline void PUT_IN_EXECUTING(int w) { - LOCK(Yap_locks_bm_executing_workers); - BITMAP_insert(Yap_bm_executing_workers, w); - UNLOCK(Yap_locks_bm_executing_workers); + LOCK(GLOBAL_locks_bm_executing_workers); + BITMAP_insert(GLOBAL_bm_executing_workers, w); + UNLOCK(GLOBAL_locks_bm_executing_workers); return; } static inline void PUT_OUT_EXECUTING(int w) { - LOCK(Yap_locks_bm_executing_workers); - BITMAP_delete(Yap_bm_executing_workers, w); - UNLOCK(Yap_locks_bm_executing_workers); + LOCK(GLOBAL_locks_bm_executing_workers); + BITMAP_delete(GLOBAL_bm_executing_workers, w); + UNLOCK(GLOBAL_locks_bm_executing_workers); return; } static inline void PUT_IN_FINISHED(int w) { - LOCK(Yap_locks_bm_finished_workers); - BITMAP_insert(Yap_bm_finished_workers, w); - UNLOCK(Yap_locks_bm_finished_workers); + LOCK(GLOBAL_locks_bm_finished_workers); + BITMAP_insert(GLOBAL_bm_finished_workers, w); + UNLOCK(GLOBAL_locks_bm_finished_workers); return; } @@ -244,18 +244,18 @@ void PUT_IN_FINISHED(int w) { #ifdef TABLING_INNER_CUTS static inline void PUT_IN_PRUNING(int w) { - LOCK(Yap_locks_bm_pruning_workers); - BITMAP_insert(Yap_bm_pruning_workers, w); - UNLOCK(Yap_locks_bm_pruning_workers); + LOCK(GLOBAL_locks_bm_pruning_workers); + BITMAP_insert(GLOBAL_bm_pruning_workers, w); + UNLOCK(GLOBAL_locks_bm_pruning_workers); return; } static inline void PUT_OUT_PRUNING(int w) { - LOCK(Yap_locks_bm_pruning_workers); - BITMAP_delete(Yap_bm_pruning_workers, w); - UNLOCK(Yap_locks_bm_pruning_workers); + LOCK(GLOBAL_locks_bm_pruning_workers); + BITMAP_delete(GLOBAL_bm_pruning_workers, w); + UNLOCK(GLOBAL_locks_bm_pruning_workers); return; } #endif /* TABLING_INNER_CUTS */ @@ -268,18 +268,18 @@ void PUT_OUT_PRUNING(int w) { static inline void PUT_IN_REQUESTABLE(int p) { - LOCK(Yap_locks_bm_requestable_workers); - BITMAP_insert(Yap_bm_requestable_workers, p); - UNLOCK(Yap_locks_bm_requestable_workers); + LOCK(GLOBAL_locks_bm_requestable_workers); + BITMAP_insert(GLOBAL_bm_requestable_workers, p); + UNLOCK(GLOBAL_locks_bm_requestable_workers); return; } static inline void PUT_OUT_REQUESTABLE(int p) { - LOCK(Yap_locks_bm_requestable_workers); - BITMAP_delete(Yap_bm_requestable_workers, p); - UNLOCK(Yap_locks_bm_requestable_workers); + LOCK(GLOBAL_locks_bm_requestable_workers); + BITMAP_delete(GLOBAL_bm_requestable_workers, p); + UNLOCK(GLOBAL_locks_bm_requestable_workers); return; } @@ -381,7 +381,7 @@ int CUT_last_worker_left_pending_prune(or_fr_ptr or_frame) { ltt = OrFr_pend_prune_ltt(or_frame); members = OrFr_members(or_frame); BITMAP_delete(members, worker_id); - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(members, i) && BRANCH_LTT(i, depth) > ltt) return FALSE; } @@ -404,7 +404,7 @@ or_fr_ptr CUT_leftmost_or_frame(void) { ltt = BRANCH_LTT(worker_id, depth); BITMAP_difference(members, OrFr_members(leftmost_or_fr), members); if (members) - for (i = 0; i < Yap_number_workers; i++) + for (i = 0; i < GLOBAL_number_workers; i++) if (BITMAP_member(members, i) && BRANCH_LTT(i, depth) > ltt) goto update_nearest_leftnode_data; BITMAP_copy(members, OrFr_members(leftmost_or_fr)); @@ -438,12 +438,12 @@ or_fr_ptr CUT_leftmost_until(or_fr_ptr start_or_fr, int until_depth) { leftmost_or_fr = OrFr_nearest_leftnode(start_or_fr); depth = OrFr_depth(leftmost_or_fr); if (depth > until_depth) { - BITMAP_copy(prune_members, Yap_bm_pruning_workers); + BITMAP_copy(prune_members, GLOBAL_bm_pruning_workers); BITMAP_delete(prune_members, worker_id); ltt = BRANCH_LTT(worker_id, depth); BITMAP_intersection(members, prune_members, OrFr_members(leftmost_or_fr)); if (members) { - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(members, i) && BRANCH_LTT(i, depth) > ltt && EQUAL_OR_YOUNGER_CP(GetOrFr_node(leftmost_or_fr), REMOTE_pruning_scope(i))) @@ -458,7 +458,7 @@ or_fr_ptr CUT_leftmost_until(or_fr_ptr start_or_fr, int until_depth) { ltt = BRANCH_LTT(worker_id, depth); BITMAP_intersection(members, prune_members, OrFr_members(leftmost_or_fr)); if (members) { - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(members, i) && BRANCH_LTT(i, depth) > ltt && EQUAL_OR_YOUNGER_CP(GetOrFr_node(leftmost_or_fr), REMOTE_pruning_scope(i))) { diff --git a/OPTYap/or.memory.c b/OPTYap/or.memory.c new file mode 100644 index 000000000..17c05b91a --- /dev/null +++ b/OPTYap/or.memory.c @@ -0,0 +1,254 @@ +/************************************************************************ +** ** +** The YapTab/YapOr/OPTYap systems ** +** ** +** YapTab extends the Yap Prolog engine to support sequential tabling ** +** YapOr extends the Yap Prolog engine to support or-parallelism ** +** OPTYap extends the Yap Prolog engine to support or-parallel tabling ** +** ** +** ** +** Yap Prolog was developed at University of Porto, Portugal ** +** ** +************************************************************************/ + +/************************************** +** Includes & Declarations ** +**************************************/ + +#include "Yap.h" +#if defined(YAPOR_COPY) || defined(YAPOR_COW) || defined(YAPOR_SBA) +#include +#include +#include +#include +#include +#include "Yatom.h" +#include "alloc.h" +#include "or.macros.h" + + + +/************************************ +** Macros & Declarations ** +************************************/ + +#define GLOBAL_LOCAL_STRUCTS_AREA ADJUST_SIZE_TO_PAGE(sizeof(struct global_data) + MAX_WORKERS * sizeof(struct worker_local)) + +#ifdef MMAP_MEMORY_MAPPING_SCHEME +int fd_mapfile; +#elif SHM_MEMORY_MAPPING_SCHEME +int shm_mapid[MAX_WORKERS + 2]; +#endif /* MEMORY_MAPPING_SCHEME */ + + + +/****************************************** +** Local functions declaration ** +******************************************/ + +#ifdef SHM_MEMORY_MAPPING_SCHEME +void shm_map_memory(int id, int size, void *shmaddr); +void shm_unmap_memory(int id); +#endif /* SHM_MEMORY_MAPPING_SCHEME */ + + + +/******************************** +** Global functions ** +********************************/ + +void Yap_init_yapor_global_local_memory(void) { + Yap_local = (struct worker_local *)(MMAP_ADDR - GLOBAL_LOCAL_STRUCTS_AREA); + Yap_global = (struct global_data *)(MMAP_ADDR - sizeof(struct global_data)); + +#ifdef MMAP_MEMORY_MAPPING_SCHEME + { char mapfile[20]; + strcpy(mapfile,"./mapfile"); + itos(getpid(), &mapfile[9]); + if ((fd_mapfile = open(mapfile, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0) + Yap_Error(FATAL_ERROR, TermNil, "open error (Yap_init_yapor_global_local_memory)"); + if (lseek(fd_mapfile, GLOBAL_LOCAL_STRUCTS_AREA, SEEK_SET) < 0) + Yap_Error(FATAL_ERROR, TermNil, "lseek error (Yap_init_yapor_global_local_memory)"); + if (write(fd_mapfile, "", 1) < 0) + Yap_Error(FATAL_ERROR, TermNil, "write error (Yap_init_yapor_global_local_memory)"); + if (mmap((void *) Yap_local, (size_t) GLOBAL_LOCAL_STRUCTS_AREA, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_FIXED, fd_mapfile, 0) == (void *) -1) + Yap_Error(FATAL_ERROR, TermNil, "mmap error (Yap_init_global_local_memory)"); + } +#elif SHM_MEMORY_MAPPING_SCHEME + /* place as segment MAX_WORKERS (0..MAX_WORKERS-1 reserved for worker areas) */ + shm_map_memory(MAX_WORKERS, GLOBAL_LOCAL_STRUCTS_AREA, (void *) Yap_local); +#endif /* MEMORY_MAPPING_SCHEME */ + + return; +} + + +void Yap_init_yapor_stacks_memory(long TrailStackArea, long HeapStackArea, long GlobalLocalStackArea, int n_workers) { + long StacksArea; + + TrailStackArea = ADJUST_SIZE_TO_PAGE(TrailStackArea); + HeapStackArea = ADJUST_SIZE_TO_PAGE(HeapStackArea); + GlobalLocalStackArea = ADJUST_SIZE_TO_PAGE(GlobalLocalStackArea); + Yap_worker_area_size = GlobalLocalStackArea + TrailStackArea; +#if defined(YAPOR_COPY) || defined(YAPOR_SBA) + StacksArea = HeapStackArea + Yap_worker_area_size * n_workers; +#elif defined(YAPOR_COW) + StacksArea = HeapStackArea; +#endif /* YAPOR_COPY || YAPOR_SBA || YAPOR_COW */ + + Yap_HeapBase = (ADDR) MMAP_ADDR; + LOCAL_GlobalBase = (ADDR) (MMAP_ADDR + HeapStackArea); + +#ifdef MMAP_MEMORY_MAPPING_SCHEME + /* map stacks in a single go */ + if (lseek(fd_mapfile, GLOBAL_LOCAL_STRUCTS_AREA + StacksArea, SEEK_SET) < 0) + Yap_Error(FATAL_ERROR, TermNil, "lseek error (Yap_init_yapor_stacks_memory)"); + if (write(fd_mapfile, "", 1) < 0) + Yap_Error(FATAL_ERROR, TermNil, "write error (Yap_init_yapor_stacks_memory)"); + if (mmap((void *) Yap_HeapBase, (size_t) StacksArea, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_FIXED, fd_mapfile, GLOBAL_LOCAL_STRUCTS_AREA) == (void *) -1) + Yap_Error(FATAL_ERROR, TermNil, "mmap error (Yap_init_yapor_stacks_memory)"); +#elif SHM_MEMORY_MAPPING_SCHEME + /* place heap stack segment as MAX_WORKERS+1 */ + shm_map_memory(MAX_WORKERS + 1, HeapStackArea, (void *) Yap_HeapBase); +#if defined(YAPOR_COPY) || defined(YAPOR_SBA) + /* map segments for worker areas as 0..MAX_WORKERS-1 */ + { int i; + for (i = 0; i < n_workers; i++) + shm_map_memory(i, Yap_worker_area_size, LOCAL_GlobalBase + Yap_worker_area_size * i); + } +#endif /* YAPOR_COPY || YAPOR_SBA */ +#endif /* MEMORY_MAPPING_SCHEME */ + +#ifdef YAPOR_COW + /* just allocate local space for stacks */ + { int private_fd_mapfile; + if ((private_fd_mapfile = open("/dev/zero", O_RDWR)) < 0) + Yap_Error(FATAL_ERROR, TermNil, "open error (Yap_init_yapor_stacks_memory)"); + if (mmap(LOCAL_GlobalBase, Yap_worker_area_size, PROT_READ|PROT_WRITE, + MAP_PRIVATE|MAP_FIXED, private_fd_mapfile, 0) == (void *) -1) + Yap_Error(FATAL_ERROR, TermNil, "mmap error (Yap_init_yapor_stacks_memory)"); + close(private_fd_mapfile); + } +#endif /* YAPOR_COW */ + +#ifdef YAPOR_SBA + /* alloc space for the sparse binding array */ + sba_size = Yap_worker_area_size * n_workers; + if ((binding_array = (char *)malloc(sba_size)) == NULL) + Yap_Error(FATAL_ERROR, TermNil, "malloc error (Yap_init_yapor_stacks_memory)"); + if ((CELL)binding_array & MBIT) + Yap_Error(INTERNAL_ERROR, TermNil, "binding_array start address conflicts with tag used in IDB (Yap_init_yapor_stacks_memory)"); + sba_offset = binding_array - LOCAL_GlobalBase; + sba_end = (int)binding_array + sba_size; +#endif /* YAPOR_SBA */ + + LOCAL_TrailBase = LOCAL_GlobalBase + GlobalLocalStackArea; + LOCAL_LocalBase = LOCAL_TrailBase - CellSize; + LOCAL_TrailTop = LOCAL_TrailBase + TrailStackArea; + HeapLim = LOCAL_GlobalBase; + Yap_InitHeap(Yap_HeapBase); + return; +} + + +void Yap_remap_yapor_memory(void) { +#if defined(YAPOR_COPY) + int i; + void *remap_addr = LOCAL_GlobalBase; +#ifdef MMAP_MEMORY_MAPPING_SCHEME + long remap_offset = (ADDR) remap_addr - (ADDR) Yap_local; + if (munmap(remap_addr, (size_t)(Yap_worker_area_size * GLOBAL_number_workers)) == -1) + Yap_Error(FATAL_ERROR, TermNil, "munmap error (Yap_remap_yapor_memory)"); + for (i = 0; i < GLOBAL_number_workers; i++) + if (mmap(remap_addr + worker_offset(i), (size_t)Yap_worker_area_size, PROT_READ|PROT_WRITE, + MAP_SHARED|MAP_FIXED, fd_mapfile, remap_offset + i * Yap_worker_area_size) == (void *) -1) + Yap_Error(FATAL_ERROR, TermNil, "mmap error (Yap_remap_yapor_memory)"); +#else /* SHM_MEMORY_MAPPING_SCHEME */ + for (i = 0; i < GLOBAL_number_workers; i++) + if (shmdt(remap_addr + Yap_worker_area_size * i) == -1) + Yap_Error(FATAL_ERROR, TermNil, "shmdt error (Yap_remap_yapor_memory)"); + for (i = 0; i < GLOBAL_number_workers; i++) + if(shmat(shm_mapid[i], remap_addr + worker_offset(i), 0) == (void *) -1) + Yap_Error(FATAL_ERROR, TermNil, "shmat error (Yap_remap_yapor_memory)"); +#endif /* MEMORY_MAPPING_SCHEME */ +#elif defined(YAPOR_SBA) + /* setup workers so that they have different areas */ + LOCAL_GlobalBase += worker_id * Yap_worker_area_size; + LOCAL_TrailBase += worker_id * Yap_worker_area_size; + LOCAL_LocalBase += worker_id * Yap_worker_area_size; + LOCAL_TrailTop += worker_id * Yap_worker_area_size; +#endif /* YAPOR_COPY || YAPOR_SBA */ +} + + +void Yap_unmap_yapor_memory (void) { + int i; + + INFORMATION_MESSAGE("Worker %d exiting...", worker_id); + for (i = 0; i < GLOBAL_number_workers; i++) + if (i != worker_id && GLOBAL_worker_pid(i) != 0) { + if (kill(GLOBAL_worker_pid(i), SIGKILL) != 0) + INFORMATION_MESSAGE("Can't kill process %d", GLOBAL_worker_pid(i)); + else + INFORMATION_MESSAGE("Killing process %d", GLOBAL_worker_pid(i)); + } +#ifdef YAPOR_COW + if (GLOBAL_number_workers > 1) { + if (kill(GLOBAL_master_worker, SIGINT) != 0) + INFORMATION_MESSAGE("Can't kill process %d", GLOBAL_master_worker); + else + INFORMATION_MESSAGE("Killing process %d", GLOBAL_master_worker); + } +#endif /* YAPOR_COW */ + +#ifdef MMAP_MEMORY_MAPPING_SCHEME + { char mapfile[20]; + strcpy(mapfile,"./mapfile"); +#if defined(YAPOR_COPY) || defined(YAPOR_SBA) + itos(GLOBAL_worker_pid(0), &mapfile[9]); +#elif defined(YAPOR_COW) + itos(GLOBAL_master_worker, &mapfile[9]); +#endif /* YAPOR_COPY || YAPOR_SBA || YAPOR_COW */ + if (remove(mapfile) == 0) + INFORMATION_MESSAGE("Removing mapfile \"%s\"", mapfile); + else + INFORMATION_MESSAGE("Can't remove mapfile \"%s\"", mapfile); + } +#elif SHM_MEMORY_MAPPING_SCHEME +#if defined(YAPOR_COPY) || defined(YAPOR_SBA) + shm_unmap_memory(MAX_WORKERS); + shm_unmap_memory(MAX_WORKERS + 1); + for (i = 0; i < GLOBAL_number_workers; i++) + shm_unmap_memory(i); +#elif defined(YAPOR_COW) + shm_unmap_memory(0); +#endif /* YAPOR_COPY || YAPOR_SBA || YAPOR_COW */ +#endif /* MEMORY_MAPPING_SCHEME */ + return; +} + + + +/* ------------------------- ** +** Local functions ** +** ------------------------- */ + +#ifdef SHM_MEMORY_MAPPING_SCHEME +void shm_map_memory(int id, int size, void *shmaddr) { + if ((shm_mapid[id] = shmget(IPC_PRIVATE, size, SHM_R|SHM_W)) == -1) + Yap_Error(FATAL_ERROR, TermNil, "shmget error (shm_map_memory)"); + if (shmat(shm_mapid[id], shmaddr, 0) == (void *) -1) + Yap_Error(FATAL_ERROR, TermNil, "shmat error (shm_map_memory)"); + return; +} + + +void shm_unmap_memory(int id) { + if (shmctl(shm_mapid[id], IPC_RMID, 0) == 0) + INFORMATION_MESSAGE("Removing shared memory segment %d", shm_mapid[id]); + else + INFORMATION_MESSAGE("Can't remove shared memory segment %d", shm_mapid[id]); + return; +} +#endif /* SHM_MEMORY_MAPPING_SCHEME */ +#endif /* YAPOR_COPY || YAPOR_COW || YAPOR_SBA */ diff --git a/OPTYap/or.sba_amiops.h b/OPTYap/or.sba_amiops.h index 7d534b8b8..c5224f25a 100644 --- a/OPTYap/or.sba_amiops.h +++ b/OPTYap/or.sba_amiops.h @@ -66,7 +66,6 @@ Dereferencing macros if (0 == (D)) break; \ if (IsPairTerm(D)) goto LabelList; \ } while (TRUE); - #endif /* UNIQUE_TAG_FOR_PAIRS */ EXTERN inline Term Deref(Term a) @@ -108,6 +107,7 @@ A contains the address of the variable that is to be trailed #define RESET_VARIABLE(V) (*(CELL *)(V) = 0) +#if SIZEOF_DOUBLE == 2*SIZEOF_LONG_INT inline EXTERN void AlignGlobalForDouble(void) { @@ -118,6 +118,7 @@ AlignGlobalForDouble(void) H++; } } +#endif /* SIZEOF_DOUBLE == 2*SIZEOF_LONG_INT */ #ifdef YAPOR diff --git a/OPTYap/or.sba_engine.c b/OPTYap/or.sba_engine.c index 8992a66ec..08747bd34 100644 --- a/OPTYap/or.sba_engine.c +++ b/OPTYap/or.sba_engine.c @@ -87,21 +87,21 @@ reset_trail(tr_fr_ptr tr_top, tr_fr_ptr trp) void make_root_choice_point(void) { if (worker_id == 0) { - LOCAL_top_cp = Yap_root_cp = OrFr_node(Yap_root_or_fr) = B; + LOCAL_top_cp = GLOBAL_root_cp = OrFr_node(GLOBAL_root_or_fr) = B; B->cp_h = H0; B->cp_ap = GETWORK; - B->cp_or_fr = Yap_root_or_fr; + B->cp_or_fr = GLOBAL_root_or_fr; } else { - B = LOCAL_top_cp = Yap_root_cp; + B = LOCAL_top_cp = GLOBAL_root_cp; TR = B->cp_tr; } - LOCAL_top_or_fr = Yap_root_or_fr; + LOCAL_top_or_fr = GLOBAL_root_or_fr; LOCAL_load = 0; LOCAL_prune_request = NULL; BRANCH(worker_id, 0) = 0; - H_FZ = (CELL *) Yap_GlobalBase; - B_FZ = (choiceptr) Yap_LocalBase; - TR_FZ = (tr_fr_ptr) Yap_TrailBase; + H_FZ = (CELL *) LOCAL_GlobalBase; + B_FZ = (choiceptr) LOCAL_LocalBase; + TR_FZ = (tr_fr_ptr) LOCAL_TrailBase; } @@ -109,10 +109,10 @@ void free_root_choice_point(void) { reset_trail(LOCAL_top_cp->cp_tr, TR); TR = LOCAL_top_cp->cp_tr; B = LOCAL_top_cp->cp_b; - LOCAL_top_cp = (choiceptr) Yap_LocalBase; - H_FZ = (CELL *) Yap_GlobalBase; - B_FZ = (choiceptr) Yap_LocalBase; - TR_FZ = (tr_fr_ptr) Yap_TrailBase; + LOCAL_top_cp = (choiceptr) LOCAL_LocalBase; + H_FZ = (CELL *) LOCAL_GlobalBase; + B_FZ = (choiceptr) LOCAL_LocalBase; + TR_FZ = (tr_fr_ptr) LOCAL_TrailBase; } @@ -121,7 +121,7 @@ void p_share_work(void) { if (! BITMAP_member(OrFr_members(REMOTE_top_or_fr(worker_q)), worker_id) || B == REMOTE_top_cp(worker_q) || - (LOCAL_load <= Yap_delayed_release_load && OrFr_nearest_livenode(LOCAL_top_or_fr) == NULL)) { + (LOCAL_load <= GLOBAL_delayed_release_load && OrFr_nearest_livenode(LOCAL_top_or_fr) == NULL)) { /* refuse sharing request */ REMOTE_reply_signal(LOCAL_share_request) = no_sharing; LOCAL_share_request = MAX_WORKERS; @@ -163,7 +163,7 @@ int q_share_work(int worker_p) { /* make sharing request */ LOCK_WORKER(worker_p); - if (BITMAP_member(Yap_bm_idle_workers, worker_p) || + if (BITMAP_member(GLOBAL_bm_idle_workers, worker_p) || REMOTE_share_request(worker_p) != MAX_WORKERS) { /* worker p is idle or has another request */ UNLOCK_WORKER(worker_p); diff --git a/OPTYap/or.sba_unify.h b/OPTYap/or.sba_unify.h index b2bcf8362..d5d640596 100644 --- a/OPTYap/or.sba_unify.h +++ b/OPTYap/or.sba_unify.h @@ -37,9 +37,6 @@ Int bind_variable(Term t0, Term t1) } EXTERN inline -/* -Int unify(Term t0, Term t1) -*/ Int unify(Term t0, Term t1) { tr_fr_ptr TR0 = TR; @@ -69,7 +66,7 @@ EXTERN inline Int unify_constant(register Term a, register Term cons) return(IsLongIntTerm(cons) && LongIntOfTerm(a) == LongIntOfTerm(cons)); #ifdef TERM_EXTENSIONS } else if (IsAttachFunc(fun)) { - return(attas[ExtFromFunctor(fun)].bind_op(SBIND,a,cons)); + return(GLOBAL_attas[ExtFromFunctor(fun)].bind_op(SBIND,a,cons)); #endif /* TERM_EXTENSIONS */ } else return(FALSE); diff --git a/OPTYap/or.scheduler.c b/OPTYap/or.scheduler.c index 8931bb8e6..fbea6ab3d 100644 --- a/OPTYap/or.scheduler.c +++ b/OPTYap/or.scheduler.c @@ -65,36 +65,36 @@ void PUT_NO_WORK_IN_UPPER_NODES(void) { static inline void PUT_IDLE(int worker_num) { - LOCK(Yap_locks_bm_idle_workers); - BITMAP_insert(Yap_bm_idle_workers, worker_num); - UNLOCK(Yap_locks_bm_idle_workers); + LOCK(GLOBAL_locks_bm_idle_workers); + BITMAP_insert(GLOBAL_bm_idle_workers, worker_num); + UNLOCK(GLOBAL_locks_bm_idle_workers); return; } static inline void PUT_BUSY(int worker_num) { - LOCK(Yap_locks_bm_idle_workers); - BITMAP_delete(Yap_bm_idle_workers, worker_num); - UNLOCK(Yap_locks_bm_idle_workers); + LOCK(GLOBAL_locks_bm_idle_workers); + BITMAP_delete(GLOBAL_bm_idle_workers, worker_num); + UNLOCK(GLOBAL_locks_bm_idle_workers); return; } static inline void PUT_IN_ROOT_NODE(int worker_num) { - LOCK(Yap_locks_bm_root_cp_workers); - BITMAP_insert(Yap_bm_root_cp_workers, worker_num); - UNLOCK(Yap_locks_bm_root_cp_workers); + LOCK(GLOBAL_locks_bm_root_cp_workers); + BITMAP_insert(GLOBAL_bm_root_cp_workers, worker_num); + UNLOCK(GLOBAL_locks_bm_root_cp_workers); return; } static inline void PUT_OUT_ROOT_NODE(int worker_num) { - LOCK(Yap_locks_bm_root_cp_workers); - BITMAP_delete(Yap_bm_root_cp_workers, worker_num); - UNLOCK(Yap_locks_bm_root_cp_workers); + LOCK(GLOBAL_locks_bm_root_cp_workers); + BITMAP_delete(GLOBAL_bm_root_cp_workers, worker_num); + UNLOCK(GLOBAL_locks_bm_root_cp_workers); return; } @@ -215,21 +215,21 @@ int get_work(void) { SCH_refuse_share_request_if_any(); counter = 0; - BITMAP_difference(stable_busy, OrFr_members(LOCAL_top_or_fr), Yap_bm_idle_workers); + BITMAP_difference(stable_busy, OrFr_members(LOCAL_top_or_fr), GLOBAL_bm_idle_workers); while (1) { - while (BITMAP_subset(Yap_bm_idle_workers, OrFr_members(LOCAL_top_or_fr)) && - Get_LOCAL_top_cp() != Get_Yap_root_cp()) { + while (BITMAP_subset(GLOBAL_bm_idle_workers, OrFr_members(LOCAL_top_or_fr)) && + Get_LOCAL_top_cp() != Get_GLOBAL_root_cp()) { /* no busy workers here and below */ if (! move_up_one_node(NULL)) { PUT_BUSY(worker_id); return TRUE; } } - if (Get_LOCAL_top_cp() == Get_Yap_root_cp()) { - if (! BITMAP_member(Yap_bm_root_cp_workers, worker_id)) + if (Get_LOCAL_top_cp() == Get_GLOBAL_root_cp()) { + if (! BITMAP_member(GLOBAL_bm_root_cp_workers, worker_id)) PUT_IN_ROOT_NODE(worker_id); - if (BITMAP_same(Yap_bm_idle_workers, Yap_bm_root_cp_workers) && - BITMAP_same(Yap_bm_idle_workers, Yap_bm_present_workers)) { + if (BITMAP_same(GLOBAL_bm_idle_workers, GLOBAL_bm_root_cp_workers) && + BITMAP_same(GLOBAL_bm_idle_workers, GLOBAL_bm_present_workers)) { /* All workers are idle in root choicepoint. Execution must finish as there is no available computation. */ return FALSE; @@ -247,15 +247,15 @@ int get_work(void) { PUT_BUSY(worker_id); return TRUE; } - if (++counter == Yap_scheduler_loop) { + if (++counter == GLOBAL_scheduler_loop) { if (search_for_hidden_shared_work(stable_busy)) { PUT_BUSY(worker_id); return TRUE; } counter = 0; - BITMAP_difference(stable_busy, OrFr_members(LOCAL_top_or_fr), Yap_bm_idle_workers); + BITMAP_difference(stable_busy, OrFr_members(LOCAL_top_or_fr), GLOBAL_bm_idle_workers); } else { - BITMAP_minus(stable_busy, Yap_bm_idle_workers); + BITMAP_minus(stable_busy, GLOBAL_bm_idle_workers); } } } @@ -347,7 +347,7 @@ int move_up_one_node(or_fr_ptr nearest_livenode) { if (OrFr_suspensions(LOCAL_top_or_fr)) { susp_fr_ptr resume_fr; #ifdef TIMESTAMP_CHECK - resume_fr = suspension_frame_to_resume(LOCAL_top_or_fr, ++Yap_timestamp); + resume_fr = suspension_frame_to_resume(LOCAL_top_or_fr, ++GLOBAL_timestamp); #else resume_fr = suspension_frame_to_resume(LOCAL_top_or_fr); #endif /* TIMESTAMP_CHECK */ @@ -528,18 +528,18 @@ int get_work_below(void){ bitmap busy_below, idle_below; worker_p = -1; - big_load = Yap_delayed_release_load ; - BITMAP_difference(busy_below, OrFr_members(LOCAL_top_or_fr), Yap_bm_idle_workers); + big_load = GLOBAL_delayed_release_load ; + BITMAP_difference(busy_below, OrFr_members(LOCAL_top_or_fr), GLOBAL_bm_idle_workers); BITMAP_difference(idle_below, OrFr_members(LOCAL_top_or_fr), busy_below); BITMAP_delete(idle_below, worker_id); - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(idle_below ,i) && YOUNGER_CP(REMOTE_top_cp(i), Get_LOCAL_top_cp())) BITMAP_minus(busy_below, OrFr_members(REMOTE_top_or_fr(i))); } if (BITMAP_empty(busy_below)) return FALSE; /* choose the worker with highest load */ - for (i = 0 ; i < Yap_number_workers; i++) { + for (i = 0 ; i < GLOBAL_number_workers; i++) { if (BITMAP_member(busy_below ,i) && REMOTE_load(i) > big_load) { worker_p = i; big_load = REMOTE_load(i); @@ -558,14 +558,14 @@ int get_work_above(void){ bitmap visible_busy_above, visible_idle_above; worker_p = -1; - big_load = Yap_delayed_release_load ; - BITMAP_difference(visible_busy_above, Yap_bm_present_workers, OrFr_members(LOCAL_top_or_fr)); - BITMAP_minus(visible_busy_above, Yap_bm_invisible_workers); + big_load = GLOBAL_delayed_release_load ; + BITMAP_difference(visible_busy_above, GLOBAL_bm_present_workers, OrFr_members(LOCAL_top_or_fr)); + BITMAP_minus(visible_busy_above, GLOBAL_bm_invisible_workers); BITMAP_copy(visible_idle_above, visible_busy_above); - BITMAP_minus(visible_busy_above, Yap_bm_idle_workers); - BITMAP_and(visible_idle_above, Yap_bm_idle_workers); + BITMAP_minus(visible_busy_above, GLOBAL_bm_idle_workers); + BITMAP_and(visible_idle_above, GLOBAL_bm_idle_workers); BITMAP_insert(visible_busy_above, worker_id); - for (i = 0 ; i < Yap_number_workers; i++) { + for (i = 0 ; i < GLOBAL_number_workers; i++) { if (BITMAP_member(visible_idle_above, i)) BITMAP_minus(visible_busy_above, OrFr_members(REMOTE_top_or_fr(i))); } @@ -573,7 +573,7 @@ int get_work_above(void){ return FALSE; BITMAP_delete(visible_busy_above, worker_id); /* choose the worker with higher load */ - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(visible_busy_above ,i) && REMOTE_load(i) > big_load) { worker_p = i; big_load = REMOTE_load(i); @@ -582,14 +582,14 @@ int get_work_above(void){ if (worker_p == -1) return FALSE; /* put workers invisibles */ - LOCK(Yap_locks_bm_invisible_workers); - if (BITMAP_member(Yap_bm_invisible_workers, worker_p)) { - UNLOCK(Yap_locks_bm_invisible_workers); + LOCK(GLOBAL_locks_bm_invisible_workers); + if (BITMAP_member(GLOBAL_bm_invisible_workers, worker_p)) { + UNLOCK(GLOBAL_locks_bm_invisible_workers); return FALSE; } - BITMAP_insert(Yap_bm_invisible_workers, worker_id); - BITMAP_insert(Yap_bm_invisible_workers, worker_p); - UNLOCK(Yap_locks_bm_invisible_workers); + BITMAP_insert(GLOBAL_bm_invisible_workers, worker_id); + BITMAP_insert(GLOBAL_bm_invisible_workers, worker_p); + UNLOCK(GLOBAL_locks_bm_invisible_workers); /* move up to cp with worker_p */ do { if (! move_up_one_node(NULL)) { @@ -597,10 +597,10 @@ int get_work_above(void){ } } while (! BITMAP_member(OrFr_members(LOCAL_top_or_fr), worker_p)); /* put workers visibles */ - LOCK(Yap_locks_bm_invisible_workers); - BITMAP_delete(Yap_bm_invisible_workers, worker_id); - BITMAP_delete(Yap_bm_invisible_workers, worker_p); - UNLOCK(Yap_locks_bm_invisible_workers); + LOCK(GLOBAL_locks_bm_invisible_workers); + BITMAP_delete(GLOBAL_bm_invisible_workers, worker_id); + BITMAP_delete(GLOBAL_bm_invisible_workers, worker_p); + UNLOCK(GLOBAL_locks_bm_invisible_workers); return (q_share_work(worker_p)); } @@ -610,11 +610,11 @@ int find_a_better_position(void){ CACHE_REGS int i; bitmap busy_above, idle_above; - BITMAP_difference(busy_above, Yap_bm_present_workers, OrFr_members(LOCAL_top_or_fr)); + BITMAP_difference(busy_above, GLOBAL_bm_present_workers, OrFr_members(LOCAL_top_or_fr)); BITMAP_copy(idle_above, busy_above); - BITMAP_minus(busy_above, Yap_bm_idle_workers); - BITMAP_and(idle_above, Yap_bm_idle_workers); - for (i = 0; i < Yap_number_workers; i++) { + BITMAP_minus(busy_above, GLOBAL_bm_idle_workers); + BITMAP_and(idle_above, GLOBAL_bm_idle_workers); + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(idle_above, i)) { if (BITMAP_empty(busy_above)) break; @@ -640,17 +640,17 @@ int search_for_hidden_shared_work(bitmap stable_busy){ CACHE_REGS int i; bitmap invisible_work, idle_below; - BITMAP_intersection(invisible_work, stable_busy, Yap_bm_requestable_workers); - BITMAP_intersection(idle_below, OrFr_members(LOCAL_top_or_fr), Yap_bm_idle_workers); + BITMAP_intersection(invisible_work, stable_busy, GLOBAL_bm_requestable_workers); + BITMAP_intersection(idle_below, OrFr_members(LOCAL_top_or_fr), GLOBAL_bm_idle_workers); BITMAP_delete(idle_below, worker_id); - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(idle_below ,i) && YOUNGER_CP(REMOTE_top_cp(i), Get_LOCAL_top_cp())) BITMAP_minus(invisible_work, OrFr_members(REMOTE_top_or_fr(i))); } if (BITMAP_empty(invisible_work)) return FALSE; /* choose the first available worker */ - for (i = 0; i < Yap_number_workers; i++ ) { + for (i = 0; i < GLOBAL_number_workers; i++ ) { if (BITMAP_member(invisible_work ,i)) break; } diff --git a/OPTYap/or.thread_engine.c b/OPTYap/or.thread_engine.c index 3b1c85710..8bf584646 100644 --- a/OPTYap/or.thread_engine.c +++ b/OPTYap/or.thread_engine.c @@ -53,30 +53,30 @@ static void share_private_nodes(int worker_q); void make_root_choice_point(void) { CACHE_REGS if (worker_id == 0) { - SetOrFr_node(Yap_root_or_fr, B); + SetOrFr_node(GLOBAL_root_or_fr, B); Set_LOCAL_top_cp(B); - Set_Yap_root_cp(B); + Set_GLOBAL_root_cp(B); } else { choiceptr imageB; - Set_LOCAL_top_cp(Get_Yap_root_cp()); - B = Get_Yap_root_cp(); + Set_LOCAL_top_cp(Get_GLOBAL_root_cp()); + B = Get_GLOBAL_root_cp(); /* this is tricky, we need to get the B from some other stack and convert back to our own stack; */ - OldLCL0 = LCL0; - LCL0 = FOREIGN_ThreadHandle(0).current_yaam_regs->LCL0_; - imageB = Get_Yap_root_cp(); + LOCAL_OldLCL0 = LCL0; + LCL0 = REMOTE_ThreadHandle(0).current_yaam_regs->LCL0_; + imageB = Get_GLOBAL_root_cp(); /* we know B */ B->cp_tr = TR = - (tr_fr_ptr)((CELL)(imageB->cp_tr)+((CELL)OldLCL0-(CELL)LCL0)); - LCL0 = OldLCL0; + (tr_fr_ptr)((CELL)(imageB->cp_tr)+((CELL)LOCAL_OldLCL0-(CELL)LCL0)); + LCL0 = LOCAL_OldLCL0; } B->cp_h = H0; B->cp_ap = GETWORK; - B->cp_or_fr = Yap_root_or_fr; - LOCAL_top_or_fr = Yap_root_or_fr; + B->cp_or_fr = GLOBAL_root_or_fr; + LOCAL_top_or_fr = GLOBAL_root_or_fr; LOCAL_load = 0; Set_LOCAL_prune_request(NULL); BRANCH(worker_id, 0) = 0; @@ -95,11 +95,11 @@ void free_root_choice_point(void) { CACHE_REGS B = Get_LOCAL_top_cp()->cp_b; #ifdef TABLING - Set_LOCAL_top_cp_on_stack((choiceptr) Yap_LocalBase); + Set_LOCAL_top_cp_on_stack((choiceptr) LOCAL_LocalBase); #endif /* TABLING */ - Set_Yap_root_cp((choiceptr) Yap_LocalBase); - Set_LOCAL_top_cp((choiceptr) Yap_LocalBase); - SetOrFr_node(Yap_root_or_fr, (choiceptr) Yap_LocalBase); + Set_GLOBAL_root_cp((choiceptr) LOCAL_LocalBase); + Set_LOCAL_top_cp((choiceptr) LOCAL_LocalBase); + SetOrFr_node(GLOBAL_root_or_fr, (choiceptr) LOCAL_LocalBase); return; } @@ -110,7 +110,7 @@ int p_share_work() { if (! BITMAP_member(OrFr_members(REMOTE_top_or_fr(worker_q)), worker_id) || B == REMOTE_top_cp(worker_q) || - (LOCAL_load <= Yap_delayed_release_load && OrFr_nearest_livenode(LOCAL_top_or_fr) == NULL)) { + (LOCAL_load <= GLOBAL_delayed_release_load && OrFr_nearest_livenode(LOCAL_top_or_fr) == NULL)) { /* refuse sharing request */ REMOTE_reply_signal(LOCAL_share_request) = no_sharing; LOCAL_share_request = MAX_WORKERS; @@ -157,7 +157,7 @@ int q_share_work(int worker_p) { /* make sharing request */ LOCK_WORKER(worker_p); - if (BITMAP_member(Yap_bm_idle_workers, worker_p) || + if (BITMAP_member(GLOBAL_bm_idle_workers, worker_p) || REMOTE_share_request(worker_p) != MAX_WORKERS) { /* worker p is idle or has another request */ UNLOCK_WORKER(worker_p); @@ -282,7 +282,7 @@ void share_private_nodes(int worker_q) { consumer_cp = DepFr_cons_cp(dep_frame); next_node_on_branch = NULL; stack_limit = (CELL *)TR; - stack = (CELL *)Yap_TrailTop; + stack = (CELL *)LOCAL_TrailTop; #endif /* TABLING */ /* initialize auxiliary variables */ @@ -388,7 +388,7 @@ void share_private_nodes(int worker_q) { #ifdef TABLING /* update or-frames stored in auxiliary stack */ - while (STACK_NOT_EMPTY(stack, (CELL *)Yap_TrailTop)) { + while (STACK_NOT_EMPTY(stack, (CELL *)LOCAL_TrailTop)) { next_node_on_branch = (choiceptr) STACK_POP_DOWN(stack); or_frame = (or_fr_ptr) STACK_POP_DOWN(stack); OrFr_nearest_livenode(or_frame) = OrFr_next(or_frame) = next_node_on_branch->cp_or_fr; @@ -497,7 +497,7 @@ void share_private_nodes(int worker_q) { #ifdef DEBUG_OPTYAP { dep_fr_ptr aux_dep_fr = LOCAL_top_dep_fr; - while(aux_dep_fr != Yap_root_dep_fr) { + while(aux_dep_fr != GLOBAL_root_dep_fr) { choiceptr top_cp_on_branch; top_cp_on_branch = DepFr_cons_cp(aux_dep_fr); while (YOUNGER_CP(top_cp_on_branch, B)) { diff --git a/OPTYap/tab.insts.i b/OPTYap/tab.insts.i index 5a7742b69..9555ab6a0 100644 --- a/OPTYap/tab.insts.i +++ b/OPTYap/tab.insts.i @@ -304,7 +304,7 @@ -> we need a shared data structure to avoid redundant computations! UNLOCK_OR_FRAME(LOCAL_top_or_fr); #else - fprintf(stderr,"PROBLEM: cp_last_answer field is local to the cp!\n"); + Sfprintf(Serror, "PROBLEM: cp_last_answer field is local to the cp!\n"); exit(1); #endif } @@ -442,7 +442,7 @@ find_leader_node(leader_cp, leader_dep_on_stack); store_consumer_node(tab_ent, sg_fr, leader_cp, leader_dep_on_stack); #ifdef DEBUG_OPTYAP - if (Yap_parallel_execution_mode) { + if (GLOBAL_parallel_execution_mode) { choiceptr aux_cp; aux_cp = B; while (YOUNGER_CP(aux_cp, Get_LOCAL_top_cp_on_stack())) @@ -553,7 +553,7 @@ find_leader_node(leader_cp, leader_dep_on_stack); store_consumer_node(tab_ent, sg_fr, leader_cp, leader_dep_on_stack); #ifdef DEBUG_OPTYAP - if (Yap_parallel_execution_mode) { + if (GLOBAL_parallel_execution_mode) { choiceptr aux_cp; aux_cp = B; while (YOUNGER_CP(aux_cp, Get_LOCAL_top_cp_on_stack())) @@ -664,7 +664,7 @@ find_leader_node(leader_cp, leader_dep_on_stack); store_consumer_node(tab_ent, sg_fr, leader_cp, leader_dep_on_stack); #ifdef DEBUG_OPTYAP - if (Yap_parallel_execution_mode) { + if (GLOBAL_parallel_execution_mode) { choiceptr aux_cp; aux_cp = B; while (YOUNGER_CP(aux_cp, Get_LOCAL_top_cp_on_stack())) @@ -878,7 +878,7 @@ /* new answer */ #ifdef TABLING_INNER_CUTS /* check for potencial prunings */ - if (! BITMAP_empty(Yap_bm_pruning_workers)) { + if (! BITMAP_empty(GLOBAL_bm_pruning_workers)) { int until_depth, depth; until_depth = OrFr_depth(SgFr_gen_top_or_fr(sg_fr)); @@ -888,12 +888,12 @@ bitmap prune_members, members; or_fr_ptr leftmost_or_fr, or_fr, nearest_or_fr; - BITMAP_copy(prune_members, Yap_bm_pruning_workers); + BITMAP_copy(prune_members, GLOBAL_bm_pruning_workers); BITMAP_delete(prune_members, worker_id); ltt = BRANCH_LTT(worker_id, depth); BITMAP_intersection(members, prune_members, OrFr_members(LOCAL_top_or_fr)); if (members) { - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(members, i) && BRANCH_LTT(i, depth) > ltt && EQUAL_OR_YOUNGER_CP(Get_LOCAL_top_cp(), REMOTE_pruning_scope(i))) { @@ -939,7 +939,7 @@ ltt = BRANCH_LTT(worker_id, depth); BITMAP_intersection(members, prune_members, OrFr_members(leftmost_or_fr)); if (members) { - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(members, i) && BRANCH_LTT(i, depth) > ltt && EQUAL_OR_YOUNGER_CP(GetOrFr_node(leftmost_or_fr), REMOTE_pruning_scope(i))) @@ -954,7 +954,7 @@ ltt = BRANCH_LTT(worker_id, depth); BITMAP_intersection(members, prune_members, OrFr_members(leftmost_or_fr)); if (members) { - for (i = 0; i < Yap_number_workers; i++) { + for (i = 0; i < GLOBAL_number_workers; i++) { if (BITMAP_member(members, i) && BRANCH_LTT(i, depth) > ltt && EQUAL_OR_YOUNGER_CP(GetOrFr_node(leftmost_or_fr), REMOTE_pruning_scope(i))) { @@ -1213,7 +1213,7 @@ } #endif /* YAPOR */ #ifdef DEBUG_OPTYAP - if (Yap_parallel_execution_mode) { + if (GLOBAL_parallel_execution_mode) { choiceptr aux_cp; OPTYAP_ERROR_CHECKING(completion, YOUNGER_CP(Get_LOCAL_top_cp(), Get_LOCAL_top_cp_on_stack())); aux_cp = chain_cp; @@ -1284,7 +1284,7 @@ } #endif /* YAPOR */ #ifdef DEBUG_OPTYAP - if (Yap_parallel_execution_mode) { + if (GLOBAL_parallel_execution_mode) { choiceptr aux_cp; OPTYAP_ERROR_CHECKING(completion, YOUNGER_CP(Get_LOCAL_top_cp(), Get_LOCAL_top_cp_on_stack())); aux_cp = chain_cp; @@ -1381,7 +1381,7 @@ if (SCH_top_shared_cp(B)) { #ifdef TIMESTAMP_CHECK - timestamp = ++Yap_timestamp; + timestamp = ++GLOBAL_timestamp; #endif /* TIMESTAMP_CHECK */ entry_owners = OrFr_owners(LOCAL_top_or_fr); } @@ -1409,7 +1409,7 @@ UNLOCK(DepFr_lock(dep_fr)); #ifdef DEBUG_OPTYAP - if (Yap_parallel_execution_mode) { + if (GLOBAL_parallel_execution_mode) { choiceptr aux_cp; OPTYAP_ERROR_CHECKING(completion, Get_LOCAL_top_cp(), Get_LOCAL_top_cp_on_stack()); aux_cp = DepFr_cons_cp(dep_fr); @@ -1434,7 +1434,7 @@ } #endif /* YAPOR */ #ifdef DEBUG_OPTYAP - if (Yap_parallel_execution_mode) { + if (GLOBAL_parallel_execution_mode) { choiceptr aux_cp; OPTYAP_ERROR_CHECKING(completion, YOUNGER_CP(Get_LOCAL_top_cp(), Get_LOCAL_top_cp_on_stack())); aux_cp = DepFr_cons_cp(dep_fr); diff --git a/OPTYap/tab.macros.h b/OPTYap/tab.macros.h index 410248cd6..b9899a4b2 100644 --- a/OPTYap/tab.macros.h +++ b/OPTYap/tab.macros.h @@ -111,10 +111,10 @@ static inline tg_sol_fr_ptr CUT_prune_tg_solution_frames(tg_sol_fr_ptr, int); #define MakeTableVarTerm(INDEX) ((INDEX) << NumberOfLowTagBits) #define VarIndexOfTableTerm(TERM) (((unsigned int) (TERM)) >> NumberOfLowTagBits) #define VarIndexOfTerm(TERM) \ - ((((CELL) (TERM)) - Yap_table_var_enumerator(0)) / sizeof(CELL)) + ((((CELL) (TERM)) - GLOBAL_table_var_enumerator(0)) / sizeof(CELL)) #define IsTableVarTerm(TERM) \ - ((CELL) (TERM)) >= Yap_table_var_enumerator(0) && \ - ((CELL) (TERM)) <= Yap_table_var_enumerator(MAX_TABLE_VARS - 1) + ((CELL) (TERM)) >= GLOBAL_table_var_enumerator(0) && \ + ((CELL) (TERM)) <= GLOBAL_table_var_enumerator(MAX_TABLE_VARS - 1) #ifdef TRIE_COMPACT_PAIRS #define PairTermMark NULL #define CompactPairInit AbsPair((Term *) 0) @@ -154,8 +154,8 @@ static inline tg_sol_fr_ptr CUT_prune_tg_solution_frames(tg_sol_fr_ptr, int); #define IS_GLOBAL_TRIE_HASH(NODE) (TrNode_entry(NODE) == GLOBAL_TRIE_HASH_MARK) #define HASH_TABLE_LOCK(NODE) ((((unsigned long int) (NODE)) >> 5) & (TABLE_LOCK_BUCKETS - 1)) -#define LOCK_TABLE(NODE) LOCK(Yap_table_lock(HASH_TABLE_LOCK(NODE))) -#define UNLOCK_TABLE(NODE) UNLOCK(Yap_table_lock(HASH_TABLE_LOCK(NODE))) +#define LOCK_TABLE(NODE) LOCK(GLOBAL_table_lock(HASH_TABLE_LOCK(NODE))) +#define UNLOCK_TABLE(NODE) UNLOCK(GLOBAL_table_lock(HASH_TABLE_LOCK(NODE))) #define STACK_PUSH_UP(ITEM, STACK) *--(STACK) = (CELL)(ITEM) #define STACK_POP_UP(STACK) *--(STACK) @@ -290,8 +290,8 @@ static inline tg_sol_fr_ptr CUT_prune_tg_solution_frames(tg_sol_fr_ptr, int); SetMode_GlobalTrie(TabEnt_mode(TAB_ENT)); \ TabEnt_subgoal_trie(TAB_ENT) = sg_node; \ TabEnt_hash_chain(TAB_ENT) = NULL; \ - TabEnt_next(TAB_ENT) = Yap_root_tab_ent; \ - Yap_root_tab_ent = TAB_ENT; \ + TabEnt_next(TAB_ENT) = GLOBAL_root_tab_ent; \ + GLOBAL_root_tab_ent = TAB_ENT; \ } #define new_subgoal_frame(SG_FR, CODE) \ @@ -394,27 +394,27 @@ static inline tg_sol_fr_ptr CUT_prune_tg_solution_frames(tg_sol_fr_ptr, int); #ifdef LIMIT_TABLING #define insert_into_global_sg_fr_list(SG_FR) \ - SgFr_previous(SG_FR) = Yap_last_sg_fr; \ + SgFr_previous(SG_FR) = GLOBAL_last_sg_fr; \ SgFr_next(SG_FR) = NULL; \ - if (Yap_first_sg_fr == NULL) \ - Yap_first_sg_fr = SG_FR; \ + if (GLOBAL_first_sg_fr == NULL) \ + GLOBAL_first_sg_fr = SG_FR; \ else \ - SgFr_next(Yap_last_sg_fr) = SG_FR; \ - Yap_last_sg_fr = SG_FR + SgFr_next(GLOBAL_last_sg_fr) = SG_FR; \ + GLOBAL_last_sg_fr = SG_FR #define remove_from_global_sg_fr_list(SG_FR) \ if (SgFr_previous(SG_FR)) { \ if ((SgFr_next(SgFr_previous(SG_FR)) = SgFr_next(SG_FR)) != NULL) \ SgFr_previous(SgFr_next(SG_FR)) = SgFr_previous(SG_FR); \ else \ - Yap_last_sg_fr = SgFr_previous(SG_FR); \ + GLOBAL_last_sg_fr = SgFr_previous(SG_FR); \ } else { \ - if ((Yap_first_sg_fr = SgFr_next(SG_FR)) != NULL) \ + if ((GLOBAL_first_sg_fr = SgFr_next(SG_FR)) != NULL) \ SgFr_previous(SgFr_next(SG_FR)) = NULL; \ else \ - Yap_last_sg_fr = NULL; \ + GLOBAL_last_sg_fr = NULL; \ } \ - if (Yap_check_sg_fr == SG_FR) \ - Yap_check_sg_fr = SgFr_previous(SG_FR) + if (GLOBAL_check_sg_fr == SG_FR) \ + GLOBAL_check_sg_fr = SgFr_previous(SG_FR) #else #define insert_into_global_sg_fr_list(SG_FR) #define remove_from_global_sg_fr_list(SG_FR) @@ -435,13 +435,13 @@ static inline Int freeze_current_cp(void) { TR_FZ = freeze_cp->cp_tr; B = B->cp_b; HB = B->cp_h; - return (Yap_LocalBase - (ADDR)freeze_cp); + return (LOCAL_LocalBase - (ADDR)freeze_cp); } static inline void wake_frozen_cp(Int frozen_offset) { CACHE_REGS - choiceptr frozen_cp = (choiceptr)(Yap_LocalBase - frozen_offset); + choiceptr frozen_cp = (choiceptr)(LOCAL_LocalBase - frozen_offset); restore_bindings(TR, frozen_cp->cp_tr); B = frozen_cp; @@ -453,7 +453,7 @@ static inline void wake_frozen_cp(Int frozen_offset) { static inline void abolish_frozen_cps_until(Int frozen_offset) { CACHE_REGS - choiceptr frozen_cp = (choiceptr)(Yap_LocalBase - frozen_offset); + choiceptr frozen_cp = (choiceptr)(LOCAL_LocalBase - frozen_offset); B_FZ = frozen_cp; H_FZ = frozen_cp->cp_h; @@ -464,9 +464,9 @@ static inline void abolish_frozen_cps_until(Int frozen_offset) { static inline void abolish_frozen_cps_all(void) { CACHE_REGS - B_FZ = (choiceptr) Yap_LocalBase; - H_FZ = (CELL *) Yap_GlobalBase; - TR_FZ = (tr_fr_ptr) Yap_TrailBase; + B_FZ = (choiceptr) LOCAL_LocalBase; + H_FZ = (CELL *) LOCAL_GlobalBase; + TR_FZ = (tr_fr_ptr) LOCAL_TrailBase; return; } @@ -500,10 +500,10 @@ static inline void unbind_variables(tr_fr_ptr unbind_tr, tr_fr_ptr end_tr) { RESET_VARIABLE(ref); } else if (IsPairTerm(ref)) { ref = (CELL) RepPair(ref); - if (IN_BETWEEN(Yap_TrailBase, ref, Yap_TrailTop)) { + if (IN_BETWEEN(LOCAL_TrailBase, ref, LOCAL_TrailTop)) { /* avoid frozen segments */ unbind_tr = (tr_fr_ptr) ref; - TABLING_ERROR_CHECKING(unbind_variables, unbind_tr > (tr_fr_ptr) Yap_TrailTop); + TABLING_ERROR_CHECKING(unbind_variables, unbind_tr > (tr_fr_ptr) LOCAL_TrailTop); TABLING_ERROR_CHECKING(unbind_variables, unbind_tr < end_tr); } #ifdef MULTI_ASSIGNMENT_VARIABLES @@ -523,7 +523,7 @@ static inline void rebind_variables(tr_fr_ptr rebind_tr, tr_fr_ptr end_tr) { CACHE_REGS TABLING_ERROR_CHECKING(rebind_variables, rebind_tr < end_tr); /* rebind loop */ - Yap_NEW_MAHASH((ma_h_inner_struct *)H); + Yap_NEW_MAHASH((ma_h_inner_struct *)H PASS_REGS); while (rebind_tr != end_tr) { CELL ref = (CELL) TrailTerm(--rebind_tr); /* check for global or local variables */ @@ -532,16 +532,16 @@ static inline void rebind_variables(tr_fr_ptr rebind_tr, tr_fr_ptr end_tr) { *((CELL *)ref) = TrailVal(rebind_tr); } else if (IsPairTerm(ref)) { ref = (CELL) RepPair(ref); - if (IN_BETWEEN(Yap_TrailBase, ref, Yap_TrailTop)) { + if (IN_BETWEEN(LOCAL_TrailBase, ref, LOCAL_TrailTop)) { /* avoid frozen segments */ rebind_tr = (tr_fr_ptr) ref; - TABLING_ERROR_CHECKING(rebind_variables, rebind_tr > (tr_fr_ptr) Yap_TrailTop); + TABLING_ERROR_CHECKING(rebind_variables, rebind_tr > (tr_fr_ptr) LOCAL_TrailTop); TABLING_ERROR_CHECKING(rebind_variables, rebind_tr < end_tr); } #ifdef MULTI_ASSIGNMENT_VARIABLES } else { CELL *cell_ptr = RepAppl(ref); - if (!Yap_lookup_ma_var(cell_ptr)) { + if (!Yap_lookup_ma_var(cell_ptr PASS_REGS)) { /* first time we found the variable, let's put the new value */ *cell_ptr = TrailVal(rebind_tr); } @@ -560,7 +560,7 @@ static inline void restore_bindings(tr_fr_ptr unbind_tr, tr_fr_ptr rebind_tr) { TABLING_ERROR_CHECKING(restore_variables, unbind_tr < rebind_tr); end_tr = rebind_tr; - Yap_NEW_MAHASH((ma_h_inner_struct *)H); + Yap_NEW_MAHASH((ma_h_inner_struct *)H PASS_REGS); while (unbind_tr != end_tr) { /* unbind loop */ while (unbind_tr > end_tr) { @@ -569,10 +569,10 @@ static inline void restore_bindings(tr_fr_ptr unbind_tr, tr_fr_ptr rebind_tr) { RESET_VARIABLE(ref); } else if (IsPairTerm(ref)) { ref = (CELL) RepPair(ref); - if (IN_BETWEEN(Yap_TrailBase, ref, Yap_TrailTop)) { + if (IN_BETWEEN(LOCAL_TrailBase, ref, LOCAL_TrailTop)) { /* avoid frozen segments */ unbind_tr = (tr_fr_ptr) ref; - TABLING_ERROR_CHECKING(restore_variables, unbind_tr > (tr_fr_ptr) Yap_TrailTop); + TABLING_ERROR_CHECKING(restore_variables, unbind_tr > (tr_fr_ptr) LOCAL_TrailTop); } #ifdef MULTI_ASSIGNMENT_VARIABLES } else if (IsApplTerm(ref)) { @@ -582,7 +582,7 @@ static inline void restore_bindings(tr_fr_ptr unbind_tr, tr_fr_ptr rebind_tr) { /* multi-assignment variable */ /* so that the upper cell is the old value */ --unbind_tr; - if (!Yap_lookup_ma_var(pt)) { + if (!Yap_lookup_ma_var(pt PASS_REGS)) { pt[0] = TrailVal(unbind_tr); } #endif /* MULTI_ASSIGNMENT_VARIABLES */ @@ -593,10 +593,10 @@ static inline void restore_bindings(tr_fr_ptr unbind_tr, tr_fr_ptr rebind_tr) { ref = (CELL) TrailTerm(--end_tr); if (IsPairTerm(ref)) { ref = (CELL) RepPair(ref); - if (IN_BETWEEN(Yap_TrailBase, ref, Yap_TrailTop)) { + if (IN_BETWEEN(LOCAL_TrailBase, ref, LOCAL_TrailTop)) { /* avoid frozen segments */ end_tr = (tr_fr_ptr) ref; - TABLING_ERROR_CHECKING(restore_variables, end_tr > (tr_fr_ptr) Yap_TrailTop); + TABLING_ERROR_CHECKING(restore_variables, end_tr > (tr_fr_ptr) LOCAL_TrailTop); } } } @@ -608,10 +608,10 @@ static inline void restore_bindings(tr_fr_ptr unbind_tr, tr_fr_ptr rebind_tr) { *((CELL *)ref) = TrailVal(rebind_tr); } else if (IsPairTerm(ref)) { ref = (CELL) RepPair(ref); - if (IN_BETWEEN(Yap_TrailBase, ref, Yap_TrailTop)) { + if (IN_BETWEEN(LOCAL_TrailBase, ref, LOCAL_TrailTop)) { /* avoid frozen segments */ rebind_tr = (tr_fr_ptr) ref; - TABLING_ERROR_CHECKING(restore_variables, rebind_tr > (tr_fr_ptr) Yap_TrailTop); + TABLING_ERROR_CHECKING(restore_variables, rebind_tr > (tr_fr_ptr) LOCAL_TrailTop); TABLING_ERROR_CHECKING(restore_variables, rebind_tr < end_tr); } #ifdef MULTI_ASSIGNMENT_VARIABLES @@ -629,13 +629,13 @@ static inline void restore_bindings(tr_fr_ptr unbind_tr, tr_fr_ptr rebind_tr) { static inline CELL *expand_auxiliary_stack(CELL *stack) { CACHE_REGS - void *old_top = Yap_TrailTop; + void *old_top = LOCAL_TrailTop; INFORMATION_MESSAGE("Expanding trail in 64 Kbytes"); if (! Yap_growtrail(K64, TRUE)) { /* TRUE means 'contiguous_only' */ Yap_Error(OUT_OF_TRAIL_ERROR, TermNil, "stack full (STACK_CHECK_EXPAND)"); return NULL; } else { - UInt diff = (void *)Yap_TrailTop - old_top; + UInt diff = (void *)LOCAL_TrailTop - old_top; CELL *new_stack = (CELL *)((void *)stack + diff); memmove((void *)new_stack, (void *)stack, old_top - (void *)stack); return new_stack; @@ -645,6 +645,7 @@ static inline CELL *expand_auxiliary_stack(CELL *stack) { static inline void abolish_incomplete_subgoals(choiceptr prune_cp) { CACHE_REGS + #ifdef YAPOR if (EQUAL_OR_YOUNGER_CP(GetOrFr_node(LOCAL_top_susp_or_fr), prune_cp)) pruning_over_tabling_data_structures(); @@ -652,7 +653,7 @@ static inline void abolish_incomplete_subgoals(choiceptr prune_cp) { if (EQUAL_OR_YOUNGER_CP(DepFr_cons_cp(LOCAL_top_dep_fr), prune_cp)) { #ifdef YAPOR - if (Yap_parallel_execution_mode) + if (GLOBAL_parallel_execution_mode) pruning_over_tabling_data_structures(); #endif /* YAPOR */ do { @@ -666,7 +667,7 @@ static inline void abolish_incomplete_subgoals(choiceptr prune_cp) { while (LOCAL_top_sg_fr && EQUAL_OR_YOUNGER_CP(SgFr_gen_cp(LOCAL_top_sg_fr), prune_cp)) { sg_fr_ptr sg_fr; #ifdef YAPOR - if (Yap_parallel_execution_mode) + if (GLOBAL_parallel_execution_mode) pruning_over_tabling_data_structures(); #endif /* YAPOR */ sg_fr = LOCAL_top_sg_fr; diff --git a/OPTYap/tab.tries.c b/OPTYap/tab.tries.c index 7cc6fe480..f76cb2d6b 100644 --- a/OPTYap/tab.tries.c +++ b/OPTYap/tab.tries.c @@ -17,13 +17,8 @@ #include "Yap.h" #ifdef TABLING -#include -#ifdef HAVE_STRING_H -#include -#endif /* HAVE_STRING_H */ #include "Yatom.h" #include "YapHeap.h" -#include "yapio.h" #include "tab.macros.h" static inline sg_node_ptr subgoal_trie_check_insert_entry(tab_ent_ptr, sg_node_ptr, Term); @@ -78,6 +73,7 @@ static inline void traverse_update_arity(char *, int *, int *); *******************************/ static struct trie_statistics{ + IOSTREAM *out; int show; long subgoals; long subgoals_incomplete; @@ -94,6 +90,7 @@ static struct trie_statistics{ long global_trie_references; } trie_stats; +#define TrStat_out trie_stats.out #define TrStat_show trie_stats.show #define TrStat_subgoals trie_stats.subgoals #define TrStat_sg_incomplete trie_stats.subgoals_incomplete @@ -110,7 +107,7 @@ static struct trie_statistics{ #define SHOW_TABLE_ARITY_ARRAY_SIZE 10000 #define SHOW_TABLE_STRUCTURE(MESG, ARGS...) \ if (TrStat_show == SHOW_MODE_STRUCTURE) \ - fprintf(Yap_stdout, MESG, ##ARGS) + Sfprintf(TrStat_out, MESG, ##ARGS) #define CHECK_DECREMENT_GLOBAL_TRIE_REFERENCE(REF,MODE) \ if (MODE == TRAVERSE_MODE_NORMAL && IsVarTerm(REF) && REF > VarIndexOfTableTerm(MAX_TABLE_VARS)) { \ @@ -185,47 +182,47 @@ static struct trie_statistics{ static inline CELL *exec_substitution_loop(gt_node_ptr current_node, CELL **stack_vars_ptr, CELL *stack_terms) { /************************************************************************ - =========== - | | - | ... | - | | - ----------- - YENV --> | N+1 | <-- stack_vars - ----------- - | VAR_N | - ----------- - | ... | - ----------- - | VAR_0 | - ----------- - | | - | ... | - | | - =========== - | | - | ... | - | | - ----------- - TR --> | | <-- stack_terms_limit - ----------- - | | - | ... | - | | - ----------| - | TERM_N | <-- stack_terms - ----------| * - | ... | /|\ - ----------| | stack_terms_pair_offset (TRIE_COMPACT_PAIRS) - | TERM_1 | \|/ - =========== * - Yap_TrailTop --> | | <-- stack_terms_base (TRIE_COMPACT_PAIRS) - ----------- + =========== + | | + | ... | + | | + ----------- + YENV --> | N+1 | <-- stack_vars + ----------- + | VAR_N | + ----------- + | ... | + ----------- + | VAR_0 | + ----------- + | | + | ... | + | | + =========== + | | + | ... | + | | + ----------- + TR --> | | <-- stack_terms_limit + ----------- + | | + | ... | + | | + ----------| + | TERM_N | <-- stack_terms + ----------| * + | ... | /|\ + ----------| | stack_terms_pair_offset (TRIE_COMPACT_PAIRS) + | TERM_1 | \|/ + =========== * + LOCAL_TrailTop --> | | <-- stack_terms_base (TRIE_COMPACT_PAIRS) + ----------- ************************************************************************/ CACHE_REGS CELL *stack_vars = *stack_vars_ptr; CELL *stack_terms_limit = (CELL *) TR; #ifdef TRIE_COMPACT_PAIRS -#define stack_terms_base ((CELL *) Yap_TrailTop) +#define stack_terms_base ((CELL *) LOCAL_TrailTop) int stack_terms_pair_offset = 0; #endif /* TRIE_COMPACT_PAIRS */ Term t = TrNode_entry(current_node); @@ -468,7 +465,7 @@ static void free_global_trie_branch(gt_node_ptr current_node) { if (num_nodes == 0) { FREE_HASH_BUCKETS(Hash_buckets(hash)); FREE_GLOBAL_TRIE_HASH(hash); - if (parent_node != Yap_root_gt) { + if (parent_node != GLOBAL_root_gt) { #ifdef GLOBAL_TRIE_FOR_SUBTERMS if (mode == TRAVERSE_MODE_NORMAL) { if (IsApplTerm(t)) { @@ -506,7 +503,7 @@ static void free_global_trie_branch(gt_node_ptr current_node) { } else if (TrNode_next(current_node) == NULL) { CHECK_DECREMENT_GLOBAL_TRIE_FOR_SUBTERMS_REFERENCE(t, mode); FREE_GLOBAL_TRIE_NODE(current_node); - if (parent_node != Yap_root_gt) { + if (parent_node != GLOBAL_root_gt) { #ifdef GLOBAL_TRIE_FOR_SUBTERMS if (mode == TRAVERSE_MODE_NORMAL) { if (IsApplTerm(t)) { @@ -804,7 +801,7 @@ static void traverse_global_trie(gt_node_ptr current_node, char *str, int str_in static void traverse_global_trie_for_term(gt_node_ptr current_node, char *str, int *str_index, int *arity, int *mode, int type) { - if (TrNode_parent(current_node) != Yap_root_gt) + if (TrNode_parent(current_node) != GLOBAL_root_gt) traverse_global_trie_for_term(TrNode_parent(current_node), str, str_index, arity, mode, type); traverse_trie_node(TrNode_entry(current_node), str, str_index, arity, mode, type); return; @@ -1085,7 +1082,7 @@ void load_answer(ans_node_ptr current_ans_node, CELL *subs_ptr) { Term t = STACK_POP_DOWN(stack_terms); Bind((CELL *) subs_ptr[i], t); } - TABLING_ERROR_CHECKING(load_answer, stack_terms != (CELL *)Yap_TrailTop); + TABLING_ERROR_CHECKING(load_answer, stack_terms != (CELL *)LOCAL_TrailTop); return; #undef subs_arity @@ -1099,13 +1096,13 @@ CELL *exec_substitution(gt_node_ptr current_node, CELL *aux_stack) { Term t; ++aux_stack; /* skip the heap_arity entry */ - stack_terms = exec_substitution_loop(current_node, &aux_stack, (CELL *) Yap_TrailTop); + stack_terms = exec_substitution_loop(current_node, &aux_stack, (CELL *) LOCAL_TrailTop); *--aux_stack = 0; /* restore the heap_arity entry */ subs_ptr = aux_stack + aux_stack[1] + 2; t = STACK_POP_DOWN(stack_terms); Bind((CELL *) subs_ptr[subs_arity], t); - TABLING_ERROR_CHECKING(exec_substitution, stack_terms != (CELL *)Yap_TrailTop); + TABLING_ERROR_CHECKING(exec_substitution, stack_terms != (CELL *)LOCAL_TrailTop); *subs_ptr = subs_arity - 1; return aux_stack; @@ -1297,9 +1294,10 @@ void free_answer_hash_chain(ans_hash_ptr hash) { } -void show_table(tab_ent_ptr tab_ent, int show_mode) { +void show_table(tab_ent_ptr tab_ent, int show_mode, IOSTREAM *out) { sg_node_ptr sg_node; + TrStat_out = out; TrStat_show = show_mode; if (show_mode == SHOW_MODE_STATISTICS) { TrStat_subgoals = 0; @@ -1313,9 +1311,9 @@ void show_table(tab_ent_ptr tab_ent, int show_mode) { #endif /* TABLING_INNER_CUTS */ TrStat_ans_nodes = 0; TrStat_gt_refs = 0; - fprintf(Yap_stdout, "Table statistics for predicate '%s/%d'\n", AtomName(TabEnt_atom(tab_ent)), TabEnt_arity(tab_ent)); + Sfprintf(TrStat_out, "Table statistics for predicate '%s/%d'\n", AtomName(TabEnt_atom(tab_ent)), TabEnt_arity(tab_ent)); } else { /* SHOW_MODE_STRUCTURE */ - fprintf(Yap_stdout, "Table structure for predicate '%s/%d'\n", AtomName(TabEnt_atom(tab_ent)), TabEnt_arity(tab_ent)); + Sfprintf(TrStat_out, "Table structure for predicate '%s/%d'\n", AtomName(TabEnt_atom(tab_ent)), TabEnt_arity(tab_ent)); } sg_node = TrNode_child(TabEnt_subgoal_trie(tab_ent)); if (sg_node) { @@ -1349,47 +1347,48 @@ void show_table(tab_ent_ptr tab_ent, int show_mode) { } else SHOW_TABLE_STRUCTURE(" EMPTY\n"); if (show_mode == SHOW_MODE_STATISTICS) { - fprintf(Yap_stdout, " Subgoal trie structure\n"); - fprintf(Yap_stdout, " Subgoals: %ld (%ld incomplete)\n", TrStat_subgoals, TrStat_sg_incomplete); - fprintf(Yap_stdout, " Subgoal trie nodes: %ld\n", TrStat_sg_nodes); - fprintf(Yap_stdout, " Answer trie structure(s)\n"); + Sfprintf(TrStat_out, " Subgoal trie structure\n"); + Sfprintf(TrStat_out, " Subgoals: %ld (%ld incomplete)\n", TrStat_subgoals, TrStat_sg_incomplete); + Sfprintf(TrStat_out, " Subgoal trie nodes: %ld\n", TrStat_sg_nodes); + Sfprintf(TrStat_out, " Answer trie structure(s)\n"); #ifdef TABLING_INNER_CUTS - fprintf(Yap_stdout, " Answers: %ld (%ld pruned)\n", TrStat_answers, TrStat_answers_pruned); + Sfprintf(TrStat_out, " Answers: %ld (%ld pruned)\n", TrStat_answers, TrStat_answers_pruned); #else - fprintf(Yap_stdout, " Answers: %ld\n", TrStat_answers); + Sfprintf(TrStat_out, " Answers: %ld\n", TrStat_answers); #endif /* TABLING_INNER_CUTS */ - fprintf(Yap_stdout, " Answers 'TRUE': %ld\n", TrStat_answers_true); - fprintf(Yap_stdout, " Answers 'NO': %ld\n", TrStat_answers_no); - fprintf(Yap_stdout, " Answer trie nodes: %ld\n", TrStat_ans_nodes); - fprintf(Yap_stdout, " Global trie references: %ld\n", TrStat_gt_refs); + Sfprintf(TrStat_out, " Answers 'TRUE': %ld\n", TrStat_answers_true); + Sfprintf(TrStat_out, " Answers 'NO': %ld\n", TrStat_answers_no); + Sfprintf(TrStat_out, " Answer trie nodes: %ld\n", TrStat_ans_nodes); + Sfprintf(TrStat_out, " Global trie references: %ld\n", TrStat_gt_refs); } return; } -void show_global_trie(int show_mode) { +void show_global_trie(int show_mode, IOSTREAM *out) { + TrStat_out = out; TrStat_show = show_mode; if (show_mode == SHOW_MODE_STATISTICS) { TrStat_gt_terms = 0; TrStat_gt_nodes = 1; TrStat_gt_refs = 0; - fprintf(Yap_stdout, "Global trie statistics\n"); + Sfprintf(TrStat_out, "Global trie statistics\n"); } else { /* SHOW_MODE_STRUCTURE */ - fprintf(Yap_stdout, "Global trie structure\n"); + Sfprintf(TrStat_out, "Global trie structure\n"); } - if (TrNode_child(Yap_root_gt)) { + if (TrNode_child(GLOBAL_root_gt)) { char *str = (char *) malloc(sizeof(char) * SHOW_TABLE_STR_ARRAY_SIZE); int *arity = (int *) malloc(sizeof(int) * SHOW_TABLE_ARITY_ARRAY_SIZE); arity[0] = 0; - traverse_global_trie(TrNode_child(Yap_root_gt), str, 0, arity, TRAVERSE_MODE_NORMAL, TRAVERSE_POSITION_FIRST); + traverse_global_trie(TrNode_child(GLOBAL_root_gt), str, 0, arity, TRAVERSE_MODE_NORMAL, TRAVERSE_POSITION_FIRST); free(str); free(arity); } else SHOW_TABLE_STRUCTURE(" EMPTY\n"); if (show_mode == SHOW_MODE_STATISTICS) { - fprintf(Yap_stdout, " Terms: %ld\n", TrStat_gt_terms); - fprintf(Yap_stdout, " Global trie nodes: %ld\n", TrStat_gt_nodes); - fprintf(Yap_stdout, " Global trie auto references: %ld\n", TrStat_gt_refs); + Sfprintf(TrStat_out, " Terms: %ld\n", TrStat_gt_terms); + Sfprintf(TrStat_out, " Global trie nodes: %ld\n", TrStat_gt_nodes); + Sfprintf(TrStat_out, " Global trie auto references: %ld\n", TrStat_gt_refs); } return; } diff --git a/OPTYap/tab.tries.i b/OPTYap/tab.tries.i index ec333ad0f..b6eea1ba8 100644 --- a/OPTYap/tab.tries.i +++ b/OPTYap/tab.tries.i @@ -791,52 +791,52 @@ static inline sg_node_ptr subgoal_search_loop(tab_ent_ptr tab_ent, sg_node_ptr c #endif /* MODE_TERMS_LOOP */ #endif /* MODE_GLOBAL_TRIE_LOOP */ /************************************************************************ - =========== - | | - | ... | - | | - ----------- - | VAR_N | <-- stack_vars - ----------- * - | ... | /|\ - ----------- | subs_arity (N+1) - | VAR_0 | \|/ - ----------- * - YENV --> | | - ----------- - | | - | ... | - | | - =========== - | | - | ... | - | | - ----------- - TR --> | | <-- stack_terms_limit - ----------- - | | - | ... | - | | - ----------| - | TERM_N | <-- stack_terms - ----------| * - | ... | /|\ - ----------| | - | TERM_1 | | - ----------| | - | NULL | \|/ - =========== * - Yap_TrailTop --> | | - ----------- + =========== + | | + | ... | + | | + ----------- + | VAR_N | <-- stack_vars + ----------- * + | ... | /|\ + ----------- | subs_arity (N+1) + | VAR_0 | \|/ + ----------- * + YENV --> | | + ----------- + | | + | ... | + | | + =========== + | | + | ... | + | | + ----------- + TR --> | | <-- stack_terms_limit + ----------- + | | + | ... | + | | + ----------| + | TERM_N | <-- stack_terms + ----------| * + | ... | /|\ + ----------| | + | TERM_1 | | + ----------| | + | NULL | \|/ + =========== * + LOCAL_TrailTop --> | | + ----------- ************************************************************************/ CACHE_REGS #ifdef MODE_GLOBAL_TRIE_LOOP - gt_node_ptr current_node = Yap_root_gt; + gt_node_ptr current_node = GLOBAL_root_gt; #endif /* MODE_GLOBAL_TRIE_LOOP */ int subs_arity = *subs_arity_ptr; CELL *stack_vars = *stack_vars_ptr; #if ! defined(MODE_GLOBAL_TRIE_LOOP) || ! defined(GLOBAL_TRIE_FOR_SUBTERMS) - CELL *stack_terms = (CELL *) Yap_TrailTop; + CELL *stack_terms = (CELL *) LOCAL_TrailTop; #endif /* ! MODE_GLOBAL_TRIE_LOOP || ! GLOBAL_TRIE_FOR_SUBTERMS */ CELL *stack_terms_limit = (CELL *) TR; AUX_STACK_CHECK_EXPAND(stack_terms, stack_terms_limit + 1); /* + 1 because initially we stiil haven't done any STACK_POP_DOWN */ @@ -856,7 +856,7 @@ static inline sg_node_ptr subgoal_search_loop(tab_ent_ptr tab_ent, sg_node_ptr c if (subs_arity == MAX_TABLE_VARS) Yap_Error(INTERNAL_ERROR, TermNil, "subgoal_search_loop: MAX_TABLE_VARS exceeded"); STACK_PUSH_UP(t, stack_vars); - *((CELL *)t) = Yap_table_var_enumerator(subs_arity); + *((CELL *)t) = GLOBAL_table_var_enumerator(subs_arity); t = MakeTableVarTerm(subs_arity); subs_arity = subs_arity + 1; SUBGOAL_CHECK_INSERT_ENTRY(tab_ent, current_node, t); @@ -901,7 +901,7 @@ static inline sg_node_ptr subgoal_search_loop(tab_ent_ptr tab_ent, sg_node_ptr c STACK_PUSH_UP(t, stack_terms); } #if defined(MODE_GLOBAL_TRIE_LOOP) && defined(GLOBAL_TRIE_FOR_SUBTERMS) - } else if (current_node != Yap_root_gt) { + } else if (current_node != GLOBAL_root_gt) { gt_node_ptr entry_node = subgoal_search_global_trie_terms_loop(t, &subs_arity, &stack_vars, stack_terms); current_node = global_trie_check_insert_gt_entry(current_node, (Term) entry_node); #endif /* MODE_GLOBAL_TRIE_LOOP && GLOBAL_TRIE_FOR_SUBTERMS */ @@ -918,13 +918,13 @@ static inline sg_node_ptr subgoal_search_loop(tab_ent_ptr tab_ent, sg_node_ptr c STACK_PUSH_UP(Deref(aux_pair[0]), stack_terms); } #if defined(MODE_GLOBAL_TRIE_LOOP) && defined(GLOBAL_TRIE_FOR_SUBTERMS) - } else if (current_node != Yap_root_gt) { + } else if (current_node != GLOBAL_root_gt) { gt_node_ptr entry_node = subgoal_search_global_trie_terms_loop(t, &subs_arity, &stack_vars, stack_terms); current_node = global_trie_check_insert_gt_entry(current_node, (Term) entry_node); #endif /* MODE_GLOBAL_TRIE_LOOP && GLOBAL_TRIE_FOR_SUBTERMS */ #else /* ! TRIE_COMPACT_PAIRS */ #if defined(MODE_GLOBAL_TRIE_LOOP) && defined(GLOBAL_TRIE_FOR_SUBTERMS) - if (current_node != Yap_root_gt) { + if (current_node != GLOBAL_root_gt) { gt_node_ptr entry_node = subgoal_search_global_trie_terms_loop(t, &subs_arity, &stack_vars, stack_terms); current_node = global_trie_check_insert_gt_entry(current_node, (Term) entry_node); } else @@ -1005,41 +1005,41 @@ static inline ans_node_ptr answer_search_loop(sg_fr_ptr sg_fr, ans_node_ptr curr #endif /* MODE_TERMS_LOOP */ #endif /* MODE_GLOBAL_TRIE_LOOP */ /************************************************************************ - =========== - | | - | ... | - | | - ----------- - TR --> | VAR_0 | <-- stack_vars_base - ----------- * - | ... | /|\ - ----------- | vars_arity (N+1) - | VAR_N | \|/ - ----------- * - | | <-- stack_terms_limit - ----------- - | | - | ... | - | | - ----------| - | TERM_N | <-- stack_terms - ----------| * - | ... | /|\ - ----------| | - | TERM_1 | | - ----------| | - | NULL | \|/ - =========== * - Yap_TrailTop --> | | - ----------- + =========== + | | + | ... | + | | + ----------- + TR --> | VAR_0 | <-- stack_vars_base + ----------- * + | ... | /|\ + ----------- | vars_arity (N+1) + | VAR_N | \|/ + ----------- * + | | <-- stack_terms_limit + ----------- + | | + | ... | + | | + ----------| + | TERM_N | <-- stack_terms + ----------| * + | ... | /|\ + ----------| | + | TERM_1 | | + ----------| | + | NULL | \|/ + =========== * + LOCAL_TrailTop --> | | + ----------- ************************************************************************/ CACHE_REGS #ifdef MODE_GLOBAL_TRIE_LOOP - gt_node_ptr current_node = Yap_root_gt; + gt_node_ptr current_node = GLOBAL_root_gt; #endif /* MODE_GLOBAL_TRIE_LOOP */ int vars_arity = *vars_arity_ptr; #if ! defined(MODE_GLOBAL_TRIE_LOOP) || ! defined(GLOBAL_TRIE_FOR_SUBTERMS) - CELL *stack_terms = (CELL *) Yap_TrailTop; + CELL *stack_terms = (CELL *) LOCAL_TrailTop; #endif /* ! MODE_GLOBAL_TRIE_LOOP || ! GLOBAL_TRIE_FOR_SUBTERMS */ CELL *stack_vars_base = (CELL *) TR; #define stack_terms_limit (stack_vars_base + vars_arity) @@ -1066,7 +1066,7 @@ static inline ans_node_ptr answer_search_loop(sg_fr_ptr sg_fr, ans_node_ptr curr if (vars_arity == MAX_TABLE_VARS) Yap_Error(INTERNAL_ERROR, TermNil, "answer_search_loop: MAX_TABLE_VARS exceeded"); stack_vars_base[vars_arity] = t; - *((CELL *)t) = Yap_table_var_enumerator(vars_arity); + *((CELL *)t) = GLOBAL_table_var_enumerator(vars_arity); t = MakeTableVarTerm(vars_arity); ANSWER_CHECK_INSERT_ENTRY(sg_fr, current_node, t, _trie_retry_var + in_pair); vars_arity = vars_arity + 1; @@ -1118,7 +1118,7 @@ static inline ans_node_ptr answer_search_loop(sg_fr_ptr sg_fr, ans_node_ptr curr STACK_PUSH_UP(t, stack_terms); } #if defined(MODE_GLOBAL_TRIE_LOOP) && defined(GLOBAL_TRIE_FOR_SUBTERMS) - } else if (current_node != Yap_root_gt) { + } else if (current_node != GLOBAL_root_gt) { gt_node_ptr entry_node = answer_search_global_trie_terms_loop(t, &vars_arity, stack_terms); current_node = global_trie_check_insert_gt_entry(current_node, (Term) entry_node); #endif /* MODE_GLOBAL_TRIE_LOOP && GLOBAL_TRIE_FOR_SUBTERMS */ @@ -1137,13 +1137,13 @@ static inline ans_node_ptr answer_search_loop(sg_fr_ptr sg_fr, ans_node_ptr curr STACK_PUSH_UP(Deref(aux_pair[0]), stack_terms); } #if defined(MODE_GLOBAL_TRIE_LOOP) && defined(GLOBAL_TRIE_FOR_SUBTERMS) - } else if (current_node != Yap_root_gt) { + } else if (current_node != GLOBAL_root_gt) { gt_node_ptr entry_node = answer_search_global_trie_terms_loop(t, &vars_arity, stack_terms); current_node = global_trie_check_insert_gt_entry(current_node, (Term) entry_node); #endif /* MODE_GLOBAL_TRIE_LOOP && GLOBAL_TRIE_FOR_SUBTERMS */ #else /* ! TRIE_COMPACT_PAIRS */ #if defined(MODE_GLOBAL_TRIE_LOOP) && defined(GLOBAL_TRIE_FOR_SUBTERMS) - if (current_node != Yap_root_gt) { + if (current_node != GLOBAL_root_gt) { gt_node_ptr entry_node = answer_search_global_trie_terms_loop(t, &vars_arity, stack_terms); current_node = global_trie_check_insert_gt_entry(current_node, (Term) entry_node); } else @@ -1219,43 +1219,43 @@ static inline CELL *load_substitution_loop(gt_node_ptr current_node, int *vars_a static inline CELL *load_answer_loop(ans_node_ptr current_node) { #endif /* MODE_GLOBAL_TRIE_LOOP */ /************************************************************************ - =========== - | | - | ... | - | | - ----------- - TR --> | VAR_0 | <-- stack_vars_base - ----------- * - | ... | /|\ - ----------- | vars_arity (N+1) - | VAR_N | \|/ - ----------- * - | | <-- stack_terms_limit - ----------- - | | - | ... | - | | - ----------| - | TERM_N | <-- stack_terms - ----------| * - | ... | /|\ - ----------| | stack_terms_pair_offset (TRIE_COMPACT_PAIRS) - | TERM_1 | \|/ - =========== * - Yap_TrailTop --> | | <-- stack_terms_base (TRIE_COMPACT_PAIRS) - ----------- + =========== + | | + | ... | + | | + ----------- + TR --> | VAR_0 | <-- stack_vars_base + ----------- * + | ... | /|\ + ----------- | vars_arity (N+1) + | VAR_N | \|/ + ----------- * + | | <-- stack_terms_limit + ----------- + | | + | ... | + | | + ----------| + | TERM_N | <-- stack_terms + ----------| * + | ... | /|\ + ----------| | stack_terms_pair_offset (TRIE_COMPACT_PAIRS) + | TERM_1 | \|/ + =========== * + LOCAL_TrailTop --> | | <-- stack_terms_base (TRIE_COMPACT_PAIRS) + ----------- ************************************************************************/ CACHE_REGS #ifdef MODE_GLOBAL_TRIE_LOOP int vars_arity = *vars_arity_ptr; #else int vars_arity = 0; - CELL *stack_terms = (CELL *) Yap_TrailTop; + CELL *stack_terms = (CELL *) LOCAL_TrailTop; #endif /* MODE_GLOBAL_TRIE_LOOP */ CELL *stack_vars_base = (CELL *) TR; #define stack_terms_limit (stack_vars_base + vars_arity) #ifdef TRIE_COMPACT_PAIRS -#define stack_terms_base ((CELL *) Yap_TrailTop) +#define stack_terms_base ((CELL *) LOCAL_TrailTop) int stack_terms_pair_offset = 0; #endif /* TRIE_COMPACT_PAIRS */ Term t = TrNode_entry(current_node); diff --git a/VC/include/Yap.h b/VC/include/Yap.h index 4e08f1898..627a55f15 100644 --- a/VC/include/Yap.h +++ b/VC/include/Yap.h @@ -900,16 +900,6 @@ extern int splfild; #define DO_EVERYTHING 1 #define DO_ONLY_CODE 2 - -#ifdef EMACS - -/******************** using Emacs mode ********************************/ - -extern int emacs_mode; - -#endif - - /************ variable concerned with version number *****************/ extern char version_number[]; @@ -931,7 +921,7 @@ typedef struct opcode_tab_entry { extern int optimizer_on; /******************* the line for the current parse **********************/ -extern int StartLine; +extern int LOCAL_StartLine; extern int StartCh; extern int CurFileNo; @@ -1033,10 +1023,6 @@ typedef struct TIMED_MAVAR{ extern int output_msg; #endif -#if EMACS -extern char emacs_tmp[], emacs_tmp2[]; -#endif - #if HAVE_SIGNAL extern int snoozing; #endif diff --git a/VC/include/sshift.h b/VC/include/sshift.h index 1a85d08a6..d75c9f727 100644 --- a/VC/include/sshift.h +++ b/VC/include/sshift.h @@ -24,19 +24,19 @@ /* The difference between the old stack pointers and the new ones */ -extern Int HDiff, - GDiff, - LDiff, - TrDiff, - XDiff, - DelayDiff; +extern Int LOCAL_HDiff, + LOCAL_GDiff, + LOCAL_LDiff, + LOCAL_TrDiff, + LOCAL_XDiff, + LOCAL_DelayDiff; /* The old stack pointers */ -extern CELL *OldASP, *OldLCL0; -extern tr_fr_ptr OldTR; -extern CELL *OldGlobalBase, *OldH, *OldH0; -extern ADDR OldTrailBase, OldTrailTop; -extern ADDR OldHeapBase, OldHeapTop; +extern CELL *LOCAL_OldASP, *LOCAL_OldLCL0; +extern tr_fr_ptr LOCAL_OldTR; +extern CELL *LOCAL_OldGlobalBase, *LOCAL_OldH, *LOCAL_OldH0; +extern ADDR LOCAL_OldTrailBase, LOCAL_OldTrailTop; +extern ADDR LOCAL_OldHeapBase, LOCAL_OldHeapTop; #define CharP(ptr) ((char *) (ptr)) @@ -56,7 +56,7 @@ inline EXTERN CELL * PtoGloAdjust(CELL *); inline EXTERN CELL * PtoGloAdjust(CELL * ptr) { - return (CELL *) (((CELL *)(CharP(ptr) + GDiff)) ); + return (CELL *) (((CELL *)(CharP(ptr) + LOCAL_GDiff)) ); } @@ -65,7 +65,7 @@ inline EXTERN CELL * PtoDelayAdjust(CELL *); inline EXTERN CELL * PtoDelayAdjust(CELL * ptr) { - return (CELL *) (((CELL *)(CharP(ptr) + DelayDiff)) ); + return (CELL *) (((CELL *)(CharP(ptr) + LOCAL_DelayDiff)) ); } @@ -74,7 +74,7 @@ inline EXTERN tr_fr_ptr PtoTRAdjust(tr_fr_ptr); inline EXTERN tr_fr_ptr PtoTRAdjust(tr_fr_ptr ptr) { - return (tr_fr_ptr) (((tr_fr_ptr)(CharP(ptr) + TrDiff)) ); + return (tr_fr_ptr) (((tr_fr_ptr)(CharP(ptr) + LOCAL_TrDiff)) ); } @@ -83,7 +83,7 @@ inline EXTERN CELL * CellPtoTRAdjust(CELL *); inline EXTERN CELL * CellPtoTRAdjust(CELL * ptr) { - return (CELL *) (((CELL *)(CharP(ptr) + TrDiff)) ); + return (CELL *) (((CELL *)(CharP(ptr) + LOCAL_TrDiff)) ); } @@ -92,7 +92,7 @@ inline EXTERN CELL * PtoLocAdjust(CELL *); inline EXTERN CELL * PtoLocAdjust(CELL * ptr) { - return (CELL *) (((CELL *)(CharP(ptr) + LDiff)) ); + return (CELL *) (((CELL *)(CharP(ptr) + LOCAL_LDiff)) ); } @@ -101,7 +101,7 @@ inline EXTERN choiceptr ChoicePtrAdjust(choiceptr); inline EXTERN choiceptr ChoicePtrAdjust(choiceptr ptr) { - return (choiceptr) (((choiceptr)(CharP(ptr) + LDiff)) ); + return (choiceptr) (((choiceptr)(CharP(ptr) + LOCAL_LDiff)) ); } @@ -111,7 +111,7 @@ inline EXTERN choiceptr ConsumerChoicePtrAdjust(choiceptr); inline EXTERN choiceptr ConsumerChoicePtrAdjust(choiceptr ptr) { - return (choiceptr) (((choiceptr)(CharP(ptr) + LDiff)) ); + return (choiceptr) (((choiceptr)(CharP(ptr) + LOCAL_LDiff)) ); } @@ -120,7 +120,7 @@ inline EXTERN choiceptr GeneratorChoicePtrAdjust(choiceptr); inline EXTERN choiceptr GeneratorChoicePtrAdjust(choiceptr ptr) { - return (choiceptr) (((choiceptr)(CharP(ptr) + LDiff)) ); + return (choiceptr) (((choiceptr)(CharP(ptr) + LOCAL_LDiff)) ); } @@ -131,7 +131,7 @@ inline EXTERN CELL GlobalAdjust(CELL); inline EXTERN CELL GlobalAdjust(CELL val) { - return (CELL) ((val+GDiff) ); + return (CELL) ((val+LOCAL_GDiff) ); } @@ -140,7 +140,7 @@ inline EXTERN CELL DelayAdjust(CELL); inline EXTERN CELL DelayAdjust(CELL val) { - return (CELL) ((val+DelayDiff) ); + return (CELL) ((val+LOCAL_DelayDiff) ); } @@ -149,7 +149,7 @@ inline EXTERN ADDR GlobalAddrAdjust(ADDR); inline EXTERN ADDR GlobalAddrAdjust(ADDR ptr) { - return (ADDR) ((ptr+GDiff) ); + return (ADDR) ((ptr+LOCAL_GDiff) ); } @@ -158,7 +158,7 @@ inline EXTERN ADDR DelayAddrAdjust(ADDR); inline EXTERN ADDR DelayAddrAdjust(ADDR ptr) { - return (ADDR) ((ptr+DelayDiff) ); + return (ADDR) ((ptr+LOCAL_DelayDiff) ); } @@ -167,7 +167,7 @@ inline EXTERN CELL LocalAdjust(CELL); inline EXTERN CELL LocalAdjust(CELL val) { - return (CELL) ((val+LDiff) ); + return (CELL) ((val+LOCAL_LDiff) ); } @@ -176,7 +176,7 @@ inline EXTERN ADDR LocalAddrAdjust(ADDR); inline EXTERN ADDR LocalAddrAdjust(ADDR ptr) { - return (ADDR) ((ptr+LDiff) ); + return (ADDR) ((ptr+LOCAL_LDiff) ); } @@ -185,7 +185,7 @@ inline EXTERN CELL TrailAdjust(CELL); inline EXTERN CELL TrailAdjust(CELL val) { - return (CELL) ((val+TrDiff) ); + return (CELL) ((val+LOCAL_TrDiff) ); } @@ -194,7 +194,7 @@ inline EXTERN ADDR TrailAddrAdjust(ADDR); inline EXTERN ADDR TrailAddrAdjust(ADDR ptr) { - return (ADDR) ((ptr+TrDiff) ); + return (ADDR) ((ptr+LOCAL_TrDiff) ); } @@ -204,7 +204,7 @@ inline EXTERN Functor FuncAdjust(Functor); inline EXTERN Functor FuncAdjust(Functor f) { - return (Functor) ((Functor)(CharP(f)+HDiff) ); + return (Functor) ((Functor)(CharP(f)+LOCAL_HDiff) ); } @@ -213,7 +213,7 @@ inline EXTERN CELL * CellPtoHeapAdjust(CELL *); inline EXTERN CELL * CellPtoHeapAdjust(CELL * ptr) { - return (CELL *) (((CELL *)(CharP(ptr) + HDiff)) ); + return (CELL *) (((CELL *)(CharP(ptr) + LOCAL_HDiff)) ); } @@ -242,7 +242,7 @@ inline EXTERN Atom AtomAdjust(Atom); inline EXTERN Atom AtomAdjust(Atom at) { - return (Atom) ((at == NULL ? (at) : (Atom)(CharP(at)+HDiff) )); + return (Atom) ((at == NULL ? (at) : (Atom)(CharP(at)+LOCAL_HDiff) )); } @@ -251,7 +251,7 @@ inline EXTERN Prop PropAdjust(Prop); inline EXTERN Prop PropAdjust(Prop p) { - return (Prop) ((p == NULL ? (p) : (Prop)(CharP(p)+HDiff)) ); + return (Prop) ((p == NULL ? (p) : (Prop)(CharP(p)+LOCAL_HDiff)) ); } @@ -271,7 +271,7 @@ inline EXTERN Term BlobTermAdjust(Term); inline EXTERN Term BlobTermAdjust(Term t) { - return (Term) ((t-HDiff) ); + return (Term) ((t-LOCAL_HDiff) ); } @@ -281,7 +281,7 @@ inline EXTERN Term BlobTermAdjust(Term); inline EXTERN Term BlobTermAdjust(Term t) { - return (Term) ((t+HDiff) ); + return (Term) ((t+LOCAL_HDiff) ); } @@ -291,7 +291,7 @@ inline EXTERN AtomEntry * AtomEntryAdjust(AtomEntry *); inline EXTERN AtomEntry * AtomEntryAdjust(AtomEntry * at) { - return (AtomEntry *) ((AtomEntry *)(CharP(at)+HDiff) ); + return (AtomEntry *) ((AtomEntry *)(CharP(at)+LOCAL_HDiff) ); } @@ -300,7 +300,7 @@ inline EXTERN union CONSULT_OBJ * ConsultObjAdjust(union CONSULT_OBJ *); inline EXTERN union CONSULT_OBJ * ConsultObjAdjust(union CONSULT_OBJ * co) { - return (union CONSULT_OBJ *) ((union CONSULT_OBJ *)(CharP(co)+HDiff) ); + return (union CONSULT_OBJ *) ((union CONSULT_OBJ *)(CharP(co)+LOCAL_HDiff) ); } @@ -309,7 +309,7 @@ inline EXTERN DBRef DBRefAdjust(DBRef); inline EXTERN DBRef DBRefAdjust(DBRef dbr) { - return (DBRef) ((DBRef)(CharP(dbr)+HDiff) ); + return (DBRef) ((DBRef)(CharP(dbr)+LOCAL_HDiff) ); } @@ -318,7 +318,7 @@ inline EXTERN Term CodeAdjust(Term); inline EXTERN Term CodeAdjust(Term dbr) { - return (Term) (((Term)(dbr)+HDiff) ); + return (Term) (((Term)(dbr)+LOCAL_HDiff) ); } @@ -327,7 +327,7 @@ inline EXTERN ADDR AddrAdjust(ADDR); inline EXTERN ADDR AddrAdjust(ADDR addr) { - return (ADDR) ((ADDR)(CharP(addr)+HDiff) ); + return (ADDR) ((ADDR)(CharP(addr)+LOCAL_HDiff) ); } @@ -336,7 +336,7 @@ inline EXTERN CODEADDR CodeAddrAdjust(CODEADDR); inline EXTERN CODEADDR CodeAddrAdjust(CODEADDR addr) { - return (CODEADDR) ((CODEADDR)(CharP(addr)+HDiff) ); + return (CODEADDR) ((CODEADDR)(CharP(addr)+LOCAL_HDiff) ); } @@ -345,7 +345,7 @@ inline EXTERN BlockHeader * BlockAdjust(BlockHeader *); inline EXTERN BlockHeader * BlockAdjust(BlockHeader * addr) { - return (BlockHeader *) ((BlockHeader *)(CharP(addr)+HDiff) ); + return (BlockHeader *) ((BlockHeader *)(CharP(addr)+LOCAL_HDiff) ); } @@ -354,7 +354,7 @@ inline EXTERN yamop * PtoOpAdjust(yamop *); inline EXTERN yamop * PtoOpAdjust(yamop * ptr) { - return (yamop *) (((yamop *)(CharP(ptr) + HDiff)) ); + return (yamop *) (((yamop *)(CharP(ptr) + LOCAL_HDiff)) ); } @@ -363,7 +363,7 @@ inline EXTERN CELL * PtoHeapCellAdjust(CELL *); inline EXTERN CELL * PtoHeapCellAdjust(CELL * ptr) { - return (CELL *) (((CELL *)(CharP(ptr) + HDiff)) ); + return (CELL *) (((CELL *)(CharP(ptr) + LOCAL_HDiff)) ); } @@ -372,7 +372,7 @@ inline EXTERN PredEntry * PtoPredAdjust(PredEntry *); inline EXTERN PredEntry * PtoPredAdjust(PredEntry * ptr) { - return (PredEntry *) (((PredEntry *)(CharP(ptr) + HDiff)) ); + return (PredEntry *) (((PredEntry *)(CharP(ptr) + LOCAL_HDiff)) ); } @@ -381,7 +381,7 @@ inline EXTERN ArrayEntry * PtoArrayEAdjust(ArrayEntry *); inline EXTERN ArrayEntry * PtoArrayEAdjust(ArrayEntry * ptr) { - return (ArrayEntry *) (((ArrayEntry *)(CharP(ptr) + HDiff)) ); + return (ArrayEntry *) (((ArrayEntry *)(CharP(ptr) + LOCAL_HDiff)) ); } @@ -391,7 +391,7 @@ inline EXTERN AREG XAdjust(AREG); inline EXTERN AREG XAdjust(AREG reg) { - return (AREG) ((AREG)((reg)+XDiff) ); + return (AREG) ((AREG)((reg)+LOCAL_XDiff) ); } @@ -421,7 +421,7 @@ inline EXTERN int IsOldLocal(CELL); inline EXTERN int IsOldLocal(CELL reg) { - return (int) (IN_BETWEEN(OldASP, reg, OldLCL0)); + return (int) (IN_BETWEEN(LOCAL_OldASP, reg, LOCAL_OldLCL0)); } @@ -432,7 +432,7 @@ inline EXTERN int IsOldLocalInTR(CELL); inline EXTERN int IsOldLocalInTR(CELL reg) { - return (int) (IN_BETWEEN(OldH, reg, OldLCL0) ); + return (int) (IN_BETWEEN(LOCAL_OldH, reg, LOCAL_OldLCL0) ); } @@ -441,7 +441,7 @@ inline EXTERN int IsOldLocalInTRPtr(CELL *); inline EXTERN int IsOldLocalInTRPtr(CELL * ptr) { - return (int) (IN_BETWEEN(OldH, ptr, OldLCL0) ); + return (int) (IN_BETWEEN(LOCAL_OldH, ptr, LOCAL_OldLCL0) ); } @@ -451,7 +451,7 @@ inline EXTERN int IsOldH(CELL); inline EXTERN int IsOldH(CELL reg) { - return (int) (( CharP(reg) == CharP(OldH) ) ); + return (int) (( CharP(reg) == CharP(LOCAL_OldH) ) ); } @@ -462,7 +462,7 @@ inline EXTERN int IsOldGlobal(CELL); inline EXTERN int IsOldGlobal(CELL reg) { - return (int) (IN_BETWEEN(OldH0, reg, OldH) ); + return (int) (IN_BETWEEN(LOCAL_OldH0, reg, LOCAL_OldH) ); } @@ -471,7 +471,7 @@ inline EXTERN int IsOldGlobalPtr(CELL *); inline EXTERN int IsOldGlobalPtr(CELL * ptr) { - return (int) (IN_BETWEEN( OldH0, ptr, OldH) ); + return (int) (IN_BETWEEN( LOCAL_OldH0, ptr, LOCAL_OldH) ); } @@ -480,7 +480,7 @@ inline EXTERN int IsOldDelay(CELL); inline EXTERN int IsOldDelay(CELL reg) { - return (int) (IN_BETWEEN(OldGlobalBase, reg, OldH0) ); + return (int) (IN_BETWEEN(LOCAL_OldGlobalBase, reg, LOCAL_OldH0) ); } @@ -489,7 +489,7 @@ inline EXTERN int IsOldDelayPtr(CELL *); inline EXTERN int IsOldDelayPtr(CELL * ptr) { - return (int) (IN_BETWEEN( OldGlobalBase, ptr, OldH0) ); + return (int) (IN_BETWEEN( LOCAL_OldGlobalBase, ptr, LOCAL_OldH0) ); } @@ -498,7 +498,7 @@ inline EXTERN int IsOldTrail(CELL); inline EXTERN int IsOldTrail(CELL reg) { - return (int) (IN_BETWEEN(OldTrailBase, reg, OldTR) ); + return (int) (IN_BETWEEN(LOCAL_OldTrailBase, reg, LOCAL_OldTR) ); } @@ -507,7 +507,7 @@ inline EXTERN int IsOldTrailPtr(CELL *); inline EXTERN int IsOldTrailPtr(CELL * ptr) { - return (int) (IN_BETWEEN(OldTrailBase, ptr, OldTR) ); + return (int) (IN_BETWEEN(LOCAL_OldTrailBase, ptr, LOCAL_OldTR) ); } @@ -516,7 +516,7 @@ inline EXTERN int IsOldCode(CELL); inline EXTERN int IsOldCode(CELL reg) { - return (int) (IN_BETWEEN(OldHeapBase, reg, OldHeapTop) ); + return (int) (IN_BETWEEN(LOCAL_OldHeapBase, reg, LOCAL_OldHeapTop) ); } @@ -525,7 +525,7 @@ inline EXTERN int IsOldCodeCellPtr(CELL *); inline EXTERN int IsOldCodeCellPtr(CELL * ptr) { - return (int) (IN_BETWEEN(OldHeapBase, ptr, OldHeapTop) ); + return (int) (IN_BETWEEN(LOCAL_OldHeapBase, ptr, LOCAL_OldHeapTop) ); } diff --git a/VC/yapdll.mak b/VC/yapdll.mak index bab598d20..6c46efa1f 100755 --- a/VC/yapdll.mak +++ b/VC/yapdll.mak @@ -81,7 +81,7 @@ CLEAN : -@erase "$(INTDIR)\mavar.obj" -@erase "$(INTDIR)\modules.obj" -@erase "$(INTDIR)\opt.init.obj" - -@erase "$(INTDIR)\opt.memory.obj" + -@erase "$(INTDIR)\or.memory.obj" -@erase "$(INTDIR)\opt.preds.obj" -@erase "$(INTDIR)\or.cowengine.obj" -@erase "$(INTDIR)\or.cut.obj" @@ -161,7 +161,7 @@ LINK32_OBJS= \ "$(INTDIR)\mavar.obj" \ "$(INTDIR)\modules.obj" \ "$(INTDIR)\opt.init.obj" \ - "$(INTDIR)\opt.memory.obj" \ + "$(INTDIR)\or.memory.obj" \ "$(INTDIR)\opt.preds.obj" \ "$(INTDIR)\or.cowengine.obj" \ "$(INTDIR)\or.cut.obj" \ @@ -242,7 +242,7 @@ CLEAN : -@erase "$(INTDIR)\mavar.obj" -@erase "$(INTDIR)\modules.obj" -@erase "$(INTDIR)\opt.init.obj" - -@erase "$(INTDIR)\opt.memory.obj" + -@erase "$(INTDIR)\or.memory.obj" -@erase "$(INTDIR)\opt.preds.obj" -@erase "$(INTDIR)\or.cowengine.obj" -@erase "$(INTDIR)\or.cut.obj" @@ -325,7 +325,7 @@ LINK32_OBJS= \ "$(INTDIR)\mavar.obj" \ "$(INTDIR)\modules.obj" \ "$(INTDIR)\opt.init.obj" \ - "$(INTDIR)\opt.memory.obj" \ + "$(INTDIR)\or.memory.obj" \ "$(INTDIR)\opt.preds.obj" \ "$(INTDIR)\or.cowengine.obj" \ "$(INTDIR)\or.cut.obj" \ @@ -637,9 +637,9 @@ SOURCE="\Yap\Yap-4.3.17\OPTYap\opt.init.c" $(CPP) $(CPP_PROJ) $(SOURCE) -SOURCE="\Yap\Yap-4.3.17\OPTYap\opt.memory.c" +SOURCE="\Yap\Yap-4.3.17\OPTYap\or.memory.c" -"$(INTDIR)\opt.memory.obj" : $(SOURCE) "$(INTDIR)" +"$(INTDIR)\or.memory.obj" : $(SOURCE) "$(INTDIR)" $(CPP) $(CPP_PROJ) $(SOURCE) diff --git a/console/LGPL/pl-ntmain.c b/console/LGPL/pl-ntmain.c index 9a1af688a..4505c4882 100755 --- a/console/LGPL/pl-ntmain.c +++ b/console/LGPL/pl-ntmain.c @@ -1035,6 +1035,7 @@ win32main(rlc_console c, int argc, TCHAR **argv) if ( !PL_initialise(argc, av) ) PL_halt(1); + rlc_bind_terminal(c); PL_halt(PL_toplevel() ? 0 : 1); return 0; diff --git a/console/yap.c b/console/yap.c index d3cec5e16..dfa47a843 100644 --- a/console/yap.c +++ b/console/yap.c @@ -259,48 +259,6 @@ parse_yap_arguments(int argc, char *argv[], YAP_init_args *iap) if (!strcmp("dump-runtime-variables",p)) return dump_runtime_variables(); #endif /* YAPOR_COPY || YAPOR_COW || YAPOR_SBA || YAPOR_THREADS */ -#ifdef USE_SOCKET - case 'c': /* running as client */ - { - char *host, *p1; - long port; - char *ptr; - - host = *++argv; - argc--; - if (host == NULL || host[0] == '-') - YAP_Error(0,0L,"sockets must receive host to connect to"); - p1 = *++argv; - argc--; - if (p1 == NULL || p1[0] == '-') - YAP_Error(0,0L,"sockets must receive port to connect to"); - port = strtol(p1, &ptr, 10); - if (ptr == NULL || ptr[0] != '\0') - YAP_Error(0,0L,"port argument to socket must be a number"); - YAP_InitSocks(host,port); - } - break; -#endif -#ifdef EMACS - case 'e': - emacs_mode = TRUE; - { - File fd; - strcpy (emacs_tmp, ++p); - if ((fd = fopen (emacs_tmp, "w")) == NIL) - fprintf(stderr, "[ Warning: unable to communicate with emacs: failed to open %s ]\n", emacs_tmp); - fclose (fd); - unlink (emacs_tmp); - p = *++argv; - --argc; - strcpy (emacs_tmp2, p); - if ((fd = fopen (emacs_tmp2, "w")) == NIL) - fprintf(stderr, "Unable to communicate with emacs: failed to open %s\n", emacs_tmp2); - fclose (fd); - unlink (emacs_tmp2); - } - break; -#endif /* EMACS */ case 'F': /* just ignore for now */ argc--; @@ -348,12 +306,6 @@ parse_yap_arguments(int argc, char *argv[], YAP_init_args *iap) goto myddas_error_print; break; } -#endif -#ifdef MPWSHELL - case 'm': - if (*++p == 'p' && *++p == 'w' && *++p == '\0') - mpwshell = TRUE; - break; #endif // execution mode case 'J': diff --git a/include/YapInterface.h b/include/YapInterface.h index ca720aab5..8ede58f0f 100755 --- a/include/YapInterface.h +++ b/include/YapInterface.h @@ -325,6 +325,9 @@ extern X_API int PROTO(YAP_Init,(YAP_init_args *)); /* int YAP_FastInit(const char *) */ extern X_API int PROTO(YAP_FastInit,(CONST char *)); +/* void * YAP_TermToStream(YAP_Term) */ +extern X_API void * PROTO(YAP_TermToStream,(YAP_Term)); + /* void * YAP_InitConsult(int, const char *) */ extern X_API void * PROTO(YAP_InitConsult,(int, CONST char *)); diff --git a/library/dgraphs.yap b/library/dgraphs.yap index 73e9e7da6..7dfb1d320 100644 --- a/library/dgraphs.yap +++ b/library/dgraphs.yap @@ -210,27 +210,21 @@ delete_remaining_edges(SortedVs,Vs0,Vsf) :- dgraph_transpose(Graph, TGraph) :- rb_visit(Graph, Edges), - rb_clone(Graph, TGraph, NewNodes), - tedges(Edges,UnsortedTEdges), - sort(UnsortedTEdges,TEdges), - fill_nodes(NewNodes,TEdges). + transpose(Edges, Nodes, TEdges, []), + dgraph_new(G0), + % make sure we have all vertices, even if they are unconnected. + dgraph_add_vertices(G0, Nodes, G1), + dgraph_add_edges(G1, TEdges, TGraph). -tedges([],[]). -tedges([V-Vs|Edges],TEdges) :- - fill_tedges(Vs, V, TEdges, TEdges0), - tedges(Edges,TEdges0). +transpose([], []) --> []. +transpose([V-Edges|MoreVs], [V|Vs]) --> + transpose_edges(Edges, V), + transpose(MoreVs, Vs). -fill_tedges([], _, TEdges, TEdges). -fill_tedges([V1|Vs], V, [V1-V|TEdges], TEdges0) :- - fill_tedges(Vs, V, TEdges, TEdges0). - - -fill_nodes([],[]). -fill_nodes([V-[Child|MoreChildren]|Nodes],[V-Child|Edges]) :- !, - get_extra_children(Edges,V,MoreChildren,REdges), - fill_nodes(Nodes,REdges). -fill_nodes([_-[]|Edges],TEdges) :- - fill_nodes(Edges,TEdges). +transpose_edges([], _V) --> []. +transpose_edges(E.Edges, V) --> + [E-V], + transpose_edges(Edges, V). dgraph_compose(T1,T2,CT) :- rb_visit(T1,Nodes), diff --git a/library/dialect/swi/fli/swi.c b/library/dialect/swi/fli/swi.c index cb4210473..d0268df46 100755 --- a/library/dialect/swi/fli/swi.c +++ b/library/dialect/swi/fli/swi.c @@ -9,6 +9,8 @@ */ +#define PL_KERNEL 1 + //=== includes =============================================================== #include #include @@ -118,7 +120,7 @@ UserCPredicate(char *a, CPredicate def, unsigned long int arity, Term mod, int f Atom at; while ((at = Yap_LookupAtom(a)) == NULL) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return; } } @@ -129,7 +131,7 @@ UserCPredicate(char *a, CPredicate def, unsigned long int arity, Term mod, int f while ((at = Yap_LookupAtom(a)) == NULL) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return; } } @@ -630,7 +632,7 @@ X_API atom_t PL_new_atom(const char *c) while ((at = Yap_LookupAtom((char *)c)) == NULL) { if (!Yap_growheap(FALSE, 0L, NULL)) { CACHE_REGS - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } } @@ -646,7 +648,7 @@ X_API atom_t PL_new_atom_nchars(size_t len, const char *c) while ((pt = (char *)Yap_AllocCodeSpace(len+1)) == NULL) { if (!Yap_growheap(FALSE, 0L, NULL)) { CACHE_REGS - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } } @@ -658,7 +660,7 @@ X_API atom_t PL_new_atom_nchars(size_t len, const char *c) while ((at = Yap_LookupAtom(pt)) == NULL) { if (!Yap_growheap(FALSE, 0L, NULL)) { CACHE_REGS - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } } @@ -680,7 +682,7 @@ X_API atom_t PL_new_atom_wchars(size_t len, const wchar_t *c) while (!(nbf = (wchar_t *)YAP_AllocSpaceFromYap((len+1)*sizeof(wchar_t)))) { if (!Yap_growheap(FALSE, 0L, NULL)) { CACHE_REGS - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return 0; } } @@ -690,7 +692,7 @@ X_API atom_t PL_new_atom_wchars(size_t len, const wchar_t *c) while ((at0 = Yap_LookupWideAtom(nbf)) == NULL) { if (!Yap_growheap(FALSE, 0L, NULL)) { CACHE_REGS - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return 0L; } } @@ -703,7 +705,7 @@ X_API atom_t PL_new_atom_wchars(size_t len, const wchar_t *c) while (!(nbf = (char *)YAP_AllocSpaceFromYap((len+1)*sizeof(char)))) { if (!Yap_growheap(FALSE, 0L, NULL)) { CACHE_REGS - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return 0; } } @@ -713,7 +715,7 @@ X_API atom_t PL_new_atom_wchars(size_t len, const wchar_t *c) while (!(at0 = Yap_LookupAtom(nbf))) { if (!Yap_growheap(FALSE, 0L, NULL)) { CACHE_REGS - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return 0; } } @@ -853,7 +855,7 @@ X_API int PL_put_atom_chars(term_t t, const char *s) while (!(at = Yap_LookupAtom((char *)s))) { if (!Yap_growheap(FALSE, 0L, NULL)) { CACHE_REGS - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -870,7 +872,7 @@ X_API int PL_put_atom_nchars(term_t t, size_t len, const char *s) if (strlen(s) > len) { while (!(buf = (char *)Yap_AllocCodeSpace(len+1))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -881,7 +883,7 @@ X_API int PL_put_atom_nchars(term_t t, size_t len, const char *s) } while (!(at = Yap_LookupAtom(buf))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1031,7 +1033,7 @@ X_API int PL_throw(term_t exception) { CACHE_REGS YAP_Throw(Yap_GetFromSlot(exception PASS_REGS)); - longjmp(execution->env, 0); + longjmp(LOCAL_execution->env, 0); return 0; } @@ -1078,7 +1080,7 @@ X_API int PL_unify_atom_chars(term_t t, const char *s) Term cterm; while (!(catom = Yap_LookupAtom((char *)s))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1101,7 +1103,7 @@ X_API int PL_unify_atom_nchars(term_t t, size_t len, const char *s) buf[len] = '\0'; while (!(catom = Yap_LookupAtom(buf))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1336,7 +1338,7 @@ X_API int PL_unify_wchars(term_t t, int type, size_t len, const pl_wchar_t *char Atom at; while ((at = Yap_LookupMaybeWideAtomWithLength((wchar_t *)chars, len)) == NULL) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1395,7 +1397,7 @@ LookupMaxAtom(size_t n, char *s) buf[n] = '\0'; while (!(catom = Yap_LookupAtom(buf))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return NULL; } } @@ -1416,7 +1418,7 @@ LookupMaxWideAtom(size_t n, wchar_t *s) while (!(catom = Yap_LookupMaybeWideAtom(buf))) { if (!Yap_growheap(FALSE, 0L, NULL)) { CACHE_REGS - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return NULL; } } @@ -1499,7 +1501,7 @@ X_API int PL_unify_term(term_t l,...) char *s = va_arg(ap, char *); while (!(at = Yap_LookupAtom(s))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1594,7 +1596,7 @@ X_API int PL_unify_term(term_t l,...) while (!(at = Yap_LookupAtom(fname))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1606,7 +1608,7 @@ X_API int PL_unify_term(term_t l,...) while (!(at = Yap_LookupAtom(fname))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return FALSE; } } @@ -1988,22 +1990,22 @@ PL_initialise(int myargc, char **myargv) init_args.SchedulerLoop = 10; init_args.DelayedReleaseLoad = 3; - Yap_PL_Argc = myargc; - Yap_PL_Argv = myargv; - Yap_InitialisedFromPL = TRUE; + GLOBAL_PL_Argc = myargc; + GLOBAL_PL_Argv = myargv; + GLOBAL_InitialisedFromPL = TRUE; return YAP_Init(&init_args) != YAP_BOOT_ERROR; } X_API int PL_is_initialised(int *argcp, char ***argvp) { - if (Yap_InitialisedFromPL) { + if (GLOBAL_InitialisedFromPL) { if (argcp) - *argcp = Yap_PL_Argc; + *argcp = GLOBAL_PL_Argc; if (argvp) - *argvp = Yap_PL_Argv; + *argvp = GLOBAL_PL_Argv; } - return Yap_InitialisedFromPL; + return GLOBAL_InitialisedFromPL; } X_API module_t @@ -2057,7 +2059,7 @@ X_API predicate_t PL_predicate(const char *name, int arity, const char *m) Atom at; while (!(at = Yap_LookupAtom((char *)m))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return NULL; } } @@ -2065,7 +2067,7 @@ X_API predicate_t PL_predicate(const char *name, int arity, const char *m) } while (!(at = Yap_LookupAtom((char *)name))) { if (!Yap_growheap(FALSE, 0L, NULL)) { - Yap_Error(OUT_OF_HEAP_ERROR, TermNil, Yap_ErrorMessage); + Yap_Error(OUT_OF_HEAP_ERROR, TermNil, LOCAL_ErrorMessage); return NULL; } } @@ -2133,14 +2135,14 @@ PL_open_foreign_frame(void) CACHE_REGS open_query *new = (open_query *)malloc(sizeof(open_query)); if (!new) return 0; - new->old = execution; + new->old = LOCAL_execution; new->g = TermNil; new->open = FALSE; new->cp = CP; new->p = P; new->b = (CELL)(LCL0-(CELL*)B); new->slots = CurSlot; - execution = new; + LOCAL_execution = new; { /* initialise a new marker choicepoint */ choiceptr cp_b = ((choiceptr)ASP)-1; @@ -2168,7 +2170,7 @@ PL_close_foreign_frame(fid_t f) CurSlot = env->slots; B = (choiceptr)(LCL0-env->b); ASP = (CELL *)(LCL0-CurSlot); - execution = env->old; + LOCAL_execution = env->old; free(env); } @@ -2200,9 +2202,9 @@ PL_discard_foreign_frame(fid_t f) { CACHE_REGS open_query *env = (open_query *)f; - if (execution != env) { + if (LOCAL_execution != env) { /* handle the case where we do not want to kill the last open frame */ - open_query *env0 = execution; + open_query *env0 = LOCAL_execution; while (env0 && env0 != env) env0 = env0->old; if (!env0) return; @@ -2213,7 +2215,7 @@ PL_discard_foreign_frame(fid_t f) backtrack(); CP = env->cp; P = env->p; - execution = env->old; + LOCAL_execution = env->old; ASP = LCL0-CurSlot; B = B->cp_b; free(env); @@ -2228,8 +2230,8 @@ X_API qid_t PL_open_query(module_t ctx, int flags, predicate_t p, term_t t0) /* ignore flags and module for now */ PL_open_foreign_frame(); - execution->open=1; - execution->state=0; + LOCAL_execution->open=1; + LOCAL_execution->state=0; PredicateInfo((PredEntry *)p, &yname, &arity, &m); t[0] = SWIModuleToModule(ctx); if (arity == 0) { @@ -2243,19 +2245,19 @@ X_API qid_t PL_open_query(module_t ctx, int flags, predicate_t p, term_t t0) t[0] = MkAtomTerm((Atom)ctx); ti = Yap_MkApplTerm(FunctorModule,2,t); t[0] = ti; - execution->g = Yap_MkApplTerm(FunctorCall,1,t); + LOCAL_execution->g = Yap_MkApplTerm(FunctorCall,1,t); } else { if (m && m != CurrentModule) { Term ti; t[0] = m; ti = Yap_MkApplTerm(FunctorModule,2,t); t[0] = ti; - execution->g = Yap_MkApplTerm(FunctorCall,1,t); + LOCAL_execution->g = Yap_MkApplTerm(FunctorCall,1,t); } else { - execution->g = t[1]; + LOCAL_execution->g = t[1]; } } - return execution; + return LOCAL_execution; } X_API int PL_next_solution(qid_t qi) @@ -2263,12 +2265,12 @@ X_API int PL_next_solution(qid_t qi) CACHE_REGS int result; if (qi->open != 1) return 0; - if (setjmp(execution->env)) + if (setjmp(LOCAL_execution->env)) return 0; if (qi->state == 0) { result = YAP_RunGoal(qi->g); } else { - Yap_AllowRestart = qi->open; + LOCAL_AllowRestart = qi->open; result = YAP_RestartGoal(); } qi->state = 1; @@ -2491,9 +2493,9 @@ PL_create_engine(const PL_thread_attr_t *attr) yapt.tsize = attr->global_size; yapt.alias = (YAP_Term)attr->alias; yapt.cancel = attr->cancel; - return Yap_WLocal+YAP_ThreadCreateEngine(&yapt); + return Yap_local+YAP_ThreadCreateEngine(&yapt); } else { - return Yap_WLocal+YAP_ThreadCreateEngine(NULL); + return Yap_local+YAP_ThreadCreateEngine(NULL); } #else return NULL; @@ -2505,7 +2507,7 @@ X_API int PL_destroy_engine(PL_engine_t e) { #if THREADS - return YAP_ThreadDestroyEngine(((struct worker_local *)e)->thread_handle.current_yaam_regs->worker_id_); + return YAP_ThreadDestroyEngine(((struct worker_local *)e)->ThreadHandle_.current_yaam_regs->worker_id_); #else return FALSE; #endif @@ -2519,7 +2521,7 @@ PL_set_engine(PL_engine_t engine, PL_engine_t *old) int cwid = PL_thread_self(), nwid; if (cwid >= 0) { - if (old) *old = (PL_engine_t)(Yap_WLocal[cwid]); + if (old) *old = (PL_engine_t)(Yap_local[cwid]); } if (!engine) { if (cwid < 0) @@ -2538,12 +2540,12 @@ PL_set_engine(PL_engine_t engine, PL_engine_t *old) } return PL_ENGINE_SET; } else { - nwid = ((struct worker_local *)engine)->thread_handle.current_yaam_regs->worker_id_; + nwid = ((struct worker_local *)engine)->ThreadHandle_.current_yaam_regs->worker_id_; } - pthread_mutex_lock(&(FOREIGN_ThreadHandle(nwid).tlock)); - if (FOREIGN_ThreadHandle(nwid).pthread_handle) { - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(nwid).tlock)); + pthread_mutex_lock(&(REMOTE_ThreadHandle(nwid).tlock)); + if (REMOTE_ThreadHandle(nwid).pthread_handle) { + pthread_mutex_unlock(&(REMOTE_ThreadHandle(nwid).tlock)); if (cwid != nwid) { return PL_ENGINE_INUSE; } @@ -2552,7 +2554,7 @@ PL_set_engine(PL_engine_t engine, PL_engine_t *old) if (cwid >= 0) { if (!YAP_ThreadDetachEngine(cwid)) { *old = NULL; - pthread_mutex_unlock(&(FOREIGN_ThreadHandle(nwid).tlock)); + pthread_mutex_unlock(&(REMOTE_ThreadHandle(nwid).tlock)); return PL_ENGINE_INVAL; } } @@ -2561,7 +2563,7 @@ PL_set_engine(PL_engine_t engine, PL_engine_t *old) } return PL_ENGINE_SET; #else - if (old) *old = (PL_engine_t)&Yap_WLocal; + if (old) *old = (PL_engine_t)&Yap_local; return FALSE; #endif } @@ -2741,9 +2743,9 @@ PL_query(int query) { switch(query) { case PL_QUERY_ARGC: - return (intptr_t)Yap_argc; + return (intptr_t)GLOBAL_argc; case PL_QUERY_ARGV: - return (intptr_t)Yap_argv; + return (intptr_t)GLOBAL_argv; case PL_QUERY_USER_CPU: return (intptr_t)Yap_cputime(); case PL_QUERY_VERSION: diff --git a/library/lammpi/prologterms2c.c b/library/lammpi/prologterms2c.c index 9f344a1c7..a2af81238 100644 --- a/library/lammpi/prologterms2c.c +++ b/library/lammpi/prologterms2c.c @@ -52,7 +52,6 @@ Comments: This file provides a set of functions to convert a prolog term to a C #endif struct buffer_ds buffer; -extern char *Yap_ErrorMessage; /*********************************************************************************************/ // prototypes @@ -229,10 +228,10 @@ string2term(char *const ptr,const size_t *size) { b.ptr=NULL; } BUFFER_POS=0; - Yap_ErrorMessage=NULL; + LOCAL_ErrorMessage=NULL; t = YAP_Read(p2c_getc); if ( t==FALSE ) { - write_msg(__FUNCTION__,__FILE__,__LINE__,"FAILED string2term>>>>size:%d %d %s\n",BUFFER_SIZE,strlen(BUFFER_PTR),Yap_ErrorMessage); + write_msg(__FUNCTION__,__FILE__,__LINE__,"FAILED string2term>>>>size:%d %d %s\n",BUFFER_SIZE,strlen(BUFFER_PTR),LOCAL_ErrorMessage); exit(1); } diff --git a/library/lammpi/yap_mpi.c b/library/lammpi/yap_mpi.c index daa4237e2..4bba051f9 100644 --- a/library/lammpi/yap_mpi.c +++ b/library/lammpi/yap_mpi.c @@ -75,8 +75,7 @@ typedef struct broadcast_req BroadcastRequest; * Auxiliary data ********************************************************************/ static int mpi_status; -extern char **Yap_argv; -extern int Yap_argc; +extern int GLOBAL_argc; #define HASHSIZE 1777 static hashtable requests=NULL; @@ -261,8 +260,8 @@ static int mpi_error(int errcode){ static int mpi_init(void){ int thread_level; - // MPI_Init(&Yap_argc, &Yap_argv); - MPI_Init_thread(&Yap_argc, &Yap_argv,MPI_THREAD_SINGLE,&thread_level); + // MPI_Init(&GLOBAL_argc, &GLOBAL_argv); + MPI_Init_thread(&GLOBAL_argc, &GLOBAL_argv,MPI_THREAD_SINGLE,&thread_level); #ifdef DEBUG write_msg(__FUNCTION__,__FILE__,__LINE__,"Thread level: %d\n",thread_level); #endif @@ -300,11 +299,11 @@ rcv_msg_thread(char *handle_pred) { static int mpi_init_rcv_thread(void){ int thread_level; - // MPI_Init(&Yap_argc, &Yap_argv); + // MPI_Init(&GLOBAL_argc, &GLOBAL_argv); pthread_t thread; char *arg="handle_msg"; - MPI_Init_thread(&Yap_argc, &Yap_argv,MPI_THREAD_SINGLE,&thread_level); + MPI_Init_thread(&GLOBAL_argc, &GLOBAL_argv,MPI_THREAD_SINGLE,&thread_level); if(pthread_create(&thread,NULL,(void*)&rcv_msg_thread,arg)) { return (FALSE); } diff --git a/library/mpi/mpi.c b/library/mpi/mpi.c index 8ada34123..9c287d5f0 100644 --- a/library/mpi/mpi.c +++ b/library/mpi/mpi.c @@ -491,21 +491,21 @@ Yap_InitMPI(void) { int i,j; - mpi_argv = malloc( Yap_argc * sizeof(char *) ); - mpi_argv[0] = strdup( Yap_argv[0] ); + mpi_argv = malloc( GLOBAL_argc * sizeof(char *) ); + mpi_argv[0] = strdup( GLOBAL_argv[0] ); bufsize = RECV_BUF_SIZE; buf = malloc(bufsize * sizeof(char)); - for( i=1; i, Head1, Tail1, Head2, Tail2, [Head2|Difference]) :- % is true when Union is the union of Set1 and Set2. Note that when % something occurs in both sets, we want to retain only one copy. -ord_union(Set1, [], Set1) :- !. -ord_union([], Set2, Set2) :- !. +ord_union([S|Set1], [], [S|Set1]). +ord_union([], Set2, Set2). ord_union([Head1|Tail1], [Head2|Tail2], Union) :- compare(Order, Head1, Head2), ord_union(Order, Head1, Tail1, Head2, Tail2, Union). diff --git a/library/tries/core_tries.c b/library/tries/core_tries.c index e7fa6acad..24bb31c6a 100644 --- a/library/tries/core_tries.c +++ b/library/tries/core_tries.c @@ -463,6 +463,7 @@ void core_trie_save(TrNode node, FILE *file, void (*save_function)(TrNode, FILE fprintf(file, "BEGIN_TRIE_v2 "); traverse_and_save(TrNode_child(node), file, 0); fprintf(file, "END_TRIE_v2"); + fflush(file); } return; } @@ -486,6 +487,7 @@ TrNode core_trie_load(TrEngine engine, FILE *file, void (*load_function)(TrNode, fprintf(stderr, "******************************************\n"); fprintf(stderr, " Tries core module: trie file corrupted\n"); fprintf(stderr, "******************************************\n"); + fflush(stderr); return NULL; } if (fsetpos(file, &curpos)) @@ -498,6 +500,7 @@ TrNode core_trie_load(TrEngine engine, FILE *file, void (*load_function)(TrNode, fprintf(stderr, "******************************************\n"); fprintf(stderr, " Tries core module: trie file corrupted\n"); fprintf(stderr, "******************************************\n"); + fflush(stderr); return NULL; } if (fsetpos(file, &curpos)) @@ -507,6 +510,7 @@ TrNode core_trie_load(TrEngine engine, FILE *file, void (*load_function)(TrNode, fprintf(stderr, "****************************************\n"); fprintf(stderr, " Tries core module: invalid trie file\n"); fprintf(stderr, "****************************************\n"); + fflush(stderr); return NULL; } CURRENT_TRIE_ENGINE = engine; @@ -563,6 +567,7 @@ void core_trie_print(TrNode node, void (*print_function)(TrNode)) { traverse_and_print(TrNode_child(node), arity, str, 0, TRIE_PRINT_NORMAL); } else fprintf(stdout, "(empty)\n"); + fflush(stdout); return; } @@ -611,14 +616,15 @@ TrNode put_entry(TrNode node, YAP_Term entry) { } else if (YAP_IsIntTerm(t)) { node = trie_node_check_insert(node, t); } else if (YAP_IsFloatTerm(t)) { - volatile double f; - volatile YAP_Term *p; - f = YAP_FloatOfTerm(t); - p = (YAP_Term *)((void *) &f); /* to avoid gcc warning */ + volatile union { + double f; + YAP_Term p[SIZE_FLOAT_AS_TERM]; + } tf; /* to avoid gcc warning */ + tf.f = YAP_FloatOfTerm(t); node = trie_node_check_insert(node, FloatInitTag); - node = trie_node_check_insert(node, *p); + node = trie_node_check_insert(node, tf.p[0]); #ifdef TAG_LOW_BITS_32 - node = trie_node_check_insert(node, *(p + 1)); + node = trie_node_check_insert(node, tf.p[1]); #endif /* TAG_LOW_BITS_32 */ node = trie_node_check_insert(node, FloatEndTag); } else if (YAP_IsPairTerm(t)) { @@ -671,6 +677,7 @@ TrNode put_entry(TrNode node, YAP_Term entry) { fprintf(stderr, "***************************************\n"); fprintf(stderr, " Tries core module: unknown type tag\n"); fprintf(stderr, "***************************************\n"); + fflush(stderr); } return node; @@ -698,16 +705,17 @@ TrNode check_entry(TrNode node, YAP_Term entry) { if (!(node = trie_node_check(node, t))) return NULL; } else if (YAP_IsFloatTerm(t)) { - volatile double f; - volatile YAP_Term *p; - f = YAP_FloatOfTerm(t); - p = (YAP_Term *)((void *) &f); /* to avoid gcc warning */ + volatile union { + double f; + YAP_Term p[SIZE_FLOAT_AS_TERM]; + } tf; /* to avoid gcc warning */ + tf.f = YAP_FloatOfTerm(t); if (!(node = trie_node_check(node, FloatInitTag))) return NULL; - if (!(node = trie_node_check(node, *p))) + if (!(node = trie_node_check(node, tf.p[0]))) return NULL; #ifdef TAG_LOW_BITS_32 - if (!(node = trie_node_check(node, *(p + 1)))) + if (!(node = trie_node_check(node, tf.p[1]))) return NULL; #endif /* TAG_LOW_BITS_32 */ if (!(node = trie_node_check(node, FloatEndTag))) @@ -777,6 +785,7 @@ TrNode check_entry(TrNode node, YAP_Term entry) { fprintf(stderr, "***************************************\n"); fprintf(stderr, " Tries core module: unknown type tag\n"); fprintf(stderr, "***************************************\n"); + fflush(stderr); } return node; @@ -797,6 +806,7 @@ YAP_Term get_entry(TrNode node, YAP_Term *stack_mark, TrNode *cur_node) { fprintf(stderr, "**************************************\n"); fprintf(stderr, " Tries core module: term stack full\n"); fprintf(stderr, "**************************************\n"); + fflush(stderr); } for (i = index; i > CURRENT_INDEX; i--) stack_vars_base[i] = 0; @@ -864,17 +874,18 @@ YAP_Term get_entry(TrNode node, YAP_Term *stack_mark, TrNode *cur_node) { *cur_node = node; return t; } else if (t == FloatEndTag) { - volatile double f; - volatile YAP_Term *p; - p = (YAP_Term *)((void *) &f); /* to avoid gcc warning */ + volatile union { + double f; + YAP_Term p[SIZE_FLOAT_AS_TERM]; + } tf; /* to avoid gcc warning */ #ifdef TAG_LOW_BITS_32 node = TrNode_parent(node); - *(p + 1) = TrNode_entry(node); + tf.p[1] = TrNode_entry(node); #endif /* TAG_LOW_BITS_32 */ node = TrNode_parent(node); - *p = TrNode_entry(node); + tf.p[0] = TrNode_entry(node); node = TrNode_parent(node); /* ignore FloatInitTag */ - t = YAP_MkFloatTerm(f); + t = YAP_MkFloatTerm(tf.f); PUSH_UP(stack_args, t, stack_vars); } else if (t == FloatInitTag) { } @@ -888,6 +899,7 @@ YAP_Term get_entry(TrNode node, YAP_Term *stack_mark, TrNode *cur_node) { fprintf(stderr, "***************************************\n"); fprintf(stderr, " Tries core module: unknown type tag\n"); fprintf(stderr, "***************************************\n"); + fflush(stderr); } node = TrNode_parent(node); } @@ -1462,7 +1474,7 @@ void traverse_and_print(TrNode node, int *arity, char *str, int str_index, int m memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); if (mode != TRIE_PRINT_FLOAT2 && arity[arity[0]] < 0) { /* restore possible PairEndEmptyTag/PairEndTermTag/CommaEndTag side-effect */ - if (str[str_index - 1] != '[') + if (str_index > 0 && str[str_index - 1] != '[') str[str_index - 1] = ','; /* restore possible PairEndTermTag side-effect */ if (str[last_pair_mark] == '|') @@ -1481,7 +1493,7 @@ void traverse_and_print(TrNode node, int *arity, char *str, int str_index, int m memcpy(arity, current_arity, sizeof(int) * (current_arity[0] + 1)); if (mode != TRIE_PRINT_FLOAT2 && arity[arity[0]] < 0) { /* restore possible PairEndEmptyTag/PairEndTermTag/CommaEndTag side-effect */ - if (str[str_index - 1] != '[') + if (str_index > 0 && str[str_index - 1] != '[') str[str_index - 1] = ','; /* restore possible PairEndTermTag side-effect */ if (str[last_pair_mark] == '|') @@ -1500,19 +1512,21 @@ void traverse_and_print(TrNode node, int *arity, char *str, int str_index, int m arity[arity[0]] = (YAP_Int) t; mode = TRIE_PRINT_FLOAT2; } else if (mode == TRIE_PRINT_FLOAT2) { - volatile double f; - volatile YAP_Term *p; - p = (YAP_Term *)((void *) &f); /* to avoid gcc warning */ - *(p + 1) = t; - *p = (YAP_Term) arity[arity[0]]; + volatile union { + double f; + YAP_Term p[SIZE_FLOAT_AS_TERM]; + } tf; /* to avoid gcc warning */ + tf.p[1] = t; + tf.p[0] = (YAP_Term) arity[arity[0]]; arity[arity[0]] = -1; #else /* TAG_64BITS */ - volatile double f; - volatile YAP_Term *p; - p = (YAP_Term *)((void *) &f); /* to avoid gcc warning */ - *p = t; + volatile union { + double f; + YAP_Term p[SIZE_FLOAT_AS_TERM]; + } tf; /* to avoid gcc warning */ + tf.p[0] = t; #endif /* TAG_SCHEME */ - str_index += sprintf(& str[str_index], "%.15g", f); + str_index += sprintf(& str[str_index], "%.15g", tf.f); mode = TRIE_PRINT_FLOAT_END; } else if (mode == TRIE_PRINT_FLOAT_END) { arity[0]--; @@ -1609,6 +1623,7 @@ void traverse_and_print(TrNode node, int *arity, char *str, int str_index, int m fprintf(stderr, "***************************************\n"); fprintf(stderr, " Tries core module: unknown type tag\n"); fprintf(stderr, "***************************************\n"); + fflush(stderr); } if (arity[0]) { @@ -1696,6 +1711,7 @@ YAP_Term trie_to_list_node(TrNode node) { fprintf(stderr, "***************************************\n"); fprintf(stderr, " Tries core module: unknown type tag\n"); fprintf(stderr, "***************************************\n"); + fflush(stderr); return YAP_MkAtomTerm(YAP_LookupAtom("fail")); } @@ -1709,7 +1725,7 @@ YAP_Term trie_to_list_node(TrNode node) { #ifdef TAG_LOW_BITS_32 static inline -YAP_Term trie_to_list_floats_tag_low_32(YAP_Term result, TrNode node, volatile YAP_Term **p, volatile double *f) { +YAP_Term trie_to_list_floats_tag_low_32(YAP_Term result, TrNode node, volatile YAP_Term *p, volatile double *f) { if(IS_HASH_NODE(node)) { TrNode *first_bucket, *bucket; TrHash hash = (TrHash) node; @@ -1720,16 +1736,15 @@ YAP_Term trie_to_list_floats_tag_low_32(YAP_Term result, TrNode node, volatile Y do { if(*--bucket) { node = *bucket; - do { - *(*p + 1) = TrNode_entry(node); + p[1] = TrNode_entry(node); PUSH_NEW_FLOAT_TERM(*f); } while((node = TrNode_next(node))); } } while (bucket != first_bucket); } else { do { - *(*p + 1) = TrNode_entry(node); + p[1] = TrNode_entry(node); PUSH_NEW_FLOAT_TERM(*f); } while((node = TrNode_next(node))); } @@ -1741,11 +1756,12 @@ YAP_Term trie_to_list_floats_tag_low_32(YAP_Term result, TrNode node, volatile Y static YAP_Term trie_to_list_floats(TrNode node) { - volatile double f; - volatile YAP_Term *p; + volatile union { + double f; + YAP_Term p[SIZE_FLOAT_AS_TERM]; + } tf; /* to avoid gcc warning */ YAP_Term result = YAP_MkAtomTerm(YAP_LookupAtom("[]")); - p = (YAP_Term *)((void *) &f); /* to avoid gcc warning */ if (IS_HASH_NODE(node)) { TrNode *first_bucket, *bucket; TrHash hash = (TrHash) node; @@ -1755,22 +1771,22 @@ YAP_Term trie_to_list_floats(TrNode node) { if (*--bucket) { node = *bucket; do { - *p = TrNode_entry(node); + tf.p[0] = TrNode_entry(node); #ifdef TAG_LOW_BITS_32 - result = trie_to_list_floats_tag_low_32(result, TrNode_child(node), &p, &f); + result = trie_to_list_floats_tag_low_32(result, TrNode_child(node), &tf.p, &tf.f); #else - PUSH_NEW_FLOAT_TERM(f); + PUSH_NEW_FLOAT_TERM(tf.f); #endif /* TAG_LOW_BITS_32 */ } while((node = TrNode_next(node))); } } while (bucket != first_bucket); } else { do { - *p = TrNode_entry(node); + tf.p[0] = TrNode_entry(node); #ifdef TAG_LOW_BITS_32 - result = trie_to_list_floats_tag_low_32(result, TrNode_child(node), &p, &f); + result = trie_to_list_floats_tag_low_32(result, TrNode_child(node), &tf.p, &tf.f); #else - PUSH_NEW_FLOAT_TERM(f); + PUSH_NEW_FLOAT_TERM(tf.f); #endif /* TAG_LOW_BITS_32 */ } while((node = TrNode_next(node))); } diff --git a/library/tries/core_tries.h b/library/tries/core_tries.h index f627911be..e9029ed26 100644 --- a/library/tries/core_tries.h +++ b/library/tries/core_tries.h @@ -14,8 +14,10 @@ #include "config.h" #if SIZEOF_INT_P==4 #define TAG_LOW_BITS_32 /* 'Tags_32LowTag.h' tagging scheme */ +#define SIZE_FLOAT_AS_TERM 2 #elif SIZEOF_INT_P==8 #define TAG_64BITS /* 'Tags_64bits.h' tagging scheme */ +#define SIZE_FLOAT_AS_TERM 1 #else #error Unknown tagging scheme #endif /* YAP_SCHEME */ diff --git a/misc/GLOBALS b/misc/GLOBALS index 48083acb3..d410af693 100644 --- a/misc/GLOBALS +++ b/misc/GLOBALS @@ -7,67 +7,128 @@ // - they must be initialised somewhere // - they may be of interest to restore // -// The defs include 4+ components: +// The defs include 3+ components: // Type -// name in structured -// global name +// name in structured / global name // init code (optional) // restore code (optional) // -// - - // Stuff that must be shared by all threads or workers START_GLOBAL_DATA +// initialization: tell whether the system has been initialised and by whom. +int Initialised =FALSE +int InitialisedFromPL =FALSE +int PL_Argc =0 +char** PL_Argv =NULL + +// halt hooks +struct halt_hook* HaltHooks =NULL + +// stack overflow expansion/gc control +int AllowLocalExpansion =TRUE +int AllowGlobalExpansion =TRUE +int AllowTrailExpansion =TRUE +UInt SizeOfOverflow =0 + +// amount of space recovered in all garbage collections +UInt AGcThreshold =10000 +Agc_hook AGCHook =NULL + + /* multi-thread support */ #if THREADS /* number of threads and processes in system */ -UInt n_of_threads Yap_NOfThreads =1 +UInt NOfThreads =1 /* number of threads created since start */ -UInt n_of_threads_created Yap_NOfThreadsCreated =1 +UInt NOfThreadsCreated =1 /* total run time for dead threads */ -UInt threads_total_time Yap_ThreadsTotalTime =0L -#endif +UInt ThreadsTotalTime =0L +// Threads Array +lockvar ThreadHandlesLock MkLock +#endif -// multi-thread/ORP support #if defined(YAPOR) || defined(THREADS) // protect long critical regions -lockvar bgl Yap_BGL MkLock +lockvar BGL MkLock #endif -// stack overflow expansion/gc control -int allow_local_expansion Yap_AllowLocalExpansion =TRUE -int allow_global_expansion Yap_AllowGlobalExpansion =TRUE -int allow_trail_expansion Yap_AllowTrailExpansion =TRUE -UInt size_of_overflow Yap_SizeOfOverflow =0 -// amount of space recovered in all garbage collections -UInt agc_last_call Yap_AGcLastCall =0 -// amount of space recovered in all garbage collections -UInt agc_threshold Yap_AGcThreshold =10000 -Agc_hook agc_hook Yap_AGCHook =NULL - - -// Threads Array -#ifdef THREADS -lockvar thread_handles_lock Yap_ThreadHandlesLock MkLock -#endif - -// Ricardo's stuff #if defined(YAPOR) || defined(TABLING) -struct global_optyap_data optyap_data Yap_optyap_data void -struct local_data remote[MAX_WORKERS] REMOTE void +struct global_optyap_data optyap_data void +#endif /* YAPOR || TABLING */ + +// whether Yap is responsible for signal handling + +int PrologShouldHandleInterrupts void + +/* This is the guy who actually started the system, and who has the correct registers */ +#if defined(THREADS) +pthread_t master_thread void +#endif /* THREADS */ + +// streams +YP_FILE* stdout =stdout +YP_FILE* stderr =stderr + +// access to yap initial arguments +char** argv void +int argc void + +// extensions to Terms +#ifdef COROUTINING +/* array with the ops for your favourite extensions */ +ext_op attas[attvars_ext+1] void #endif -// initialization: tell whether the system has been initialised and by whom. -int initialised Yap_Initialised =FALSE -int initialised_from_pl Yap_InitialisedFromPL =FALSE -int pl_argc Yap_PL_Argc =0 -char **pl_argv Yap_PL_Argv =NULL +// agc.c +int agc_calls void +YAP_ULONG_LONG agc_collected void +/* total time spent in GC */ +Int tot_agc_time =0 +/* number of heap objects in all garbage collections */ +Int tot_agc_recovered =0 + +//arrays.c +#if HAVE_MMAP +struct MMAP_ARRAY_BLOCK* mmap_arrays =NULL +#endif + + +#ifdef DEBUG +//computils.c +char Option[20] void +YP_FILE* logfile void +//init.c +int output_msg =FALSE +#endif + +//gprof.c +Int ProfCalls void +Int ProfGCs void +Int ProfHGrows void +Int ProfSGrows void +Int ProfMallocs void +Int ProfOn void +Int ProfOns void +struct RB_red_blk_node* ProfilerRoot void +struct RB_red_blk_node* ProfilerNil void +char* DIRNAME =NULL + +#if defined(COFF) || defined(A_OUT) +// loada_coff.c && load_aout.c +char Executable[YAP_FILENAME_MAX] void +#endif + + +#if __simplescalar__ +char pwd[YAP_FILENAME_MAX] void +#endif + +//udi.c +//struct udi_control_block RtreeCmd void + -// halt hooks -struct halt_hook *yap_halt_hook Yap_HaltHooks =NULL END_GLOBAL_DATA diff --git a/misc/LOCALS b/misc/LOCALS index bf4ea441a..f5b8e50f6 100644 --- a/misc/LOCALS +++ b/misc/LOCALS @@ -2,161 +2,213 @@ START_WORKER_LOCAL // Streams -int c_input_stream Yap_c_input_stream =0 -int c_output_stream Yap_c_output_stream =1 -int c_error_stream Yap_c_error_stream =2 +int c_input_stream =0 +int c_output_stream =1 +int c_error_stream =2 -/* shifts and restore: per local data-structure */ -restoreinfo rinfo -. rinfo.old_ASP OldASP =NULL -. rinfo.old_LCL0 OldLCL0 =NULL -. rinfo.old_TR OldTR =NULL -. rinfo.old_GlobalBase OldGlobalBase =NULL -. rinfo.old_H OldH =NULL -. rinfo.old_H0 OldH0 =NULL -. rinfo.old_TrailBase OldTrailBase =NULL -. rinfo.old_TrailTop OldTrailTop =NULL -. rinfo.old_HeapBase OldHeapBase =NULL -. rinfo.old_HeapTop OldHeapTop =NULL -. rinfo.cl_diff ClDiff =0L -. rinfo.g_diff GDiff =0L -. rinfo.h_diff HDiff =0L -. rinfo.g_diff0 GDiff0 =0L -. rinfo.g_split GSplit =NULL -. rinfo.l_diff LDiff =0L -. rinfo.tr_diff TrDiff =0L -. rinfo.x_diff XDiff =0L -. rinfo.delay_diff DelayDiff =0L -. rinfo.base_diff BaseDiff =0L +// Restore info +CELL* OldASP =NULL +CELL* OldLCL0 =NULL +tr_fr_ptr OldTR =NULL +CELL* OldGlobalBase =NULL +CELL* OldH =NULL +CELL* OldH0 =NULL +ADDR OldTrailBase =NULL +ADDR OldTrailTop =NULL +ADDR OldHeapBase =NULL +ADDR OldHeapTop =NULL +Int ClDiff =0L +Int GDiff =0L +Int HDiff =0L +Int GDiff0 =0L +CELL* GSplit =NULL +Int LDiff =0L +Int TrDiff =0L +Int XDiff =0L +Int DelayDiff =0L +Int BaseDiff =0L -struct reduction_counters call_counters -. call_counters.reductions ReductionsCounter =0L -. call_counters.reductions_retries PredEntriesCounter =0L -. call_counters.retries RetriesCounter =0L -. call_counters.reductions_on ReductionsCounterOn =0L -. call_counters.reductions_retries_on PredEntriesCounterOn =0L -. call_counters.retries_on RetriesCounterOn =0L - -int interrupts_disabled Yap_InterruptsDisabled =FALSE +// Reduction counters +YAP_ULONG_LONG ReductionsCounter =0L +YAP_ULONG_LONG PredEntriesCounter =0L +YAP_ULONG_LONG RetriesCounter =0L +int ReductionsCounterOn =0L +int PredEntriesCounterOn =0L +int RetriesCounterOn =0L // support for consulting files /* current consult stack */ -union CONSULT_OBJ* consultsp ConsultSp =NULL +union CONSULT_OBJ* ConsultSp =NULL /* current maximum number of cells in consult stack */ -UInt consultcapacity ConsultCapacity void +UInt ConsultCapacity void /* top of consult stack */ -union CONSULT_OBJ* consultbase ConsultBase =NULL +union CONSULT_OBJ* ConsultBase =NULL /* low-water mark for consult */ -union CONSULT_OBJ* consultlow ConsultLow =NULL +union CONSULT_OBJ* ConsultLow =NULL //global variables -Term global_arena GlobalArena =0L TermToGlobalOrAtomAdjust -UInt global_arena_overflows GlobalArenaOverflows =0L -Int delay_arena_overflows DelayArenaOverflows =0L -Int arena_overflows ArenaOverflows =0L -Int depth_arenas DepthArenas =0 +Term GlobalArena =0L TermToGlobalOrAtomAdjust +UInt GlobalArenaOverflows =0L +Int ArenaOverflows =0L +Int DepthArenas =0 -int arith_error ArithError =FALSE -struct pred_entry* last_asserted_pred LastAssertedPred =NULL -int debug_on DebugOn =FALSE -struct format_status* f_info FormatInfo =NULL -char* scanner_stack ScannerStack =NULL -struct scanner_extra_alloc* scanner_extra_blocks ScannerExtraBlocks =NULL -struct DB_TERM *ball_term BallTerm =NULL RestoreBallTerm(wid) -UInt active_signals ActiveSignals =0L -UInt i_pred_arity IPredArity =0L -yamop* prof_end ProfEnd =NULL -int uncaught_throw UncaughtThrow =FALSE -int doing_undefp DoingUndefp =FALSE -Int start_line StartLine =0L -scratch_block scratchpad ScratchPad InitScratchPad(wid) +int ArithError =FALSE +struct pred_entry* LastAssertedPred =NULL +int DebugOn =FALSE +char* ScannerStack =NULL +struct scanner_extra_alloc* ScannerExtraBlocks =NULL +struct DB_TERM* BallTerm =NULL RestoreBallTerm(wid) +UInt ActiveSignals =0L +UInt IPredArity =0L +yamop* ProfEnd =NULL +int UncaughtThrow =FALSE +int DoingUndefp =FALSE +Int StartLine =0L +scratch_block ScratchPad InitScratchPad(wid) #ifdef COROUTINING -Term woken_goals WokenGoals =0L TermToGlobalAdjust -Term atts_mutable_list AttsMutableList =0L TermToGlobalAdjust +Term WokenGoals =0L TermToGlobalAdjust +Term AttsMutableList =0L TermToGlobalAdjust #endif // gc_stuff -Term gc_generation GcGeneration =0L TermToGlobalAdjust -Term gc_phase GcPhase =0L TermToGlobalAdjust -UInt gc_current_phase GcCurrentPhase =0L -UInt gc_calls GcCalls =0L -Int tot_gc_time TotGcTime =0L -YAP_ULONG_LONG tot_gc_recovered TotGcRecovered =0L -Int last_gc_time LastGcTime =0L -Int last_ss_time LastSSTime =0L +Term GcGeneration =0L TermToGlobalAdjust +Term GcPhase =0L TermToGlobalAdjust +UInt GcCurrentPhase =0L +UInt GcCalls =0L +Int TotGcTime =0L +YAP_ULONG_LONG TotGcRecovered =0L +Int LastGcTime =0L +Int LastSSTime =0L -#if LOW_LEVEL_TRACER -Int total_cps Yap_total_choicepoints =0 -#endif - -int consult_level_ consult_level =0 - -// global variables that cannot be global in a thread/or-p implementation -#if defined(YAPOR) || defined(THREADS) -lockvar signal_lock SignalLock MkLock -struct pred_entry* wpp WPP =NULL /* in a single gc */ -Int tot_marked total_marked =0L -Int tot_oldies total_oldies =0L -#if DEBUG && COROUTINING -UInt tot_smarked total_smarked =0L +Int total_marked =0L +Int total_oldies =0L +struct choicept* current_B =NULL +CELL* prev_HB =NULL +CELL* HGEN =NULL +CELL** iptop =NULL + +#if defined(GC_NO_TAGS) +char* bp =NULL #endif -struct choicept *wl_current_B current_B =NULL -CELL* wl_prev_HB prev_HB =NULL -CELL* hgen HGEN =NULL -CELL** ip_top iptop =NULL -#if GC_NO_TAGS -char* b_p Yap_bp =NULL -#endif -#if defined(TABLING) || defined(YAPOR_SBA) -struct trail_frame* wl_sTR sTR =NULL -struct trail_frame* wl_sTR0 sTR0 =NULL -struct trail_frame* new_tr new_TR =NULL -#else -Term *wl_sTR sTR =NULL -Term *wl_sTR0 sTR0 =NULL -Term *new_tr new_TR =NULL -#endif -struct gc_mark_continuation* conttop0 cont_top0 =NULL -struct gc_mark_continuation* conttop cont_top =NULL -int disc_trail_entries discard_trail_entries =0 -gc_ma_hash_entry Gc_ma_hash_table[GC_MAVARS_HASH_SIZE] gc_ma_hash_table void -gc_ma_hash_entry* Gc_ma_h_top gc_ma_h_top =NULL -gc_ma_hash_entry* Gc_ma_h_list gc_ma_h_list =NULL -UInt Gc_timestamp gc_timestamp =0L -ADDR DB_vec db_vec =NULL -ADDR DB_vec0 db_vec0 =NULL -struct RB_red_blk_node* DB_root db_root =NULL -struct RB_red_blk_node* DB_nil db_nil =NULL -#endif /* defined(YAPOR) || defined(THREADS) */ +tr_fr_ptr sTR =NULL +tr_fr_ptr sTR0 =NULL +tr_fr_ptr new_TR =NULL +struct gc_mark_continuation* cont_top0 =NULL +struct gc_mark_continuation* cont_top =NULL +int discard_trail_entries =0 +gc_ma_hash_entry gc_ma_hash_table[GC_MAVARS_HASH_SIZE] void +gc_ma_hash_entry* gc_ma_h_top =NULL +gc_ma_hash_entry* gc_ma_h_list =NULL +UInt gc_timestamp =0L +ADDR db_vec =NULL +ADDR db_vec0 =NULL +struct RB_red_blk_node* db_root =NULL +struct RB_red_blk_node* db_nil =NULL +sigjmp_buf gc_restore void +struct array_entry* DynamicArrays =NULL PtoArrayEAdjust +struct static_array_entry* StaticArrays =NULL PtoArraySAdjust +struct global_entry* GlobalVariables =NULL PtoGlobalEAdjust +int AllowRestart =FALSE + +// Thread Local Area for Fast Storage of Intermediate Compiled Code +struct mem_blk* CMemFirstBlock =NULL +UInt CMemFirstBlockSz =0L -sigjmp_buf gc_restore Yap_gc_restore void -struct array_entry* dynamic_arrays DynamicArrays =NULL PtoArrayEAdjust -struct static_array_entry* static_arrays StaticArrays =NULL PtoArraySAdjust -struct global_entry* global_variables GlobalVariables =NULL PtoGlobalEAdjust -int allow_restart Yap_AllowRestart =FALSE - -// Thread Local Area for Fast Storage of Intermediate Compiled Code. -struct mem_blk* cmem_first_block Yap_CMemFirstBlock =NULL -UInt cmem_first_block_sz Yap_CMemFirstBlockSz =0L - -// Thread Local Area for Labels. -Int* label_first_array Yap_LabelFirstArray =NULL -UInt label_first_array_sz Yap_LabelFirstArraySz =0L +// Thread Local Area for Labels +Int* LabelFirstArray =NULL +UInt LabelFirstArraySz =0L // Thread Local Area for SWI-Prolog emulation routines. -struct PL_local_data *Yap_ld_ PL_local_data_p =Yap_InitThreadIO(wid) - -struct open_query_struct* _execution execution =NULL - +struct PL_local_data* PL_local_data_p =Yap_InitThreadIO(wid) #ifdef THREADS -struct thandle thread_handle ThreadHandle InitThreadHandle(wid) -#define FOREIGN_ThreadHandle(wid) (Yap_WLocal[(wid)]->thread_handle) -#define MY_ThreadHandle (Yap_WLocal[worker_id]->thread_handle) +struct thandle ThreadHandle InitThreadHandle(wid) +#endif /* THREADS */ + +#if defined(YAPOR) || defined(TABLING) +struct local_optyap_data optyap_data Yap_init_local_optyap_data(wid) +#endif /* YAPOR || TABLING */ + +int InterruptsDisabled =FALSE + +struct open_query_struct* execution =NULL + +#if LOW_LEVEL_TRACER +Int total_choicepoints =0 +#endif + +int consult_level =0 + +#if defined(YAPOR) || defined(THREADS) +lockvar SignalLock MkLock +#endif + +// Variables related to memory allocation +ADDR LocalBase void +ADDR GlobalBase void +ADDR TrailBase void +ADDR TrailTop void +char* ErrorMessage void +Term Error_Term void +#ifdef THREADS +Term Error_TYPE void +#else +yap_error_number Error_TYPE void +#endif +UInt Error_Size void +char ErrorSay[MAX_ERROR_MSG_SIZE] void +jmp_buf IOBotch void +TokEntry* tokptr void +TokEntry* toktide void +VarEntry* VarTable void +VarEntry* AnonVarTable void +sigjmp_buf RestartEnv void +char FileNameBuf[YAP_FILENAME_MAX] void +char FileNameBuf2[YAP_FILENAME_MAX] void + +// Prolog State + +Int PrologMode =BootMode +int CritLocks =0 + +//analyst.c +/* used to find out how many instructions of each kind are executed */ +#ifdef ANALYST +YAP_ULONG_LONG opcount[_std_top+1] void +YAP_ULONG_LONG 2opcount[_std_top+1][_std_top+1] void +#endif /* ANALYST */ + +//dbase.c +struct db_globs* s_dbg void + +//eval.c +yap_error_number matherror =YAP_NO_ERROR + +//grow.c +int heap_overflows =0 +Int total_heap_overflow_time =0 +int stack_overflows =0 +Int total_stack_overflow_time =0 +int delay_overflows =0 +Int total_delay_overflow_time =0 +int trail_overflows =0 +Int total_trail_overflow_time =0 +int atom_table_overflows =0 +Int total_atom_table_overflow_time =0 + +//load_dyld +#ifdef LOAD_DYLD +static dl_errno =0 +#endif + +//tracer.c +#ifdef LOW_LEVEL_TRACER +int do_trace_primitives =TRUE #endif -// END WORKER LOCAL STUFF END_WORKER_LOCAL + + diff --git a/misc/buildheap b/misc/buildheap index cb34dd679..85cfec22c 100644 --- a/misc/buildheap +++ b/misc/buildheap @@ -21,15 +21,15 @@ main :- file_filter_with_init('misc/HEAPFIELDS','H/hstruct.h',gen_struct,Warning,['hstruct.h','HEAPFIELDS']), file_filter_with_init('misc/HEAPFIELDS','H/dhstruct.h',gen_dstruct,Warning,['dhstruct.h','HEAPFIELDS']), file_filter_with_init('misc/HEAPFIELDS','H/rhstruct.h',gen_hstruct,Warning,['rhstruct.h','HEAPFIELDS']), - file_filter_with_init('misc/HEAPFIELDS','H/ihstruct.h',gen_init,Warning,['ihstruct.h','HEAPFIELDS']), - file_filter_with_init('misc/GLOBALS','H/hglobals.h',gen_struct,Warning,['hglobals.h','GLOBALS']), - file_filter_with_init('misc/GLOBALS','H/dglobals.h',gen_dstruct,Warning,['dglobals.h','GLOBALS']), - file_filter_with_init('misc/GLOBALS','H/rglobals.h',gen_hstruct,Warning,['rglobals.h','GLOBALS']), - file_filter_with_init('misc/GLOBALS','H/iglobals.h',gen_init,Warning,['iglobals.h','GLOBALS']), - file_filter_with_init('misc/LOCALS','H/hlocals.h',gen_struct,Warning,['hlocals.h','LOCALS']), - file_filter_with_init('misc/LOCALS','H/dlocals.h',gen_dstruct,Warning,['dlocals.h','LOCALS']), - file_filter_with_init('misc/LOCALS','H/rlocals.h',gen_hstruct,Warning,['rlocals.h','LOCALS']), - file_filter_with_init('misc/LOCALS','H/ilocals.h',gen_init,Warning,['ilocals.h','LOCALS']). + file_filter_with_init('misc/HEAPFIELDS','H/ihstruct.h',gen_init,Warning,['ihstruct.h','HEAPFIELDS']). + %file_filter_with_init('misc/GLOBALS','H/hglobals.h',gen_struct,Warning,['hglobals.h','GLOBALS']), + %file_filter_with_init('misc/GLOBALS','H/dglobals.h',gen_dstruct,Warning,['dglobals.h','GLOBALS']), + %file_filter_with_init('misc/GLOBALS','H/rglobals.h',gen_hstruct,Warning,['rglobals.h','GLOBALS']), + %file_filter_with_init('misc/GLOBALS','H/iglobals.h',gen_init,Warning,['iglobals.h','GLOBALS']), + %file_filter_with_init('misc/LOCALS','H/hlocals.h',gen_struct,Warning,['hlocals.h','LOCALS']), + %file_filter_with_init('misc/LOCALS','H/dlocals.h',gen_dstruct,Warning,['dlocals.h','LOCALS']), + %file_filter_with_init('misc/LOCALS','H/rlocals.h',gen_hstruct,Warning,['rlocals.h','LOCALS']), + %file_filter_with_init('misc/LOCALS','H/ilocals.h',gen_init,Warning,['ilocals.h','LOCALS']). warning('~n /* This file, ~a, was generated automatically by \"yap -L misc/buildheap\"~n please do not update, update misc/~a instead */~n~n'). @@ -119,13 +119,17 @@ fetch_name(Global) :- Global = "Yap_global->". fetch_name(Global) :- globals(worker), !, - Global = "WL->". + Global = "LOCAL->". fetch_name(Global) :- globals(worker_init), !, - Global = "FOREIGN(wid)->". + Global = "REMOTE(wid)->". fetch_name(Global) :- Global = "Yap_heap_regs->". +fetch_name(Global,RField,_) :- + globals(worker_init), !, + append("REMOTE(wid)->",RField,Global). +fetch_name(Global,_,Global). % handle *field[4] cut_c_stuff([0'*|Name], RName) :- !, % 'cut * @@ -174,31 +178,31 @@ gen_hstruct(Inp,Out) :- glue(Inp2, " ", Inp3), gen_hstruct(Inp3,Out). gen_hstruct(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkAT", _]), !, - fetch_name(Global), - append([" ",Global,Field," = AtomTermAdjust(Yap_heap_regs->",Field,");"], Out). + split(Inp," ",[_, Field, MacroName, "MkAT", _]), !, + fetch_name(Global,Field,MacroName), + append([" ",Global," = AtomTermAdjust(",Global,");"], Out). gen_hstruct(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkPred"| _]), !, + split(Inp," ",[_, Field, MacroName, "MkPred"| _]), !, cut_c_stuff(Field, RField), - fetch_name(Global), - append([" ",Global,RField," = PtoPredAdjust(Yap_heap_regs->",RField,");"], Out). + fetch_name(Global,RField,MacroName), + append([" ",Global," = PtoPredAdjust(",Global,");"], Out). gen_hstruct(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkOp", Name]), !, - fetch_name(Global), - append([" ",Global,Field," = Yap_opcode(",Name,");"], Out). + split(Inp," ",[_, Field, MacroName, "MkOp", Name]), !, + fetch_name(Global,Field,MacroName), + append([" ",Global," = Yap_opcode(",Name,");"], Out). gen_hstruct(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkLock"]), !, - fetch_name(Global), - append([" REINIT_LOCK(",Global,Field,");"], Out). + split(Inp," ",[_, Field, MacroName, "MkLock"]), !, + fetch_name(Global,Field,MacroName), + append([" REINIT_LOCK(",Global,");"], Out). gen_hstruct(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkRWLock"]), !, - fetch_name(Global), - append([" REINIT_RWLOCK(",Global,Field,");"], Out). + split(Inp," ",[_, Field, MacroName, "MkRWLock"]), !, + fetch_name(Global,Field,MacroName), + append([" REINIT_RWLOCK(",Global,");"], Out). gen_hstruct(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkInstE",OP]), !, + split(Inp," ",[_, Field, MacroName, "MkInstE",OP]), !, cut_c_stuff(Field, RField), - fetch_name(Global), - append([" ",Global,RField,"->opc = Yap_opcode(",OP,");"], Out). + fetch_name(Global,RField,MacroName), + append([" ",Global,"->opc = Yap_opcode(",OP,");"], Out). gen_hstruct(Inp,"") :- split(Inp," ",[_, _, _, _]), !. gen_hstruct(Inp,"") :- @@ -208,11 +212,11 @@ gen_hstruct(Inp,Restore) :- append("Restore",_,Restore0), !, append([" ",Restore0,";"],Restore). %' gen_hstruct(Inp,Out) :- - split(Inp," ",[_, Field, _, _, Adjust]), + split(Inp," ",[_, Field, MacroName, _, Adjust]), append(Adjust,"Adjust",_), !, cut_c_stuff(Field, RField), - fetch_name(Global), - append([" ",Global,RField," = ",Adjust,"(",Global,RField,");"], Out). + fetch_name(Global,RField,MacroName), + append([" ",Global," = ",Adjust,"(",Global,");"], Out). gen_hstruct(Inp,_) :- split(Inp," ",[_, _, _| _]), format(user_error,"OOPS: could not gen_hstruct for ~s~n",[Inp]). @@ -260,49 +264,53 @@ gen_init(Inp,Init) :- split(Inp," ",[_, _, _, Init0| _]), append("Yap_Init",_,Init0), !, append([" ",Init0,";"],Init). +gen_init(Inp,Init) :- + split(Inp," ",[_, _, _, Init0| _]), + append("Yap_init",_,Init0), !, + append([" ",Init0,";"],Init). gen_init(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkAT", AtomName]), !, + split(Inp," ",[_, Field, MacroName, "MkAT", AtomName]), !, cut_c_stuff(Field, RField), - fetch_name(Global), - append([" ",Global,RField," = MkAtomTerm(",AtomName,");"], Out). + fetch_name(Global,RField,MacroName), + append([" ",Global," = MkAtomTerm(",AtomName,");"], Out). gen_init(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkOp", Name]), !, - fetch_name(Global), - append([" ",Global,Field," = Yap_opcode(",Name,");"], Out). + split(Inp," ",[_, Field, MacroName, "MkOp", Name]), !, + fetch_name(Global,Field,MacroName), + append([" ",Global," = Yap_opcode(",Name,");"], Out). gen_init(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkLock"]), !, - fetch_name(Global), - append([" INIT_LOCK(",Global,Field,");"], Out). + split(Inp," ",[_, Field, MacroName, "MkLock"]), !, + fetch_name(Global,Field,MacroName), + append([" INIT_LOCK(",Global,");"], Out). gen_init(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkRWLock"]), !, - fetch_name(Global), - append([" INIT_RWLOCK(",Global,Field,");"], Out). + split(Inp," ",[_, Field, MacroName, "MkRWLock"]), !, + fetch_name(Global,Field,MacroName), + append([" INIT_RWLOCK(",Global,");"], Out). gen_init(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkInstE",OP]), !, + split(Inp," ",[_, Field, MacroName, "MkInstE",OP]), !, cut_c_stuff(Field, RField), - fetch_name(Global), - append([" ",Global,RField,"->opc = Yap_opcode(",OP,");"], Out). + fetch_name(Global,RField,MacroName), + append([" ",Global,"->opc = Yap_opcode(",OP,");"], Out). gen_init(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkPred", Atom, "0", Module]), !, + split(Inp," ",[_, Field, MacroName, "MkPred", Atom, "0", Module]), !, cut_c_stuff(Field, RField), - fetch_name(Global), - append([" ",Global,RField," = RepPredProp(PredPropByAtom(",Atom,",",Module,"));"], Out). + fetch_name(Global,RField,MacroName), + append([" ",Global," = RepPredProp(PredPropByAtom(",Atom,",",Module,"));"], Out). gen_init(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkPred", Atom, Arity, Module]), !, + split(Inp," ",[_, Field, MacroName, "MkPred", Atom, Arity, Module]), !, cut_c_stuff(Field, RField), - fetch_name(Global), - append([" ",Global,RField," = RepPredProp(PredPropByFunc(Yap_MkFunctor(",Atom,",",Arity,"),",Module,"));"], Out). + fetch_name(Global,RField,MacroName), + append([" ",Global," = RepPredProp(PredPropByFunc(Yap_MkFunctor(",Atom,",",Arity,"),",Module,"));"], Out). gen_init(Inp,Out) :- - split(Inp," ",[_, Field, _, "MkPred", Fun, Module]), !, + split(Inp," ",[_, Field, MacroName, "MkPred", Fun, Module]), !, cut_c_stuff(Field, RField), - fetch_name(Global), - append([" ",Global,RField," = RepPredProp(PredPropByFunc(",Fun,",",Module,"));"], Out). + fetch_name(Global,RField,MacroName), + append([" ",Global," = RepPredProp(PredPropByFunc(",Fun,",",Module,"));"], Out). gen_init(Inp,Out) :- - split(Inp," ",[_, Field, _, F0|_]), + split(Inp," ",[_, Field, MacroName, F0|_]), append("=",F,F0), !, cut_c_stuff(Field, RField), - fetch_name(Global), - append([" ",Global,RField," = ",F,";"], Out). + fetch_name(Global,RField,MacroName), + append([" ",Global," = ",F,";"], Out). gen_init(Inp,_) :- split(Inp," ",[_, _, _| _]), format(user_error,"OOPS: could not gen_init for ~s~n",[Inp]). diff --git a/misc/buildlocalglobal b/misc/buildlocalglobal new file mode 100644 index 000000000..4ae0d95c1 --- /dev/null +++ b/misc/buildlocalglobal @@ -0,0 +1,345 @@ + +:- use_module(library(lineutils), + [file_filter_with_init/5, + split/3, + glue/3]). + +:- use_module(library(lists), + [append/2, + append/3]). + +:- initialization(main). + +:- dynamic globals/1. + +:- yap_flag(write_strings,on). + +:- style_check(all). + +main :- + warning(Warning), + %file_filter_with_init('misc/HEAPFIELDS','H/hstruct.h',gen_struct,Warning,['hstruct.h','HEAPFIELDS']), + %file_filter_with_init('misc/HEAPFIELDS','H/dhstruct.h',gen_dstruct,Warning,['dhstruct.h','HEAPFIELDS']), + %file_filter_with_init('misc/HEAPFIELDS','H/rhstruct.h',gen_hstruct,Warning,['rhstruct.h','HEAPFIELDS']), + %file_filter_with_init('misc/HEAPFIELDS','H/ihstruct.h',gen_init,Warning,['ihstruct.h','HEAPFIELDS']), + file_filter_with_init('misc/GLOBALS','H/hglobals.h',gen_struct,Warning,['hglobals.h','GLOBALS']), + file_filter_with_init('misc/GLOBALS','H/dglobals.h',gen_dstruct,Warning,['dglobals.h','GLOBALS']), + file_filter_with_init('misc/GLOBALS','H/rglobals.h',gen_hstruct,Warning,['rglobals.h','GLOBALS']), + file_filter_with_init('misc/GLOBALS','H/iglobals.h',gen_init,Warning,['iglobals.h','GLOBALS']), + file_filter_with_init('misc/LOCALS','H/hlocals.h',gen_struct,Warning,['hlocals.h','LOCALS']), + file_filter_with_init('misc/LOCALS','H/dlocals.h',gen_dstruct,Warning,['dlocals.h','LOCALS']), + file_filter_with_init('misc/LOCALS','H/rlocals.h',gen_hstruct,Warning,['rlocals.h','LOCALS']), + file_filter_with_init('misc/LOCALS','H/ilocals.h',gen_init,Warning,['ilocals.h','LOCALS']). + +warning('~n /* This file, ~a, was generated automatically by \"yap -L misc/buildlocalglobal\"~n please do not update, update misc/~a instead */~n~n'). + + + +/* define the field */ +gen_struct(Inp,"") :- + Inp = [0'/,0'/|_], !. +gen_struct(Inp,"") :- + Inp = [0'/,0'*|_], !. +gen_struct(Inp, Out) :- + Inp = [0'#|_], !, Out = Inp. % ' +gen_struct(Inp,"") :- + Inp = [0'.|_], !. %' +gen_struct(Inp,Out) :- + Inp = "START_WORKER_LOCAL", !, + Out = "typedef struct worker_local {". +gen_struct(Inp,Out) :- + Inp = "END_WORKER_LOCAL", !, + Out = "} w_local;". +gen_struct(Inp,Out) :- + Inp = "START_GLOBAL_DATA", !, + Out = "typedef struct global_data {". +gen_struct(Inp,Out) :- + Inp = "END_GLOBAL_DATA", !, + Out = "} w_shared;". +gen_struct(Inp,Out) :- + Inp = "ATOMS", !, + Out = "#include \"tatoms.h\"". +gen_struct(Inp,Out) :- + split(Inp," ",["struct",Type, Field|_]), !, + append([" struct ",Type," ",Field,"_",";"], Out). +gen_struct(Inp,Out) :- + split(Inp," ",["union",Type, Field|_]), !, + append([" union ",Type," ",Field,"_",";"], Out). +gen_struct(Inp,"") :- + split(Inp," ",["void","void"|_]), !. +gen_struct(Inp,Out) :- + split(Inp," ",[Type, Field|_]), + split(Field,"[",[RField,VECField]), !, + append([" ",Type," ",RField,"_","[",VECField,";"], Out). +gen_struct(Inp,Out) :- + split(Inp," ",[Type, Field|_]), !, + append([" ",Type," ",Field,"_",";"], Out). +gen_struct(Inp,_) :- + split(Inp," ",[_, _, _| _]), + format(user_error,"OOPS: could not gen_struct for ~s~n",[Inp]). + +gen_dstruct(Inp,"") :- + Inp = [0'/,0'/|_], !. +gen_dstruct(Inp,"") :- + Inp = [0'/,0'*|_], !. +gen_dstruct(Inp, Out) :- + Inp = [0'#|_], !, Out = Inp. % ' +gen_dstruct(Inp,"") :- + Inp = "START_WORKER_LOCAL", !, + assert(globals(worker)). +gen_dstruct(Inp,"") :- + Inp = "END_WORKER_LOCAL", !, + retract(globals(worker)). +gen_dstruct(Inp,"") :- + Inp = "START_GLOBAL_DATA", !, + assert(globals(all)). +gen_dstruct(Inp,"") :- + Inp = "END_GLOBAL_DATA", !, + retract(globals(all)). +gen_dstruct(Inp,Out) :- + Inp = "ATOMS", !, + Out = "". +gen_dstruct(Inp,"") :- + split(Inp," ",["void","void"|_]), !. +gen_dstruct(Inp,Out) :- + split(Inp," ",["struct"|Inp2]), !, + glue(Inp2, " ", Inp3), + gen_dstruct(Inp3, Out). +gen_dstruct(Inp,Out) :- + split(Inp," ",["union"|Inp2]), !, + glue(Inp2, " ", Inp3), + gen_dstruct(Inp3, Out). +gen_dstruct(Inp,Out) :- + split(Inp," ",[".", Field,_|_]), !, + cut_c_stuff(Field, RField), + split(RField,".",[_,MField]), + fetch_name(Global,Global2,RField,MField), + append(["#define ",Global," ",Global2], Out). +gen_dstruct(Inp,Out) :- + split(Inp," ",[_, Field,_|_]), !, + cut_c_stuff(Field, RField), + fetch_name(Global,Global2,RField," "), + append(["#define ",Global," ",Global2], Out). +gen_dstruct(Inp,_) :- + split(Inp," ",[_, _, _| _]), + format(user_error,"OOPS: could not gen_dstruct for ~s~n",[Inp]). + +fetch_name(Global,Global2,RField," ") :- + globals(all), !, + append(["GLOBAL_", RField],Global), + append(["Yap_global->", RField,"_"],Global2). +fetch_name(Global,Global2,RField," ") :- + globals(worker), + append(["LOCAL_", RField],Global), + append(["LOCAL->", RField,"_"],Global2). +fetch_name(Global,Global2,RField," ") :- + globals(worker), !, + append(["REMOTE_", RField,"(wid)"],Global), + append(["REMOTE(wid)->", RField,"_"],Global2). +fetch_name(Global,Global2,RField,MField) :- + globals(worker), + append(["REMOTE_", MField,"(wid)"],Global), + append(["REMOTE(wid)->", RField],Global2). +fetch_name(Global,Global2,RField,MField) :- + globals(worker),!, + append(["LOCAL_", MField],Global), + append(["LOCAL->", RField],Global2). + +fetch_name(Global, RField) :- + globals(worker_init), !, + append(["REMOTE_", RField,"(wid)"],Global). +fetch_name(Global, RField) :- + globals(all), !, + append(["GLOBAL_", RField],Global). + +% handle *field[4] +cut_c_stuff([0'*|Name], RName) :- !, % 'cut * + cut_c_stuff(Name, RName). +cut_c_stuff(Name, RName) :- + cut_mat(Name, RName). + +cut_mat([], []). +cut_mat([0'[|_], []) :- !. %' +cut_mat(H.Name, H.RName) :- + cut_mat(Name, RName). + +gen_hstruct(Inp,"") :- + Inp = [0'/,0'/|_], !. +gen_hstruct(Inp,"") :- + Inp = [0'.|_], !. %' +gen_hstruct(Inp,"") :- + Inp = [0'/,0'*|_], !. +gen_hstruct(Inp,Out) :- + Inp = "ATOMS", !, + Out = "#include \"ratoms.h\"". +gen_hstruct(Inp,Out) :- + Inp = "START_WORKER_LOCAL", !, + Out = "static void RestoreWorker(int wid USES_REGS) {", + assert(globals(worker_init)). +gen_hstruct(Inp,Out) :- + Inp = "END_WORKER_LOCAL", !, + Out = "}", + retract(globals(worker_init)). +gen_hstruct(Inp,Out) :- + Inp = "START_GLOBAL_DATA", !, + Out = "static void RestoreGlobal(void) {", + assert(globals(all)). +gen_hstruct(Inp,Out) :- + Inp = "END_GLOBAL_DATA", !, + Out = "}", + retract(globals(all)). +gen_hstruct(Inp, Out) :- + Inp = [0'#|_], !, Out = Inp. % ' +gen_hstruct(Inp,Out) :- + split(Inp," ",["struct"|Inp2]), !, + glue(Inp2, " ", Inp3), + gen_hstruct(Inp3,Out). +gen_hstruct(Inp,Out) :- + split(Inp," ",["union"|Inp2]), !, + glue(Inp2, " ", Inp3), + gen_hstruct(Inp3,Out). +gen_hstruct(Inp,Out) :- + split(Inp," ",[_, Field, "MkAT", _]), !, + fetch_name(Global,Field), + append([" ",Global,Field," = AtomTermAdjust(Yap_heap_regs->",Field,");"], Out). +gen_hstruct(Inp,Out) :- + split(Inp," ",[_, Field, "MkPred"| _]), !, + cut_c_stuff(Field, RField), + fetch_name(Global,RField), + append([" ",Global,RField," = PtoPredAdjust(Yap_heap_regs->",RField,");"], Out). +gen_hstruct(Inp,Out) :- + split(Inp," ",[_, Field, "MkOp", Name]), !, + fetch_name(Global,Field), + append([" ",Global,Field," = Yap_opcode(",Name,");"], Out). +gen_hstruct(Inp,Out) :- + split(Inp," ",[_, Field, "MkLock"]), !, + fetch_name(Global,Field), + append([" REINIT_LOCK(",Global,");"], Out). +gen_hstruct(Inp,Out) :- + split(Inp," ",[_, Field,"MkRWLock"]), !, + fetch_name(Global,Field), + append([" REINIT_RWLOCK(",Global,Field,");"], Out). +gen_hstruct(Inp,Out) :- + split(Inp," ",[_, Field,"MkInstE",OP]), !, + cut_c_stuff(Field, RField), + fetch_name(Global,RField), + append([" ",Global,RField,"->opc = Yap_opcode(",OP,");"], Out). +gen_hstruct(Inp,"") :- + split(Inp," ",[_, _, _]), !. +gen_hstruct(Inp,"") :- + split(Inp," ",[_, _, _, "void"]), !. +gen_hstruct(Inp,Restore) :- + split(Inp," ",[_, _, _, Restore0]), + append("Restore",_,Restore0), !, + append([" ",Restore0,";"],Restore). %' +gen_hstruct(Inp,Out) :- + split(Inp," ",[_, Field, _, Adjust]), + append(Adjust,"Adjust",_), !, + cut_c_stuff(Field, RField), + fetch_name(Global,RField), + append([" ",Global," = ",Adjust,"(",Global,");"], Out). +gen_hstruct(Inp,_) :- + split(Inp," ",[_, _, _| _]), + format(user_error,"OOPS: could not gen_hstruct for ~s~n",[Inp]). + +gen_init(Inp,"") :- + Inp = [0'/,0'*|_], !. +gen_init(Inp,"") :- + Inp = [0'/,0'/|_], !. +gen_init(Inp, Out) :- + Inp = [0'#|_], !, Out = Inp. % ' +gen_init(Inp,Out) :- + Inp = "ATOMS", !, + Out = "#include \"iatoms.h\"". +gen_init(Inp,Out) :- + Inp = "START_WORKER_LOCAL", !, + Out = "static void InitWorker(int wid) {", + assert(globals(worker_init)). +gen_init(Inp,Out) :- + Inp = "END_WORKER_LOCAL", !, + Out = "}", + retract(globals(worker_init)). +gen_init(Inp,Out) :- + Inp = "START_GLOBAL_DATA", !, + Out = "static void InitGlobal(void) {", + assert(globals(all)). +gen_init(Inp,Out) :- + Inp = "END_GLOBAL_DATA", !, + Out = "}", + retract(globals(all)). +gen_init(Inp,Out) :- + split(Inp," ",["struct"|Inp2]), !, + glue(Inp2, " ", Inp3), + gen_init(Inp3, Out). +gen_init(Inp,Out) :- + split(Inp," ",["union"|Inp2]), !, + glue(Inp2, " ", Inp3), + gen_init(Inp3, Out). +gen_init(Inp,"") :- + split(Inp," ",[_, _, "void"|_]), !. +gen_init(Inp,Init) :- + split(Inp," ",[_, _, Init0| _]), + append("Init",_,Init0), !, + append([" ",Init0,";"],Init). +gen_init(Inp,Init) :- + split(Inp," ",[_, _, Init0| _]), + append("Yap_Init",_,Init0), !, + append([" ",Init0,";"],Init). +gen_init(Inp,Init) :- + split(Inp," ",[_, _, Init0| _]), + append("Yap_init",_,Init0), !, + append([" ",Init0,";"],Init). +gen_init(Inp,Out) :- + split(Inp," ",[_, Field, "MkAT", AtomName]), !, + cut_c_stuff(Field, RField), + fetch_name(Global,RField), + append([" ",Global," = MkAtomTerm(",AtomName,");"], Out). +gen_init(Inp,Out) :- + split(Inp," ",[_, Field, "MkOp", Name]), !, + fetch_name(Global,Field), + append([" ",Global," = Yap_opcode(",Name,");"], Out). +gen_init(Inp,Out) :- + split(Inp," ",[_, Field, "MkLock"]), !, + fetch_name(Global,Field), + append([" INIT_LOCK(",Global,");"], Out). +gen_init(Inp,Out) :- + split(Inp," ",[_, Field, "MkRWLock"]), !, + fetch_name(Global,Field), + append([" INIT_RWLOCK(",Global,");"], Out). +gen_init(Inp,Out) :- + split(Inp," ",[_, Field, "MkInstE",OP]), !, + cut_c_stuff(Field, RField), + fetch_name(Global,RField), + append([" ",Global,"->opc = Yap_opcode(",OP,");"], Out). +gen_init(Inp,Out) :- + split(Inp," ",[_, Field, "MkPred", Atom, "0", Module]), !, + cut_c_stuff(Field, RField), + fetch_name(Global,RField), + append([" ",Global," = RepPredProp(PredPropByAtom(",Atom,",",Module,"));"], Out). +gen_init(Inp,Out) :- + split(Inp," ",[_, Field, "MkPred", Atom, Arity, Module]), !, + cut_c_stuff(Field, RField), + fetch_name(Global,RField), + append([" ",Global," = RepPredProp(PredPropByFunc(Yap_MkFunctor(",Atom,",",Arity,"),",Module,"));"], Out). +gen_init(Inp,Out) :- + split(Inp," ",[_, Field, "MkPred", Fun, Module]), !, + cut_c_stuff(Field, RField), + fetch_name(Global,RField), + append([" ",Global," = RepPredProp(PredPropByFunc(",Fun,",",Module,"));"], Out). +gen_init(Inp,Out) :- + split(Inp," ",[".", Field,F0|_]), !, + cut_c_stuff(Field, RField), + split(RField,".",[_,MField]), + append("=",F,F0), !, + fetch_name(Global,MField), + append([" ",Global," = ",F,";"], Out). +gen_init(Inp,Out) :- + split(Inp," ",[_, Field, F0|_]), + append("=",F,F0), !, + cut_c_stuff(Field, RField), + fetch_name(Global,RField), + append([" ",Global," = ",F,";"], Out). +gen_init(Inp,_) :- + split(Inp," ",[_, _, _| _]), + format(user_error,"OOPS: could not gen_init for ~s~n",[Inp]). + diff --git a/packages/CLPBN/Makefile.in b/packages/CLPBN/Makefile.in index 0e9bd8fb9..c3cc626e7 100644 --- a/packages/CLPBN/Makefile.in +++ b/packages/CLPBN/Makefile.in @@ -30,7 +30,7 @@ CLPBN_SRCDIR = $(srcdir)/clpbn CLPBN_LEARNING_SRCDIR = $(srcdir)/learning -CLPBN_EXDIR = $(srcdir)/clpbn/examples +CLPBN_EXDIR = $(srcdir)/examples CLPBN_PROGRAMS= \ $(CLPBN_SRCDIR)/aggregates.yap \ @@ -51,7 +51,7 @@ CLPBN_PROGRAMS= \ $(CLPBN_SRCDIR)/table.yap \ $(CLPBN_SRCDIR)/topsort.yap \ $(CLPBN_SRCDIR)/utils.yap \ - $(CLPBN_SRCDIR)/vel.yap \ + $(CLPBN_SRCDIR)/ve.yap \ $(CLPBN_SRCDIR)/viterbi.yap \ $(CLPBN_SRCDIR)/xbif.yap @@ -71,6 +71,15 @@ CLPBN_SCHOOL_EXAMPLES= \ $(CLPBN_EXDIR)/School/school_64.yap \ $(CLPBN_EXDIR)/School/tables.yap +CLPBN_HMMER_EXAMPLES= \ + $(CLPBN_EXDIR)/HMMer/Artemia.fa \ + $(CLPBN_EXDIR)/HMMer/fasta.yap \ + $(CLPBN_EXDIR)/HMMer/globin.hmm \ + $(CLPBN_EXDIR)/HMMer/globin.yap \ + $(CLPBN_EXDIR)/HMMer/plan7.yap \ + $(CLPBN_EXDIR)/HMMer/scan.yap \ + $(CLPBN_EXDIR)/HMMer/score.yap + CLPBN_EXAMPLES= \ $(CLPBN_EXDIR)/cg.yap \ $(CLPBN_EXDIR)/sprinkler.yap @@ -80,9 +89,11 @@ install: $(CLBN_TOP) $(CLBN_PROGRAMS) $(CLPBN_PROGRAMS) mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn/learning mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn/examples/School + mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn/examples/HMMer for h in $(CLPBN_TOP); do $(INSTALL_DATA) $$h $(DESTDIR)$(SHAREDIR); done for h in $(CLPBN_PROGRAMS); do $(INSTALL_DATA) $$h $(DESTDIR)$(SHAREDIR)/clpbn; done for h in $(CLPBN_LEARNING_PROGRAMS); do $(INSTALL_DATA) $$h $(DESTDIR)$(SHAREDIR)/clpbn/learning; done for h in $(CLPBN_EXAMPLES); do $(INSTALL_DATA) $$h $(DESTDIR)$(SHAREDIR)/clpbn/examples; done for h in $(CLPBN_SCHOOL_EXAMPLES); do $(INSTALL_DATA) $$h $(DESTDIR)$(SHAREDIR)/clpbn/examples/School; done + for h in $(CLPBN_HMMER_EXAMPLES); do $(INSTALL_DATA) $$h $(DESTDIR)$(SHAREDIR)/clpbn/examples/HMMer; done diff --git a/packages/CLPBN/clpbn.yap b/packages/CLPBN/clpbn.yap index c28814f92..11e57eb45 100644 --- a/packages/CLPBN/clpbn.yap +++ b/packages/CLPBN/clpbn.yap @@ -7,6 +7,7 @@ clpbn_key/2, clpbn_init_solver/4, clpbn_run_solver/3, + clpbn_finalize_solver/1, clpbn_init_solver/5, clpbn_run_solver/4, clpbn_init_graph/1, @@ -28,13 +29,22 @@ :- attribute key/1, dist/2, evidence/1, starter/0. -:- use_module('clpbn/vel', - [vel/3, - check_if_vel_done/1, - init_vel_solver/4, - run_vel_solver/3 +:- use_module('clpbn/ve', + [ve/3, + check_if_ve_done/1, + init_ve_solver/4, + run_ve_solver/3 ]). +:- use_module('clpbn/bp', + [bp/3, + check_if_bp_done/1, + init_bp_solver/4, + run_bp_solver/3, + finalize_bp_solver/1 + ]). + + :- use_module('clpbn/jt', [jt/3, init_jt_solver/4, @@ -53,6 +63,14 @@ run_gibbs_solver/3 ]). +:- use_module('clpbn/bp', + [bp/3, + check_if_bp_done/1, + init_bp_solver/4, + run_bp_solver/3, + finalize_bp_solver/1 + ]). + :- use_module('clpbn/pgrammar', [init_pcg_solver/4, run_pcg_solver/3, @@ -92,8 +110,8 @@ :- dynamic solver/1,output/1,use/1,suppress_attribute_display/1, parameter_softening/1, em_solver/1. -solver(vel). -em_solver(vel). +solver(ve). +em_solver(ve). %output(xbif(user_error)). %output(gviz(user_error)). @@ -142,6 +160,18 @@ clpbn_flag(parameter_softening,Before,After) :- % ,writeln({Var = Key with Dist}) . +% +% make sure a query variable is reachable by the garbage collector. +% +store_var(El) :- + catch(b_getval(clpbn_qvars,Q.Tail), _, init_clpbn_vars(El, Q, Tail)), + Tail = [El|NewTail], + b_setval(clpbn_qvars, [Q|NewTail]). + +init_clpbn_vars(El, Q, Tail) :- + Q = [El|Tail], + b_setval(clpbn_qvars, [Q|Tail]). + check_constraint(Constraint, _, _, Constraint) :- var(Constraint), !. check_constraint((A->D), _, _, (A->D)) :- var(A), !. check_constraint((([A|B].L)->D), Vars, NVars, (([A|B].NL)->D)) :- !, @@ -162,8 +192,10 @@ add_evidence(V,Key,Distinfo,NV) :- nonvar(V), !, get_evidence_position(V, Distinfo, Pos), check_stored_evidence(Key, Pos), + store_var(NV), clpbn:put_atts(NV,evidence(Pos)). add_evidence(V,K,_,V) :- + store_var(V), add_evidence(K,V). clpbn_marginalise(V, Dist) :- @@ -183,7 +215,7 @@ project_attributes(GVars, AVars) :- clpbn_vars(AVars, DiffVars, AllVars), get_clpbn_vars(GVars,CLPBNGVars0), simplify_query_vars(CLPBNGVars0, CLPBNGVars), - (output(xbif(XBifStream)) -> clpbn2xbif(XBifStream,vel,AllVars) ; true), + (output(xbif(XBifStream)) -> clpbn2xbif(XBifStream,ve,AllVars) ; true), (output(gviz(XBifStream)) -> clpbn2gviz(XBifStream,sort,AllVars,GVars) ; true), ( Solver = graphs @@ -225,10 +257,12 @@ get_rid_of_ev_vars([V|LVs0],[V|LVs]) :- % do nothing if we don't have query variables to compute. write_out(graphs, _, AVars, _) :- clpbn2graph(AVars). -write_out(vel, GVars, AVars, DiffVars) :- - vel(GVars, AVars, DiffVars). +write_out(ve, GVars, AVars, DiffVars) :- + ve(GVars, AVars, DiffVars). write_out(jt, GVars, AVars, DiffVars) :- jt(GVars, AVars, DiffVars). +write_out(bp, GVars, AVars, DiffVars) :- + bp(GVars, AVars, DiffVars). write_out(gibbs, GVars, AVars, DiffVars) :- gibbs(GVars, AVars, DiffVars). write_out(bnt, GVars, AVars, DiffVars) :- @@ -315,11 +349,14 @@ bind_clpbn(_, Var, _, _, _, _, []) :- use(bnt), check_if_bnt_done(Var), !. bind_clpbn(_, Var, _, _, _, _, []) :- - use(vel), - check_if_vel_done(Var), !. + use(ve), + check_if_ve_done(Var), !. +bind_clpbn(_, Var, _, _, _, _, []) :- + use(bp), + check_if_bp_done(Var), !. bind_clpbn(_, Var, _, _, _, _, []) :- use(jt), - check_if_vel_done(Var), !. + check_if_ve_done(Var), !. bind_clpbn(T, Var, Key0, _, _, _, []) :- get_atts(Var, [key(Key)]), !, ( @@ -379,18 +416,21 @@ clpbn_key(Var,Key) :- % values at the end of the day. % clpbn_init_solver(LVs, Vs0, VarsWithUnboundKeys, State) :- - solver(Solver), + solver(Solver), clpbn_init_solver(Solver, LVs, Vs0, VarsWithUnboundKeys, State). clpbn_init_solver(gibbs, LVs, Vs0, VarsWithUnboundKeys, State) :- init_gibbs_solver(LVs, Vs0, VarsWithUnboundKeys, State). -clpbn_init_solver(vel, LVs, Vs0, VarsWithUnboundKeys, State) :- - init_vel_solver(LVs, Vs0, VarsWithUnboundKeys, State). +clpbn_init_solver(ve, LVs, Vs0, VarsWithUnboundKeys, State) :- + init_ve_solver(LVs, Vs0, VarsWithUnboundKeys, State). +clpbn_init_solver(bp, LVs, Vs0, VarsWithUnboundKeys, State) :- + init_bp_solver(LVs, Vs0, VarsWithUnboundKeys, State). clpbn_init_solver(jt, LVs, Vs0, VarsWithUnboundKeys, State) :- init_jt_solver(LVs, Vs0, VarsWithUnboundKeys, State). clpbn_init_solver(pcg, LVs, Vs0, VarsWithUnboundKeys, State) :- init_pcg_solver(LVs, Vs0, VarsWithUnboundKeys, State). + % % LVs is the list of lists of variables to marginalise % Vs is the full graph @@ -398,15 +438,21 @@ clpbn_init_solver(pcg, LVs, Vs0, VarsWithUnboundKeys, State) :- % % clpbn_run_solver(LVs, LPs, State) :- - solver(Solver), + solver(Solver), clpbn_run_solver(Solver, LVs, LPs, State). clpbn_run_solver(gibbs, LVs, LPs, State) :- run_gibbs_solver(LVs, LPs, State). -clpbn_run_solver(vel, LVs, LPs, State) :- - run_vel_solver(LVs, LPs, State). + +clpbn_run_solver(ve, LVs, LPs, State) :- + run_ve_solver(LVs, LPs, State). + +clpbn_run_solver(bp, LVs, LPs, State) :- + run_bp_solver(LVs, LPs, State). + clpbn_run_solver(jt, LVs, LPs, State) :- run_jt_solver(LVs, LPs, State). + clpbn_run_solver(pcg, LVs, LPs, State) :- run_pcg_solver(LVs, LPs, State). @@ -415,3 +461,10 @@ add_keys(Key1+V1,_Key2,Key1+V1). clpbn_init_graph(pcg) :- !, pcg_init_graph. clpbn_init_graph(_). + +clpbn_finalize_solver(State) :- + solver(bp), !, + functor(State, _, Last), + arg(Last, State, Info), + finalize_bp_solver(Info). +clpbn_finalize_solver(_State). diff --git a/packages/CLPBN/clpbn/aggregates.yap b/packages/CLPBN/clpbn/aggregates.yap index ed83ebb95..3c189756d 100644 --- a/packages/CLPBN/clpbn/aggregates.yap +++ b/packages/CLPBN/clpbn/aggregates.yap @@ -52,7 +52,7 @@ cpt_average(AllVars, Key, Els0, Tab, Vs, NewVs) :- cpt_average(AllVars, Key, Els0, 1.0, Tab, Vs, NewVs). % support variables with evidence from domain. This should make everyone's life easier. -cpt_average([Ev|Vars], Key, Els0, Softness, p(Els0, CPT, NewParents), Vs, NewVs) :- +cpt_average([Ev|Vars], Key, Els0, Softness, pf(Els0, MAT, NewParents), Vs, NewVs) :- find_evidence(Vars, 0, TotEvidence, RVars), build_avg_table(RVars, Vars, Els0, Key, TotEvidence, Softness, MAT0, NewParents0, Vs, IVs), include_qevidence(Ev, MAT0, MAT, NewParents0, NewParents, Vs, IVs, NewVs). diff --git a/packages/CLPBN/clpbn/bp.yap b/packages/CLPBN/clpbn/bp.yap index da4043a4f..417958298 100644 --- a/packages/CLPBN/clpbn/bp.yap +++ b/packages/CLPBN/clpbn/bp.yap @@ -1,157 +1,152 @@ -/*********************************** +/************************************************ Belief Propagation in CLP(BN) - - This should connect to C-code. -*********************************/ +**************************************************/ -:- module(clpbn_bp, [ - bp/3, - check_if_bp_done/1, - init_bp_solver/4, - run_bp_solver/3]). - - -:- use_module(library('clpbn/aggregates'), - [check_for_agg_vars/2]). - -:- use_module(library('clpbn/connected'), - [init_influences/3, - influences/5 +:- module(clpbn_bp, + [bp/3, + check_if_bp_done/1, + init_bp_solver/4, + run_bp_solver/3, + finalize_bp_solver/1 ]). + :- use_module(library('clpbn/dists'), [dist/4, get_dist_domain/2, + get_dist_domain_size/2, get_dist_params/2 ]). -:- use_module(library('clpbn/display'), - [clpbn_bind_vals/3]). -:-use_module(library(lists), - [append/3, - memberchk/2 - ]). +:- use_module(library('clpbn/display'), + [clpbn_bind_vals/3]). + + +:- use_module(library(atts)). + +:- use_module(library(charsio)). :- load_foreign_files(['horus'], [], init_predicates). -:- attribute all_diffs/1. +:- attribute id/1. + +:- dynamic num_bayes_nets/1. check_if_bp_done(_Var). -% -% implementation of belief propagation -% -% A1 = +QueryVars -> sets of independent marginalization variables -% A2 = *AllVars -> list of all variables -% A3 = -Output -> output probabilities -% -% Other important variables: -% -% State0 initialized graph, is used to pass data from initialization -% to query solving (eg, State might be the JT and be used to run -% different queries). -% +num_bayes_nets(0). + + bp([[]],_,_) :- !. -bp([QueryVars],AllVars,Output) :- - writeln(queryVars:QueryVars), - writeln(allVars:AllVars), - % init_bp_solver([QueryVars], AllVars, Output, State), - run_bp_solver([QueryVars], [AllVars], _State), - % bind probs back to variables so that they can be output. - clpbn_bind_vals([QueryVars],[LPs],Output). - -% initialise necessary data for query solver -init_bp_solver(Qs, AllVars, _, graph(LVis)) :- - % replace average, max, min and friends by binary nodes. - check_for_agg_vars(AllVars, UnFoldedVars), - % replace the variables reachable from G - init_influences(UnfoldedVars, G, RG), - init_bp_solver_for_questions(Qs, G, RG, _, LVis). - -init_bp_solver_for_questions([], _, _, [], []). -init_bp_solver_for_questions([Vs|MVs], G, RG, [NVs|MNVs0], [NVs|LVis]) :- - % find variables connectd to Vs - influences(Vs, _, NVs0, G, RG), - sort(NVs0, NVs), - init_bp_solver_for_questions(MVs, G, RG, MNVs0, LVis). +bp([QueryVars], AllVars, Output) :- + init_bp_solver(_, AllVars, _, BayesNet), + run_bp_solver([QueryVars], LPs, BayesNet), + finalize_bp_solver(BayesNet), + clpbn_bind_vals([QueryVars], LPs, Output). -% use a findall to recover space without needing for GC -run_bp_solver(LVs, LPs, _) :- - findall(Ps, solve_bp(LVs, LPs, Ps), LPs). +init_bp_solver(_, AllVars, _, (BayesNet, DistIds)) :- + %inc_num_bayes_nets, + %(showprofres(50) -> true ; true), + process_ids(AllVars, 0, DistIds0), + get_vars_info(AllVars, VarsInfo), + sort(DistIds0, DistIds), + %(num_bayes_nets(0) -> writeln(vars:VarsInfo) ; true), + %(num_bayes_nets(0) -> writeln(dists:DistsInfo) ; true), + create_network(VarsInfo, BayesNet). + %get_extra_vars_info(AllVars, ExtraVarsInfo), + %set_extra_vars_info(BayesNet, ExtraVarsInfo). + - -solve_bp([LVs|_], [NVs0|_], Ps) :- - get_vars_info(NVs0, LVi), - get_dists_info(NVs0, Dists), - process(LVi, Dists, LVs, Ps). -solve_bp([_|MoreLVs], [_|MoreLVis], Ps) :- - solve_bp(MoreLVs, MoreLVis, Ps). +process_ids([], _, []). +process_ids([V|Vs], VarId0, [DistId|DistIds]) :- + clpbn:get_atts(V, [dist(DistId, _)]), !, + put_atts(V, [id(VarId0)]), + VarId is VarId0 + 1, + process_ids(Vs, VarId, DistIds). +process_ids([_|Vs], VarId, DistIds) :- + process_ids(Vs, VarId, DistIds). get_vars_info([], []). -get_vars_info([V|Vs], [var(V, Id, Parents, NParents, Ev)|LV]) :- - clpbn:get_atts(V, [dist(Id, Parents)]), !, - length(Parents, NParents), +get_vars_info([V|Vs], [var(VarId, DSize, Ev, ParentIds, DistId)|VarsInfo]) :- + clpbn:get_atts(V, [dist(DistId, Parents)]), !, + get_atts(V, [id(VarId)]), + get_dist_domain_size(DistId, DSize), get_evidence(V, Ev), - get_vars_info(Vs, LV). -get_vars_info([_|Vs], LV) :- - get_vars_info(Vs, LV). + vars2ids(Parents, ParentIds), + get_vars_info(Vs, VarsInfo). +get_vars_info([_|Vs], VarsInfo) :- + get_vars_info(Vs, VarsInfo). + + +vars2ids([], []). +vars2ids([V|QueryVars], [VarId|Ids]) :- + get_atts(V, [id(VarId)]), + vars2ids(QueryVars, Ids). get_evidence(V, Ev) :- clpbn:get_atts(V, [evidence(Ev)]), !. -get_evidence(V, -1). % no evidence !!! +get_evidence(_V, -1). % no evidence !!! -get_dists_info([],[]). -get_dists_info([V|Vs], [dist(Id, Domain, DSize, Params, NParams) | Dists]) :- - clpbn:get_atts(V, [dist(Id, _)]), !, - get_dist_domain(Id, Domain), - length(Domain, DSize), +get_extra_vars_info([], []). +get_extra_vars_info([V|Vs], [v(VarId, Label, Domain)|VarsInfo]) :- + get_atts(V, [id(VarId)]), !, + clpbn:get_atts(V, [key(Key),dist(DistId, _)]), + term_to_atom(Key, Label), + get_dist_domain(DistId, Domain0), + numbers2atoms(Domain0, Domain), + get_extra_vars_info(Vs, VarsInfo). +get_extra_vars_info([_|Vs], VarsInfo) :- + get_extra_vars_info(Vs, VarsInfo). + + +numbers2atoms([], []). +numbers2atoms([Atom|L0], [Atom|L]) :- + atom(Atom), !, + numbers2atoms(L0, L). +numbers2atoms([Number|L0], [Atom|L]) :- + number_atom(Number, Atom), + numbers2atoms(L0, L). + + +run_bp_solver(QVsL0, LPs, (BayesNet, DistIds)) :- + get_dists_parameters(DistIds, DistsParams), + set_parameters(BayesNet, DistsParams), + process_query_list(QVsL0, QVsL), + %writeln(' qvs':QVsL), + %(num_bayes_nets(1506) -> writeln(qvs:QVsL) ; true), + run_solver(BayesNet, QVsL, LPs). + + +process_query_list([], []). +process_query_list([[V]|QueryVars], [VarId|Ids]) :- !, + get_atts(V, [id(VarId)]), + process_query_list(QueryVars, Ids). +process_query_list([Vs|QueryVars], [VarIds|Ids]) :- + vars2ids(Vs, VarIds), + process_query_list(QueryVars, Ids). + + +get_dists_parameters([],[]). +get_dists_parameters([Id|Ids], [dist(Id, Params)|DistsInfo]) :- get_dist_params(Id, Params), - length(Params, NParams), - get_dists_info(Vs, Dists). -get_dists_info([_|Vs], Dists) :- - get_dists_info(Vs, Dists). + get_dists_parameters(Ids, DistsInfo). -% +Vars is a list containing info about every clpbn variables -% +Dists is a list containing info about distributions -% +QVs is a list containing the query variables -% -Out is some output term stating the probabilities -process(Vars, Dists, QVs, Out) :- - write('vars = '), writeln(Vars), - order_vars(Vars, [], OrderedVars), - write('ovars = '), writeln(OrderedVars), - write('dists = '), writeln(Dists), - write('qvs = '), writeln(QVs), - length(OrderedVars, NVars), - length(Dists, NDists), - %create_network(OrderedVars, NVars, Dists, NDists, BNet), - length(QVs, NQVs), - run_solver(BNet, QVs, NQVs, Out), - free_memory(BNet). +finalize_bp_solver((BayesNet, _)) :- + delete_bayes_net(BayesNet). -order_vars([V], _, [V]) :- !. -order_vars([var(V, Id, Parents, NParents, Ev)|Vs], ParsedVars, [var(V, Id, Parents, NParents, Ev)|OrderedVars]) :- - \+ memberchk(V, ParsedVars), - parents_defined(Parents, ParsedVars), !, - order_vars(Vs, [V|ParsedVars], OrderedVars). -order_vars([var(V, Id, Parents, NParents, Ev)|Vs], ParsedVars, OrderedVars) :- - append(Vs, [var(V, Id, Parents, NParents, Ev)], NVs), - order_vars(NVs, ParsedVars, OrderedVars). +inc_num_bayes_nets :- + retract(num_bayes_nets(Count0)), + Count is Count0 + 1, + assert(num_bayes_nets(Count)). - -parents_defined([], _) :- !. -parents_defined([Parent|Parents], ParsedVars) :- - memberchk(Parent, ParsedVars), - parents_defined(Parents, ParsedVars). - -% f(F), b(B). ----> FAIL diff --git a/packages/CLPBN/clpbn/bp/BPSolver.cpp b/packages/CLPBN/clpbn/bp/BPSolver.cpp new file mode 100755 index 000000000..1d3566aa8 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/BPSolver.cpp @@ -0,0 +1,891 @@ +#include +#include +#include +#include +#include +#include + +#include "BPSolver.h" +#include "BpNode.h" + + +BPSolver* Edge::klass = 0; +StatisticMap Statistics::stats_; +unsigned Statistics::numCreatedNets = 0; +unsigned Statistics::numSolvedPolyTrees = 0; +unsigned Statistics::numSolvedLoopyNets = 0; +unsigned Statistics::numUnconvergedRuns = 0; +unsigned Statistics::maxIterations = 0; +unsigned Statistics::totalOfIterations = 0; + + +BPSolver::BPSolver (const BayesNet& bn) : Solver (&bn) +{ + bn_ = &bn; + forceGenericSolver_ = false; + //forceGenericSolver_ = true; + schedule_ = S_SEQ_FIXED; + //schedule_ = S_SEQ_RANDOM; + //schedule_ = S_PARALLEL; + //schedule_ = S_MAX_RESIDUAL; + maxIter_ = 205; + accuracy_ = 0.000001; +} + + + +BPSolver::~BPSolver (void) +{ + for (unsigned i = 0; i < msgs_.size(); i++) { + delete msgs_[i]; + } +} + + + +void +BPSolver::runSolver (void) +{ + if (DL >= 1) { + //bn_->printNetwork(); + } + + clock_t start_ = clock(); + if (bn_->isSingleConnected() && !forceGenericSolver_) { + runPolyTreeSolver(); + Statistics::numSolvedPolyTrees ++; + } else { + runGenericSolver(); + Statistics::numSolvedLoopyNets ++; + if (nIter_ >= maxIter_) { + Statistics::numUnconvergedRuns ++; + } else { + Statistics::updateIterations (nIter_); + } + if (DL >= 1) { + cout << endl; + if (nIter_ < maxIter_) { + cout << "Belief propagation converged in " ; + cout << nIter_ << " iterations" << endl; + } else { + cout << "The maximum number of iterations was hit, terminating..." ; + cout << endl; + } + } + } + double time = (double (clock() - start_)) / CLOCKS_PER_SEC; + unsigned size = bn_->getNumberOfNodes(); + Statistics::updateStats (size, time); + //if (size > 30) { + // stringstream ss; + // ss << size << "." << Statistics::getCounting (size) << ".dot" ; + // bn_->exportToDotFile (ss.str().c_str()); + //} +} + + + +ParamSet +BPSolver::getPosterioriOf (const Variable* var) const +{ + assert (var); + assert (var == bn_->getNode (var->getVarId())); + assert (var->getIndex() < msgs_.size()); + return msgs_[var->getIndex()]->getBeliefs(); +} + + + + +ParamSet +BPSolver::getJointDistribution (const NodeSet& jointVars) const +{ + if (DL >= 1) { + cout << "calculating joint distribuition on: " ; + for (unsigned i = 0; i < jointVars.size(); i++) { + cout << jointVars[i]->getLabel() << " " ; + } + cout << endl; + } + + //BayesNet* workingNet = bn_->pruneNetwork (bn_->getNodes()); + //FIXME see if this works: + BayesNet* workingNet = bn_->pruneNetwork (jointVars); + BayesNode* node = workingNet->getNode (jointVars[0]->getVarId()); + + BayesNet* tempNet = workingNet->pruneNetwork (node); + BPSolver solver (*tempNet); + solver.runSolver(); + + NodeSet observedVars = { jointVars[0] }; + + node = tempNet->getNode (jointVars[0]->getVarId()); + ParamSet prevBeliefs = solver.getPosterioriOf (node); + + delete tempNet; + + for (unsigned i = 1; i < jointVars.size(); i++) { + node = workingNet->getNode (observedVars[i - 1]->getVarId()); + if (!node->hasEvidence()) { + node->setEvidence (0); + } + node = workingNet->getNode (jointVars[i]->getVarId()); + tempNet = workingNet->pruneNetwork (node); + + ParamSet allBeliefs; + vector confs = + BayesNet::getDomainConfigurationsOf (observedVars); + for (unsigned j = 0; j < confs.size(); j++) { + for (unsigned k = 0; k < observedVars.size(); k++) { + node = tempNet->getNode (observedVars[k]->getVarId()); + if (!observedVars[k]->hasEvidence()) { + if (node) { + node->setEvidence (confs[j][k]); + } else { + // FIXME try optimize + //assert (false); + cout << observedVars[k]->getLabel(); + cout << " is not in temporary net!" ; + cout << endl; + } + } else { + cout << observedVars[k]->getLabel(); + cout << " already has evidence in original net!" ; + cout << endl; + } + } + BPSolver solver (*tempNet); + node = tempNet->getNode (jointVars[i]->getVarId()); + solver.runSolver(); + ParamSet beliefs = solver.getPosterioriOf (node); + for (unsigned k = 0; k < beliefs.size(); k++) { + allBeliefs.push_back (beliefs[k]); + } + } + + int count = -1; + for (unsigned j = 0; j < allBeliefs.size(); j++) { + if (j % jointVars[i]->getDomainSize() == 0) { + count ++; + } + allBeliefs[j] *= prevBeliefs[count]; + } + prevBeliefs = allBeliefs; + observedVars.push_back (jointVars[i]); + delete tempNet; + } + delete workingNet; + return prevBeliefs; +} + + + +void +BPSolver::initializeSolver (void) +{ + if (DL >= 1) { + cout << "Initializing solver" << endl; + cout << "-> schedule = "; + if (forceGenericSolver_) { + switch (schedule_) { + case S_SEQ_FIXED: cout << "sequential fixed" ; break; + case S_SEQ_RANDOM: cout << "sequential random" ; break; + case S_PARALLEL: cout << "parallel" ; break; + case S_MAX_RESIDUAL: cout << "max residual" ; break; + } + } else { + cout << "polytree solver" ; + } + cout << endl; + cout << "-> max iters = " << maxIter_ << endl; + cout << "-> accuracy = " << accuracy_ << endl; + cout << endl; + } + + const NodeSet& nodes = bn_->getNodes(); + for (unsigned i = 0; i < msgs_.size(); i++) { + delete msgs_[i]; + } + msgs_.clear(); + msgs_.reserve (nodes.size()); + updateOrder_.clear(); + sortedOrder_.clear(); + edgeMap_.clear(); + + for (unsigned i = 0; i < nodes.size(); i++) { + msgs_.push_back (new BpNode (nodes[i])); + } + + NodeSet roots = bn_->getRootNodes(); + for (unsigned i = 0; i < roots.size(); i++) { + const ParamSet& params = roots[i]->getParameters(); + ParamSet& piVals = M(roots[i])->getPiValues(); + for (int ri = 0; ri < roots[i]->getDomainSize(); ri++) { + piVals[ri] = params[ri]; + } + } +} + + + +void +BPSolver::incorporateEvidence (BayesNode* x) +{ + ParamSet& piVals = M(x)->getPiValues(); + ParamSet& ldVals = M(x)->getLambdaValues(); + for (int xi = 0; xi < x->getDomainSize(); xi++) { + piVals[xi] = 0.0; + ldVals[xi] = 0.0; + } + piVals[x->getEvidence()] = 1.0; + ldVals[x->getEvidence()] = 1.0; +} + + + +void +BPSolver::runPolyTreeSolver (void) +{ + initializeSolver(); + const NodeSet& nodes = bn_->getNodes(); + + // Hack: I need this else this can happen with bayes ball + // Variable: 174 + // Id: 174 + // Domain: -1, 0, 1 + // Evidence: 1 + // Parents: + // Childs: 176 + // cpt + // ---------------------------------------------------- + // -1 0 0 0 0 ... + // 0 0.857143 0.857143 0.857143 0.857143 ... + // 1 0.142857 0.142857 0.142857 0.142857 ... + // the cpt for this node would be 0,0,0 + + for (unsigned i = 0; i < nodes.size(); i++) { + if (nodes[i]->hasEvidence()) { + incorporateEvidence (nodes[i]); + } + } + + // first compute all node marginals ... + NodeSet roots = bn_->getRootNodes(); + for (unsigned i = 0; i < roots.size(); i++) { + const NodeSet& childs = roots[i]->getChilds(); + for (unsigned j = 0; j < childs.size(); j++) { + polyTreePiMessage (roots[i], childs[j]); + } + } + // then propagate the evidence + for (unsigned i = 0; i < nodes.size(); i++) { + if (nodes[i]->hasEvidence()) { + incorporateEvidence (nodes[i]); + const NodeSet& parents = nodes[i]->getParents(); + for (unsigned j = 0; j < parents.size(); j++) { + if (!parents[j]->hasEvidence()) { + polyTreeLambdaMessage (nodes[i], parents[j]); + } + } + const NodeSet& childs = nodes[i]->getChilds(); + for (unsigned j = 0; j < childs.size(); j++) { + polyTreePiMessage (nodes[i], childs[j]); + } + } + } +} + + + +void +BPSolver::polyTreePiMessage (BayesNode* z, BayesNode* x) +{ + if (DL >= 1) { + cout << PI << " (" << z->getLabel(); + cout << " --> " << x->getLabel(); + cout << ")" << endl; + } + calculateNextPiMessage (z, x); + updatePiMessage (z, x); + + if (!x->hasEvidence()) { + updatePiValues (x); + const NodeSet& xChilds = x->getChilds(); + for (unsigned i = 0; i < xChilds.size(); i++) { + polyTreePiMessage (x, xChilds[i]); + } + } + + if (M(x)->hasReceivedChildInfluence()) { + const NodeSet& xParents = x->getParents(); + for (unsigned i = 0; i < xParents.size(); i++) { + if (xParents[i] != z && !xParents[i]->hasEvidence()) { + polyTreeLambdaMessage (x, xParents[i]); + } + } + } +} + + + +void +BPSolver::polyTreeLambdaMessage (BayesNode* y, BayesNode* x) +{ + if (DL >= 1) { + cout << LD << " (" << y->getLabel(); + cout << " --> " << x->getLabel(); + cout << ")" << endl; + } + calculateNextLambdaMessage (y, x); + updateLambdaMessage (y, x); + updateLambdaValues (x); + + const NodeSet& xParents = x->getParents(); + for (unsigned i = 0; i < xParents.size(); i++) { + if (!xParents[i]->hasEvidence()) { + polyTreeLambdaMessage (x, xParents[i]); + } + } + + const NodeSet& xChilds = x->getChilds(); + for (unsigned i = 0; i < xChilds.size(); i++) { + if (xChilds[i] != y) { + polyTreePiMessage (x, xChilds[i]); + } + } +} + + + +void +BPSolver::runGenericSolver() +{ + initializeSolver(); + const NodeSet& nodes = bn_->getNodes(); + for (unsigned i = 0; i < nodes.size(); i++) { + if (nodes[i]->hasEvidence()) { + incorporateEvidence (nodes[i]); + } + } + + for (unsigned i = 0; i < nodes.size(); i++) { + // pi messages + const NodeSet& childs = nodes[i]->getChilds(); + for (unsigned j = 0; j < childs.size(); j++) { + updateOrder_.push_back (Edge (nodes[i], childs[j], PI_MSG)); + } + // lambda messages + const NodeSet& parents = nodes[i]->getParents(); + for (unsigned j = 0; j < parents.size(); j++) { + if (!parents[j]->hasEvidence()) { + updateOrder_.push_back (Edge (nodes[i], parents[j], LAMBDA_MSG)); + } + } + } + + nIter_ = 0; + while (!converged() && nIter_ < maxIter_) { + + nIter_++; + if (DL >= 1) { + cout << endl; + cout << "****************************************" ; + cout << "****************************************" ; + cout << endl; + cout << " Iteration " << nIter_ << endl; + cout << "****************************************" ; + cout << "****************************************" ; + cout << endl; + } + + switch (schedule_) { + + case S_SEQ_RANDOM: + random_shuffle (updateOrder_.begin(), updateOrder_.end()); + // no break + + case S_SEQ_FIXED: + for (unsigned i = 0; i < updateOrder_.size(); i++) { + calculateNextMessage (updateOrder_[i]); + updateMessage (updateOrder_[i]); + updateValues (updateOrder_[i]); + } + break; + + case S_PARALLEL: + for (unsigned i = 0; i < updateOrder_.size(); i++) { + calculateNextMessage (updateOrder_[i]); + } + for (unsigned i = 0; i < updateOrder_.size(); i++) { + updateMessage (updateOrder_[i]); + updateValues (updateOrder_[i]); + } + break; + + case S_MAX_RESIDUAL: + maxResidualSchedule(); + break; + + } + } +} + + + +void +BPSolver::maxResidualSchedule (void) +{ + if (nIter_ == 1) { + Edge::klass = this; + for (unsigned i = 0; i < updateOrder_.size(); i++) { + calculateNextMessage (updateOrder_[i]); + updateResidual (updateOrder_[i]); + SortedOrder::iterator it = sortedOrder_.insert (updateOrder_[i]); + edgeMap_.insert (make_pair (updateOrder_[i].getId(), it)); + } + return; + } + + for (unsigned c = 0; c < sortedOrder_.size(); c++) { + if (DL >= 1) { + for (set::iterator it = sortedOrder_.begin(); + it != sortedOrder_.end(); it ++) { + cout << it->toString() << " residual = " ; + cout << getResidual (*it) << endl; + } + } + + set::iterator it = sortedOrder_.begin(); + Edge e = *it; + if (getResidual (e) < accuracy_) { + return; + } + updateMessage (e); + updateValues (e); + clearResidual (e); + sortedOrder_.erase (it); + assert (edgeMap_.find (e.getId()) != edgeMap_.end()); + edgeMap_.find (e.getId())->second = sortedOrder_.insert (e); + + // update the messages that depend on message source --> destination + const NodeSet& childs = e.destination->getChilds(); + for (unsigned i = 0; i < childs.size(); i++) { + if (childs[i] != e.source) { + Edge neighbor (e.destination, childs[i], PI_MSG); + calculateNextMessage (neighbor); + updateResidual (neighbor); + assert (edgeMap_.find (neighbor.getId()) != edgeMap_.end()); + EdgeMap::iterator iter = edgeMap_.find (neighbor.getId()); + sortedOrder_.erase (iter->second); + iter->second = sortedOrder_.insert (neighbor); + } + } + const NodeSet& parents = e.destination->getParents(); + for (unsigned i = 0; i < parents.size(); i++) { + if (parents[i] != e.source && !parents[i]->hasEvidence()) { + Edge neighbor (e.destination, parents[i], LAMBDA_MSG); + calculateNextMessage (neighbor); + updateResidual (neighbor); + assert (edgeMap_.find (neighbor.getId()) != edgeMap_.end()); + EdgeMap::iterator iter = edgeMap_.find (neighbor.getId()); + sortedOrder_.erase (iter->second); + iter->second = sortedOrder_.insert (neighbor); + } + } + } +} + + + +bool +BPSolver::converged (void) const +{ + bool converged = true; + if (schedule_ == S_MAX_RESIDUAL) { + if (nIter_ <= 2) { + return false; + } + // this can happen if every node does not have neighbors + if (sortedOrder_.size() == 0) { + return true; + } + Param maxResidual = getResidual (*(sortedOrder_.begin())); + if (maxResidual > accuracy_) { + return false; + } + } else { + if (nIter_ == 0) { + return false; + } + const NodeSet& nodes = bn_->getNodes(); + for (unsigned i = 0; i < nodes.size(); i++) { + if (!nodes[i]->hasEvidence()) { + double change = M(nodes[i])->getBeliefChange(); + if (DL >= 1) { + cout << nodes[i]->getLabel() + " belief change = " ; + cout << change << endl; + } + if (change > accuracy_) { + converged = false; + if (DL == 0) break; + } + } + } + } + + return converged; +} + + + +void +BPSolver::updatePiValues (BayesNode* x) +{ + // π(Xi) + const NodeSet& parents = x->getParents(); + const vector& entries = x->getCptEntries(); + assert (parents.size() != 0); + stringstream* calcs1; + stringstream* calcs2; + + ParamSet messageProducts (entries.size()); + for (unsigned k = 0; k < entries.size(); k++) { + if (DL >= 5) { + calcs1 = new stringstream; + calcs2 = new stringstream; + } + double messageProduct = 1.0; + const DomainConf& conf = entries[k].getParentConfigurations(); + for (unsigned i = 0; i < parents.size(); i++) { + messageProduct *= M(parents[i])->getPiMessageValue(x, conf[i]); + if (DL >= 5) { + if (i != 0) *calcs1 << "." ; + if (i != 0) *calcs2 << "*" ; + *calcs1 << PI << "(" << x->getLabel() << ")" ; + *calcs1 << "[" << parents[i]->getDomain()[conf[i]] << "]"; + *calcs2 << M(parents[i])->getPiMessageValue(x, conf[i]); + } + } + messageProducts[k] = messageProduct; + if (DL >= 5) { + cout << " mp" << k; + cout << " = " << (*calcs1).str(); + if (parents.size() == 1) { + cout << " = " << messageProduct << endl; + } else { + cout << " = " << (*calcs2).str(); + cout << " = " << messageProduct << endl; + } + delete calcs1; + delete calcs2; + } + } + + for (int xi = 0; xi < x->getDomainSize(); xi++) { + double sum = 0.0; + if (DL >= 5) { + calcs1 = new stringstream; + calcs2 = new stringstream; + } + for (unsigned k = 0; k < entries.size(); k++) { + sum += x->getProbability (xi, entries[k]) * messageProducts[k]; + if (DL >= 5) { + if (k != 0) *calcs1 << " + " ; + if (k != 0) *calcs2 << " + " ; + *calcs1 << x->cptEntryToString (xi, entries[k]); + *calcs1 << ".mp" << k; + *calcs2 << x->getProbability (xi, entries[k]); + *calcs2 << "*" << messageProducts[k]; + } + } + M(x)->setPiValue (xi, sum); + if (DL >= 5) { + cout << " " << PI << "(" << x->getLabel() << ")" ; + cout << "[" << x->getDomain()[xi] << "]" ; + cout << " = " << (*calcs1).str(); + cout << " = " << (*calcs2).str(); + cout << " = " << sum << endl; + delete calcs1; + delete calcs2; + } + } +} + + + +void +BPSolver::updateLambdaValues (BayesNode* x) +{ + // λ(Xi) + const NodeSet& childs = x->getChilds(); + assert (childs.size() != 0); + stringstream* calcs1; + stringstream* calcs2; + + for (int xi = 0; xi < x->getDomainSize(); xi++) { + double product = 1.0; + if (DL >= 5) { + calcs1 = new stringstream; + calcs2 = new stringstream; + } + for (unsigned i = 0; i < childs.size(); i++) { + product *= M(x)->getLambdaMessageValue(childs[i], xi); + if (DL >= 5) { + if (i != 0) *calcs1 << "." ; + if (i != 0) *calcs2 << "*" ; + *calcs1 << LD << "(" << childs[i]->getLabel(); + *calcs1 << "-->" << x->getLabel() << ")" ; + *calcs1 << "[" << x->getDomain()[xi] << "]" ; + *calcs2 << M(x)->getLambdaMessageValue(childs[i], xi); + } + } + M(x)->setLambdaValue (xi, product); + if (DL >= 5) { + cout << " " << LD << "(" << x->getLabel() << ")" ; + cout << "[" << x->getDomain()[xi] << "]" ; + cout << " = " << (*calcs1).str(); + if (childs.size() == 1) { + cout << " = " << product << endl; + } else { + cout << " = " << (*calcs2).str(); + cout << " = " << product << endl; + } + delete calcs1; + delete calcs2; + } + } +} + + + +void +BPSolver::calculateNextPiMessage (BayesNode* z, BayesNode* x) +{ + // πX(Zi) + ParamSet& zxPiNextMessage = M(z)->piNextMessageReference (x); + const NodeSet& zChilds = z->getChilds(); + stringstream* calcs1; + stringstream* calcs2; + + for (int zi = 0; zi < z->getDomainSize(); zi++) { + double product = M(z)->getPiValue (zi); + if (DL >= 5) { + calcs1 = new stringstream; + calcs2 = new stringstream; + *calcs1 << PI << "(" << z->getLabel() << ")"; + *calcs1 << "[" << z->getDomain()[zi] << "]" ; + *calcs2 << product; + } + for (unsigned i = 0; i < zChilds.size(); i++) { + if (zChilds[i] != x) { + product *= M(z)->getLambdaMessageValue(zChilds[i], zi); + if (DL >= 5) { + *calcs1 << "." << LD << "(" << zChilds[i]->getLabel(); + *calcs1 << "-->" << z->getLabel() << ")"; + *calcs1 << "[" << z->getDomain()[zi] + "]" ; + *calcs2 << " * " << M(z)->getLambdaMessageValue(zChilds[i], zi); + } + } + } + zxPiNextMessage[zi] = product; + if (DL >= 5) { + cout << " " << PI << "(" << z->getLabel(); + cout << "-->" << x->getLabel() << ")" ; + cout << "[" << z->getDomain()[zi] << "]" ; + cout << " = " << (*calcs1).str(); + if (zChilds.size() == 1) { + cout << " = " << product << endl; + } else { + cout << " = " << (*calcs2).str(); + cout << " = " << product << endl; + } + delete calcs1; + delete calcs2; + } + } +} + + + +void +BPSolver::calculateNextLambdaMessage (BayesNode* y, BayesNode* x) +{ + // λY(Xi) + //if (!y->hasEvidence() && !M(y)->hasReceivedChildInfluence()) { + // if (DL >= 5) { + // cout << "unnecessary calculation" << endl; + // } + // return; + //} + ParamSet& yxLambdaNextMessage = M(x)->lambdaNextMessageReference (y); + const NodeSet& yParents = y->getParents(); + const vector& allEntries = y->getCptEntries(); + int parentIndex = y->getIndexOfParent (x); + stringstream* calcs1; + stringstream* calcs2; + + vector entries; + DomainConstr constr = make_pair (parentIndex, 0); + for (unsigned i = 0; i < allEntries.size(); i++) { + if (allEntries[i].matchConstraints(constr)) { + entries.push_back (allEntries[i]); + } + } + + ParamSet messageProducts (entries.size()); + for (unsigned k = 0; k < entries.size(); k++) { + if (DL >= 5) { + calcs1 = new stringstream; + calcs2 = new stringstream; + } + double messageProduct = 1.0; + const DomainConf& conf = entries[k].getParentConfigurations(); + for (unsigned i = 0; i < yParents.size(); i++) { + if (yParents[i] != x) { + if (DL >= 5) { + if (messageProduct != 1.0) *calcs1 << "*" ; + if (messageProduct != 1.0) *calcs2 << "*" ; + *calcs1 << PI << "(" << yParents[i]->getLabel(); + *calcs1 << "-->" << y->getLabel() << ")" ; + *calcs1 << "[" << yParents[i]->getDomain()[conf[i]] << "]" ; + *calcs2 << M(yParents[i])->getPiMessageValue(y, conf[i]); + } + messageProduct *= M(yParents[i])->getPiMessageValue(y, conf[i]); + } + } + messageProducts[k] = messageProduct; + if (DL >= 5) { + cout << " mp" << k; + cout << " = " << (*calcs1).str(); + if (yParents.size() == 1) { + cout << 1 << endl; + } else if (yParents.size() == 2) { + cout << " = " << messageProduct << endl; + } else { + cout << " = " << (*calcs2).str(); + cout << " = " << messageProduct << endl; + } + delete calcs1; + delete calcs2; + } + } + + for (int xi = 0; xi < x->getDomainSize(); xi++) { + if (DL >= 5) { + calcs1 = new stringstream; + calcs2 = new stringstream; + } + vector entries; + DomainConstr constr = make_pair (parentIndex, xi); + for (unsigned i = 0; i < allEntries.size(); i++) { + if (allEntries[i].matchConstraints(constr)) { + entries.push_back (allEntries[i]); + } + } + double outerSum = 0.0; + for (int yi = 0; yi < y->getDomainSize(); yi++) { + if (DL >= 5) { + (yi != 0) ? *calcs1 << " + {" : *calcs1 << "{" ; + (yi != 0) ? *calcs2 << " + {" : *calcs2 << "{" ; + } + double innerSum = 0.0; + for (unsigned k = 0; k < entries.size(); k++) { + if (DL >= 5) { + if (k != 0) *calcs1 << " + " ; + if (k != 0) *calcs2 << " + " ; + *calcs1 << y->cptEntryToString (yi, entries[k]); + *calcs1 << ".mp" << k; + *calcs2 << y->getProbability (yi, entries[k]); + *calcs2 << "*" << messageProducts[k]; + } + innerSum += y->getProbability (yi, entries[k]) * messageProducts[k]; + } + outerSum += innerSum * M(y)->getLambdaValue (yi); + if (DL >= 5) { + *calcs1 << "}." << LD << "(" << y->getLabel() << ")" ; + *calcs1 << "[" << y->getDomain()[yi] << "]"; + *calcs2 << "}*" << M(y)->getLambdaValue (yi); + } + } + yxLambdaNextMessage[xi] = outerSum; + if (DL >= 5) { + cout << " " << LD << "(" << y->getLabel(); + cout << "-->" << x->getLabel() << ")" ; + cout << "[" << x->getDomain()[xi] << "]" ; + cout << " = " << (*calcs1).str(); + cout << " = " << (*calcs2).str(); + cout << " = " << outerSum << endl; + delete calcs1; + delete calcs2; + } + } +} + + + +void +BPSolver::printMessageStatusOf (const BayesNode* var) const +{ + cout << left; + cout << setw (10) << "domain" ; + cout << setw (20) << PI << "(" + var->getLabel() + ")" ; + cout << setw (20) << LD << "(" + var->getLabel() + ")" ; + cout << setw (16) << "belief" ; + cout << endl; + cout << "--------------------------------" ; + cout << "--------------------------------" ; + cout << endl; + + BpNode* x = M(var); + ParamSet& piVals = x->getPiValues(); + ParamSet& ldVals = x->getLambdaValues(); + ParamSet beliefs = x->getBeliefs(); + const Domain& domain = var->getDomain(); + const NodeSet& childs = var->getChilds(); + + for (int xi = 0; xi < var->getDomainSize(); xi++) { + cout << setw (10) << domain[xi]; + cout << setw (19) << piVals[xi]; + cout << setw (19) << ldVals[xi]; + cout.precision (PRECISION); + cout << setw (16) << beliefs[xi]; + cout << endl; + } + cout << endl; + if (childs.size() > 0) { + string s = "(" + var->getLabel() + ")" ; + for (unsigned j = 0; j < childs.size(); j++) { + cout << setw (10) << "domain" ; + cout << setw (28) << PI + childs[j]->getLabel() + s; + cout << setw (28) << LD + childs[j]->getLabel() + s; + cout << endl; + cout << "--------------------------------" ; + cout << "--------------------------------" ; + cout << endl; + const ParamSet& piMessage = x->getPiMessage (childs[j]); + const ParamSet& lambdaMessage = x->getLambdaMessage (childs[j]); + for (int xi = 0; xi < var->getDomainSize(); xi++) { + cout << setw (10) << domain[xi]; + cout.precision (PRECISION); + cout << setw (27) << piMessage[xi]; + cout.precision (PRECISION); + cout << setw (27) << lambdaMessage[xi]; + cout << endl; + } + cout << endl; + } + } +} + + + +void +BPSolver::printAllMessageStatus (void) const +{ + const NodeSet& nodes = bn_->getNodes(); + for (unsigned i = 0; i < nodes.size(); i++) { + printMessageStatusOf (nodes[i]); + } +} + + diff --git a/packages/CLPBN/clpbn/bp/BPSolver.h b/packages/CLPBN/clpbn/bp/BPSolver.h new file mode 100755 index 000000000..b752b92d2 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/BPSolver.h @@ -0,0 +1,450 @@ +#ifndef BP_BPSOLVER_H +#define BP_BPSOLVER_H + +#include +#include +#include + +#include "Solver.h" +#include "BayesNet.h" +#include "BpNode.h" +#include "Shared.h" + +using namespace std; + +class BPSolver; + +static const string PI = "pi" ; +static const string LD = "ld" ; + +enum MessageType {PI_MSG, LAMBDA_MSG}; + +class BPSolver; +struct Edge +{ + Edge (BayesNode* s, BayesNode* d, MessageType t) + { + source = s; + destination = d; + type = t; + } + string getId (void) const + { + stringstream ss; + type == PI_MSG ? ss << PI : ss << LD; + ss << source->getVarId() << "." << destination->getVarId(); + return ss.str(); + } + string toString (void) const + { + stringstream ss; + type == PI_MSG ? ss << PI << "(" : ss << LD << "(" ; + ss << source->getLabel() << " --> " ; + ss << destination->getLabel(); + ss << ")" ; + return ss.str(); + } + BayesNode* source; + BayesNode* destination; + MessageType type; + static BPSolver* klass; +}; + + + +/* +class BPMessage +{ + BPMessage (BayesNode* parent, BayesNode* child) + { + parent_ = parent; + child_ = child; + currPiMsg_.resize (child->getDomainSize(), 1); + currLdMsg_.resize (parent->getDomainSize(), 1); + nextLdMsg_.resize (parent->getDomainSize(), 1); + nextPiMsg_.resize (child->getDomainSize(), 1); + piResidual_ = 1.0; + ldResidual_ = 1.0; + } + + Param getPiMessageValue (int idx) const + { + assert (idx >=0 && idx < child->getDomainSize()); + return currPiMsg_[idx]; + } + + Param getLambdaMessageValue (int idx) const + { + assert (idx >=0 && idx < parent->getDomainSize()); + return currLdMsg_[idx]; + } + + const ParamSet& getPiMessage (void) const + { + return currPiMsg_; + } + + const ParamSet& getLambdaMessage (void) const + { + return currLdMsg_; + } + + ParamSet& piNextMessageReference (void) + { + return nextPiMsg_; + } + + ParamSet& lambdaNextMessageReference (const BayesNode* source) + { + return nextLdMsg_; + } + + void updatePiMessage (void) + { + currPiMsg_ = nextPiMsg_; + Util::normalize (currPiMsg_); + } + + void updateLambdaMessage (void) + { + currLdMsg_ = nextLdMsg_; + Util::normalize (currLdMsg_); + } + + double getPiResidual (void) + { + return piResidual_; + } + + double getLambdaResidual (void) + { + return ldResidual_; + } + + void updatePiResidual (void) + { + piResidual_ = Util::getL1dist (currPiMsg_, nextPiMsg_); + } + + void updateLambdaResidual (void) + { + ldResidual_ = Util::getL1dist (currLdMsg_, nextLdMsg_); + } + + void clearPiResidual (void) + { + piResidual_ = 0.0; + } + + void clearLambdaResidual (void) + { + ldResidual_ = 0.0; + } + + BayesNode* parent_; + BayesNode* child_; + ParamSet currPiMsg_; // current pi messages + ParamSet currLdMsg_; // current lambda messages + ParamSet nextPiMsg_; + ParamSet nextLdMsg_; + Param piResidual_; + Param ldResidual_; +}; + + + +class NodeInfo +{ + NodeInfo (BayesNode* node) + { + node_ = node; + piVals_.resize (node->getDomainSize(), 1); + ldVals_.resize (node->getDomainSize(), 1); + } + + ParamSet getBeliefs (void) const + { + double sum = 0.0; + ParamSet beliefs (node_->getDomainSize()); + for (int xi = 0; xi < node_->getDomainSize(); xi++) { + double prod = piVals_[xi] * ldVals_[xi]; + beliefs[xi] = prod; + sum += prod; + } + assert (sum); + //normalize the beliefs + for (int xi = 0; xi < node_->getDomainSize(); xi++) { + beliefs[xi] /= sum; + } + return beliefs; + } + + double getPiValue (int idx) const + { + assert (idx >=0 && idx < node_->getDomainSize()); + return piVals_[idx]; + } + + void setPiValue (int idx, double value) + { + assert (idx >=0 && idx < node_->getDomainSize()); + piVals_[idx] = value; + } + + double getLambdaValue (int idx) const + { + assert (idx >=0 && idx < node_->getDomainSize()); + return ldVals_[idx]; + } + + void setLambdaValue (int idx, double value) + { + assert (idx >=0 && idx < node_->getDomainSize()); + ldVals_[idx] = value; + } + + ParamSet& getPiValues (void) + { + return piVals_; + } + + ParamSet& getLambdaValues (void) + { + return ldVals_; + } + + double getBeliefChange (void) + { + double change = 0.0; + if (oldBeliefs_.size() == 0) { + oldBeliefs_ = getBeliefs(); + change = MAX_CHANGE_; + } else { + ParamSet currentBeliefs = getBeliefs(); + for (int xi = 0; xi < node_->getDomainSize(); xi++) { + change += abs (currentBeliefs[xi] - oldBeliefs_[xi]); + } + oldBeliefs_ = currentBeliefs; + } + return change; + } + + bool hasReceivedChildInfluence (void) const + { + // if all lambda values are equal, then neither + // this node neither its descendents have evidence, + // we can use this to don't send lambda messages his parents + bool childInfluenced = false; + for (int xi = 1; xi < node_->getDomainSize(); xi++) { + if (ldVals_[xi] != ldVals_[0]) { + childInfluenced = true; + break; + } + } + return childInfluenced; + } + + BayesNode* node_; + ParamSet piVals_; // pi values + ParamSet ldVals_; // lambda values + ParamSet oldBeliefs_; +}; +*/ + + +bool compareResidual (const Edge&, const Edge&); + +class BPSolver : public Solver +{ + public: + BPSolver (const BayesNet&); + ~BPSolver (void); + + void runSolver (void); + ParamSet getPosterioriOf (const Variable* var) const; + ParamSet getJointDistribution (const NodeSet&) const; + + private: + DISALLOW_COPY_AND_ASSIGN (BPSolver); + + void initializeSolver (void); + void incorporateEvidence (BayesNode*); + void runPolyTreeSolver (void); + void polyTreePiMessage (BayesNode*, BayesNode*); + void polyTreeLambdaMessage (BayesNode*, BayesNode*); + void runGenericSolver (void); + void maxResidualSchedule (void); + bool converged (void) const; + void updatePiValues (BayesNode*); + void updateLambdaValues (BayesNode*); + void calculateNextPiMessage (BayesNode*, BayesNode*); + void calculateNextLambdaMessage (BayesNode*, BayesNode*); + void printMessageStatusOf (const BayesNode*) const; + void printAllMessageStatus (void) const; + // inlines + void updatePiMessage (BayesNode*, BayesNode*); + void updateLambdaMessage (BayesNode*, BayesNode*); + void calculateNextMessage (const Edge&); + void updateMessage (const Edge&); + void updateValues (const Edge&); + double getResidual (const Edge&) const; + void updateResidual (const Edge&); + void clearResidual (const Edge&); + BpNode* M (const BayesNode*) const; + friend bool compareResidual (const Edge&, const Edge&); + + const BayesNet* bn_; + vector msgs_; + Schedule schedule_; + int nIter_; + int maxIter_; + double accuracy_; + vector updateOrder_; + bool forceGenericSolver_; + + struct compare + { + inline bool operator() (const Edge& e1, const Edge& e2) + { + return compareResidual (e1, e2); + } + }; + + typedef multiset SortedOrder; + SortedOrder sortedOrder_; + + typedef unordered_map EdgeMap; + EdgeMap edgeMap_; + +}; + + + +inline void +BPSolver::updatePiMessage (BayesNode* source, BayesNode* destination) +{ + M(source)->updatePiMessage(destination); +} + + + +inline void +BPSolver::updateLambdaMessage (BayesNode* source, BayesNode* destination) +{ + M(destination)->updateLambdaMessage(source); +} + + + +inline void +BPSolver::calculateNextMessage (const Edge& e) +{ + if (DL >= 1) { + cout << "calculating " << e.toString() << endl; + } + if (e.type == PI_MSG) { + calculateNextPiMessage (e.source, e.destination); + } else { + calculateNextLambdaMessage (e.source, e.destination); + } +} + + + +inline void +BPSolver::updateMessage (const Edge& e) +{ + if (DL >= 1) { + cout << "updating " << e.toString() << endl; + } + if (e.type == PI_MSG) { + M(e.source)->updatePiMessage(e.destination); + } else { + M(e.destination)->updateLambdaMessage(e.source); + } +} + + + +inline void +BPSolver::updateValues (const Edge& e) +{ + if (!e.destination->hasEvidence()) { + if (e.type == PI_MSG) { + updatePiValues (e.destination); + } else { + updateLambdaValues (e.destination); + } + } +} + + + +inline double +BPSolver::getResidual (const Edge& e) const +{ + if (e.type == PI_MSG) { + return M(e.source)->getPiResidual(e.destination); + } else { + return M(e.destination)->getLambdaResidual(e.source); + } +} + + + +inline void +BPSolver::updateResidual (const Edge& e) +{ + if (e.type == PI_MSG) { + M(e.source)->updatePiResidual(e.destination); + } else { + M(e.destination)->updateLambdaResidual(e.source); + } +} + + + +inline void +BPSolver::clearResidual (const Edge& e) +{ + if (e.type == PI_MSG) { + M(e.source)->clearPiResidual(e.destination); + } else { + M(e.destination)->clearLambdaResidual(e.source); + } +} + + + +inline bool +compareResidual (const Edge& e1, const Edge& e2) +{ + double residual1; + double residual2; + if (e1.type == PI_MSG) { + residual1 = Edge::klass->M(e1.source)->getPiResidual(e1.destination); + } else { + residual1 = Edge::klass->M(e1.destination)->getLambdaResidual(e1.source); + } + if (e2.type == PI_MSG) { + residual2 = Edge::klass->M(e2.source)->getPiResidual(e2.destination); + } else { + residual2 = Edge::klass->M(e2.destination)->getLambdaResidual(e2.source); + } + return residual1 > residual2; +} + + + +inline BpNode* +BPSolver::M (const BayesNode* node) const +{ + assert (node); + assert (node == bn_->getNode (node->getVarId())); + assert (node->getIndex() < msgs_.size()); + return msgs_[node->getIndex()]; +} + + +#endif + diff --git a/packages/CLPBN/clpbn/bp/BayesNet.cpp b/packages/CLPBN/clpbn/bp/BayesNet.cpp new file mode 100755 index 000000000..291c0c8d3 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/BayesNet.cpp @@ -0,0 +1,792 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "xmlParser/xmlParser.h" + +#include "BayesNet.h" + + +BayesNet::BayesNet (void) +{ +} + + + +BayesNet::BayesNet (const char* fileName) +{ + map domains; + XMLNode xMainNode = XMLNode::openFileHelper (fileName, "BIF"); + // only the first network is parsed, others are ignored + XMLNode xNode = xMainNode.getChildNode ("NETWORK"); + int nVars = xNode.nChildNode ("VARIABLE"); + for (int i = 0; i < nVars; i++) { + XMLNode var = xNode.getChildNode ("VARIABLE", i); + string type = var.getAttribute ("TYPE"); + if (type != "nature") { + cerr << "error: only \"nature\" variables are supported" << endl; + abort(); + } + Domain domain; + string label = var.getChildNode("NAME").getText(); + int domainSize = var.nChildNode ("OUTCOME"); + for (int j = 0; j < domainSize; j++) { + if (var.getChildNode("OUTCOME", j).getText() == 0) { + stringstream ss; + ss << j + 1; + domain.push_back (ss.str()); + } else { + domain.push_back (var.getChildNode("OUTCOME", j).getText()); + } + } + domains.insert (make_pair (label, domain)); + } + + int nDefs = xNode.nChildNode ("DEFINITION"); + if (nVars != nDefs) { + cerr << "error: different number of variables and definitions"; + cerr << endl; + } + + queue indexes; + for (int i = 0; i < nDefs; i++) { + indexes.push (i); + } + + while (!indexes.empty()) { + int index = indexes.front(); + indexes.pop(); + XMLNode def = xNode.getChildNode ("DEFINITION", index); + string label = def.getChildNode("FOR").getText(); + map::const_iterator iter; + iter = domains.find (label); + if (iter == domains.end()) { + cerr << "error: unknow variable `" << label << "'" << endl; + abort(); + } + bool processItLatter = false; + NodeSet parents; + int nParams = iter->second.size(); + for (int j = 0; j < def.nChildNode ("GIVEN"); j++) { + string parentLabel = def.getChildNode("GIVEN", j).getText(); + BayesNode* parentNode = getNode (parentLabel); + if (parentNode) { + nParams *= parentNode->getDomainSize(); + parents.push_back (parentNode); + } + else { + iter = domains.find (parentLabel); + if (iter == domains.end()) { + cerr << "error: unknow parent `" << parentLabel << "'" << endl; + abort(); + } else { + // this definition contains a parent that doesn't + // have a corresponding bayesian node instance yet, + // so process this definition latter + indexes.push (index); + processItLatter = true; + break; + } + } + } + + if (!processItLatter) { + int count = 0; + ParamSet params (nParams); + stringstream s (def.getChildNode("TABLE").getText()); + while (!s.eof() && count < nParams) { + s >> params[count]; + count ++; + } + if (count != nParams) { + cerr << "error: invalid number of parameters " ; + cerr << "for variable `" << label << "'" << endl; + abort(); + } + params = reorderParameters (params, iter->second.size()); + addNode (label, iter->second, parents, params); + } + } + setIndexes(); +} + + + +BayesNet::~BayesNet (void) +{ + Statistics::writeStats(); + for (unsigned i = 0; i < nodes_.size(); i++) { + delete nodes_[i]; + } +} + + + +BayesNode* +BayesNet::addNode (unsigned varId) +{ + indexMap_.insert (make_pair (varId, nodes_.size())); + nodes_.push_back (new BayesNode (varId)); + return nodes_.back(); +} + + + +BayesNode* +BayesNet::addNode (unsigned varId, + unsigned dsize, + int evidence, + NodeSet& parents, + Distribution* dist) +{ + indexMap_.insert (make_pair (varId, nodes_.size())); + nodes_.push_back (new BayesNode ( + varId, dsize, evidence, parents, dist)); + return nodes_.back(); +} + + + +BayesNode* +BayesNet::addNode (string label, + Domain domain, + NodeSet& parents, + ParamSet& params) +{ + indexMap_.insert (make_pair (nodes_.size(), nodes_.size())); + Distribution* dist = new Distribution (params); + BayesNode* node = new BayesNode ( + nodes_.size(), label, domain, parents, dist); + dists_.push_back (dist); + nodes_.push_back (node); + return node; +} + + + +BayesNode* +BayesNet::getNode (unsigned varId) const +{ + IndexMap::const_iterator it = indexMap_.find(varId); + if (it == indexMap_.end()) { + return 0; + } else { + return nodes_[it->second]; + } +} + + + +BayesNode* +BayesNet::getNode (string label) const +{ + BayesNode* node = 0; + for (unsigned i = 0; i < nodes_.size(); i++) { + if (nodes_[i]->getLabel() == label) { + node = nodes_[i]; + break; + } + } + return node; +} + + + +void +BayesNet::addDistribution (Distribution* dist) +{ + dists_.push_back (dist); +} + + + +Distribution* +BayesNet::getDistribution (unsigned distId) const +{ + Distribution* dist = 0; + for (unsigned i = 0; i < dists_.size(); i++) { + if (dists_[i]->id == distId) { + dist = dists_[i]; + break; + } + } + return dist; +} + + + +const NodeSet& +BayesNet::getNodes (void) const +{ + return nodes_; +} + + + +int +BayesNet::getNumberOfNodes (void) const +{ + return nodes_.size(); +} + + + +NodeSet +BayesNet::getRootNodes (void) const +{ + NodeSet roots; + for (unsigned i = 0; i < nodes_.size(); i++) { + if (nodes_[i]->isRoot()) { + roots.push_back (nodes_[i]); + } + } + return roots; +} + + + +NodeSet +BayesNet::getLeafNodes (void) const +{ + NodeSet leafs; + for (unsigned i = 0; i < nodes_.size(); i++) { + if (nodes_[i]->isLeaf()) { + leafs.push_back (nodes_[i]); + } + } + return leafs; +} + + + +VarSet +BayesNet::getVariables (void) const +{ + VarSet vars; + for (unsigned i = 0; i < nodes_.size(); i++) { + vars.push_back (nodes_[i]); + } + return vars; +} + + + +BayesNet* +BayesNet::pruneNetwork (BayesNode* queryNode) const +{ + NodeSet queryNodes; + queryNodes.push_back (queryNode); + return pruneNetwork (queryNodes); +} + + + +BayesNet* +BayesNet::pruneNetwork (const NodeSet& interestedVars) const +{ + /* + cout << "interested vars: " ; + for (unsigned i = 0; i < interestedVars.size(); i++) { + cout << interestedVars[i]->getLabel() << " " ; + } + cout << endl; + */ + vector states (nodes_.size(), 0); + + Scheduling scheduling; + for (NodeSet::const_iterator it = interestedVars.begin(); + it != interestedVars.end(); it++) { + scheduling.push (ScheduleInfo (*it, false, true)); + } + + while (!scheduling.empty()) { + ScheduleInfo& sch = scheduling.front(); + StateInfo* state = states[sch.node->getIndex()]; + if (!state) { + state = new StateInfo(); + states[sch.node->getIndex()] = state; + } else { + state->visited = true; + } + if (!sch.node->hasEvidence() && sch.visitedFromChild) { + if (!state->markedOnTop) { + state->markedOnTop = true; + scheduleParents (sch.node, scheduling); + } + if (!state->markedOnBottom) { + state->markedOnBottom = true; + scheduleChilds (sch.node, scheduling); + } + } + if (sch.visitedFromParent) { + if (sch.node->hasEvidence() && !state->markedOnTop) { + state->markedOnTop = true; + scheduleParents (sch.node, scheduling); + } + if (!sch.node->hasEvidence() && !state->markedOnBottom) { + state->markedOnBottom = true; + scheduleChilds (sch.node, scheduling); + } + } + scheduling.pop(); + } + /* + cout << "\t\ttop\tbottom" << endl; + cout << "variable\t\tmarked\tmarked\tvisited\tobserved" << endl; + cout << "----------------------------------------------------------" ; + cout << endl; + for (unsigned i = 0; i < states.size(); i++) { + cout << nodes_[i]->getLabel() << ":\t\t" ; + if (states[i]) { + states[i]->markedOnTop ? cout << "yes\t" : cout << "no\t" ; + states[i]->markedOnBottom ? cout << "yes\t" : cout << "no\t" ; + states[i]->visited ? cout << "yes\t" : cout << "no\t" ; + nodes_[i]->hasEvidence() ? cout << "yes" : cout << "no" ; + cout << endl; + } else { + cout << "no\tno\tno\t" ; + nodes_[i]->hasEvidence() ? cout << "yes" : cout << "no" ; + cout << endl; + } + } + cout << endl; + */ + BayesNet* bn = new BayesNet(); + constructGraph (bn, states); + + for (unsigned i = 0; i < nodes_.size(); i++) { + delete states[i]; + } + return bn; +} + + + +void +BayesNet::constructGraph (BayesNet* bn, + const vector& states) const +{ + for (unsigned i = 0; i < nodes_.size(); i++) { + bool isRequired = false; + if (states[i]) { + isRequired = (nodes_[i]->hasEvidence() && states[i]->visited) + || + states[i]->markedOnTop; + } + if (isRequired) { + NodeSet parents; + if (states[i]->markedOnTop) { + const NodeSet& ps = nodes_[i]->getParents(); + for (unsigned j = 0; j < ps.size(); j++) { + BayesNode* parent = bn->getNode (ps[j]->getVarId()); + if (!parent) { + parent = bn->addNode (ps[j]->getVarId()); + } + parents.push_back (parent); + } + } + BayesNode* node = bn->getNode (nodes_[i]->getVarId()); + if (node) { + node->setData (nodes_[i]->getDomainSize(), + nodes_[i]->getEvidence(), parents, + nodes_[i]->getDistribution()); + } else { + node = bn->addNode (nodes_[i]->getVarId(), + nodes_[i]->getDomainSize(), + nodes_[i]->getEvidence(), parents, + nodes_[i]->getDistribution()); + } + if (nodes_[i]->hasDomain()) { + node->setDomain (nodes_[i]->getDomain()); + } + if (nodes_[i]->hasLabel()) { + node->setLabel (nodes_[i]->getLabel()); + } + } + } + bn->setIndexes(); +} + +/* +void +BayesNet::constructGraph (BayesNet* bn, + const vector& states) const +{ + for (unsigned i = 0; i < nodes_.size(); i++) { + if (states[i]) { + if (nodes_[i]->hasEvidence() && states[i]->visited) { + NodeSet parents; + if (states[i]->markedOnTop) { + const NodeSet& ps = nodes_[i]->getParents(); + for (unsigned j = 0; j < ps.size(); j++) { + BayesNode* parent = bn->getNode (ps[j]->getVarId()); + if (parent == 0) { + parent = bn->addNode (ps[j]->getVarId()); + } + parents.push_back (parent); + } + } + + BayesNode* n = bn->getNode (nodes_[i]->getVarId()); + if (n) { + n->setData (nodes_[i]->getDomainSize(), + nodes_[i]->getEvidence(), parents, + nodes_[i]->getDistribution()); + } else { + bn->addNode (nodes_[i]->getVarId(), + nodes_[i]->getDomainSize(), + nodes_[i]->getEvidence(), parents, + nodes_[i]->getDistribution()); + } + + } else if (states[i]->markedOnTop) { + NodeSet parents; + const NodeSet& ps = nodes_[i]->getParents(); + for (unsigned j = 0; j < ps.size(); j++) { + BayesNode* parent = bn->getNode (ps[j]->getVarId()); + if (parent == 0) { + parent = bn->addNode (ps[j]->getVarId()); + } + parents.push_back (parent); + } + + BayesNode* n = bn->getNode (nodes_[i]->getVarId()); + if (n) { + n->setData (nodes_[i]->getDomainSize(), + nodes_[i]->getEvidence(), parents, + nodes_[i]->getDistribution()); + } else { + bn->addNode (nodes_[i]->getVarId(), + nodes_[i]->getDomainSize(), + nodes_[i]->getEvidence(), parents, + nodes_[i]->getDistribution()); + } + } + } + } +}*/ + + + +bool +BayesNet::isSingleConnected (void) const +{ + return !containsUndirectedCycle(); +} + + + +vector +BayesNet::getDomainConfigurationsOf (const NodeSet& nodes) +{ + int nConfs = 1; + for (unsigned i = 0; i < nodes.size(); i++) { + nConfs *= nodes[i]->getDomainSize(); + } + + vector confs (nConfs); + for (int i = 0; i < nConfs; i++) { + confs[i].resize (nodes.size()); + } + + int nReps = 1; + for (int i = nodes.size() - 1; i >= 0; i--) { + int index = 0; + while (index < nConfs) { + for (int j = 0; j < nodes[i]->getDomainSize(); j++) { + for (int r = 0; r < nReps; r++) { + confs[index][i] = j; + index++; + } + } + } + nReps *= nodes[i]->getDomainSize(); + } + + return confs; +} + + + +vector +BayesNet::getInstantiations (const NodeSet& parents_) +{ + int nParents = parents_.size(); + int rowSize = 1; + for (unsigned i = 0; i < parents_.size(); i++) { + rowSize *= parents_[i]->getDomainSize(); + } + int nReps = 1; + vector headers (rowSize); + for (int i = nParents - 1; i >= 0; i--) { + Domain domain = parents_[i]->getDomain(); + int index = 0; + while (index < rowSize) { + for (int j = 0; j < parents_[i]->getDomainSize(); j++) { + for (int r = 0; r < nReps; r++) { + if (headers[index] != "") { + headers[index] = domain[j] + "," + headers[index]; + } else { + headers[index] = domain[j]; + } + index++; + } + } + } + nReps *= parents_[i]->getDomainSize(); + } + return headers; +} + + + +void +BayesNet::setIndexes (void) +{ + for (unsigned i = 0; i < nodes_.size(); i++) { + nodes_[i]->setIndex (i); + } +} + + + +void +BayesNet::freeDistributions (void) +{ + for (unsigned i = 0; i < dists_.size(); i++) { + delete dists_[i]; + } +} + + + +void +BayesNet::printNetwork (void) const +{ + for (unsigned i = 0; i < nodes_.size(); i++) { + cout << *nodes_[i]; + } +} + + + +void +BayesNet::printNetworkToFile (const char* fileName) const +{ + string s = "../../" ; + s += fileName; + ofstream out (s.c_str()); + if (!out.is_open()) { + cerr << "error: cannot open file to write at " ; + cerr << "BayesNet::printToFile()" << endl; + abort(); + } + for (unsigned i = 0; i < nodes_.size(); i++) { + out << *nodes_[i]; + } + out.close(); +} + + + +void +BayesNet::exportToDotFile (const char* fileName, + bool showNeighborless, + const NodeSet& highlightNodes) const +{ + string s = "../../" ; + s+= fileName; + ofstream out (s.c_str()); + if (!out.is_open()) { + cerr << "error: cannot open file to write at " ; + cerr << "BayesNet::exportToDotFile()" << endl; + abort(); + } + + out << "digraph \"" << fileName << "\" {" << endl; + for (unsigned i = 0; i < nodes_.size(); i++) { + const NodeSet& childs = nodes_[i]->getChilds(); + for (unsigned j = 0; j < childs.size(); j++) { + out << '"' << nodes_[i]->getLabel() << '"' << " -> " ; + out << '"' << childs[j]->getLabel() << '"' << endl; + } + } + + for (unsigned i = 0; i < nodes_.size(); i++) { + if (showNeighborless || nodes_[i]->hasNeighbors()) { + out << '"' << nodes_[i]->getLabel() << '"' ; + if (nodes_[i]->hasEvidence()) { + out << " [style=filled, fillcolor=yellow]" << endl; + } else { + out << endl; + } + } + } + + for (unsigned i = 0; i < highlightNodes.size(); i++) { + out << '"' << highlightNodes[i]->getLabel() << '"' ; + out << " [shape=box]" << endl; + } + + out << "}" << endl; + out.close(); +} + + + +void +BayesNet::exportToBifFile (const char* fileName) const +{ + string s = "../../" ; + s += fileName; + ofstream out (s.c_str()); + if(!out.is_open()) { + cerr << "error: cannot open file to write at " ; + cerr << "BayesNet::exportToBifFile()" << endl; + abort(); + } + out << "" << endl; + out << "" << endl; + out << "" << endl; + out << "" << fileName << "" << endl << endl; + for (unsigned i = 0; i < nodes_.size(); i++) { + out << "" << endl; + out << "\t" << nodes_[i]->getLabel() << "" << endl; + const Domain& domain = nodes_[i]->getDomain(); + for (unsigned j = 0; j < domain.size(); j++) { + out << "\t" << domain[j] << "" << endl; + } + out << "" << endl << endl; + } + + for (unsigned i = 0; i < nodes_.size(); i++) { + out << "" << endl; + out << "\t" << nodes_[i]->getLabel() << "" << endl; + const NodeSet& parents = nodes_[i]->getParents(); + for (unsigned j = 0; j < parents.size(); j++) { + out << "\t" << parents[j]->getLabel(); + out << "" << endl; + } + ParamSet params = revertParameterReorder (nodes_[i]->getParameters(), + nodes_[i]->getDomainSize()); + out << "\t" ; + for (unsigned j = 0; j < params.size(); j++) { + out << " " << params[j]; + } + out << "
" << endl; + out << "
" << endl << endl; + } + out << "
" << endl; + out << "
" << endl << endl; + out.close(); +} + + + +bool +BayesNet::containsUndirectedCycle (void) const +{ + vector visited (nodes_.size(), false); + for (unsigned i = 0; i < nodes_.size(); i++) { + int v = nodes_[i]->getIndex(); + if (!visited[v]) { + if (containsUndirectedCycle (v, -1, visited)) { + return true; + } + } + } + return false; +} + + + +bool +BayesNet::containsUndirectedCycle (int v, + int p, + vector& visited) const +{ + visited[v] = true; + vector adjacencies = getAdjacentNodes (v); + for (unsigned i = 0; i < adjacencies.size(); i++) { + int w = adjacencies[i]; + if (!visited[w]) { + if (containsUndirectedCycle (w, v, visited)) { + return true; + } + } + else if (visited[w] && w != p) { + return true; + } + } + return false; // no cycle detected in this component +} + + + +vector +BayesNet::getAdjacentNodes (int v) const +{ + vector adjacencies; + const NodeSet& parents = nodes_[v]->getParents(); + const NodeSet& childs = nodes_[v]->getChilds(); + for (unsigned i = 0; i < parents.size(); i++) { + adjacencies.push_back (parents[i]->getIndex()); + } + for (unsigned i = 0; i < childs.size(); i++) { + adjacencies.push_back (childs[i]->getIndex()); + } + return adjacencies; +} + + + +ParamSet +BayesNet::reorderParameters (const ParamSet& params, + int domainSize) const +{ + // the interchange format for bayesian networks keeps the probabilities + // in the following order: + // p(a1|b1,c1) p(a2|b1,c1) p(a1|b1,c2) p(a2|b1,c2) p(a1|b2,c1) p(a2|b2,c1) + // p(a1|b2,c2) p(a2|b2,c2). + // + // however, in clpbn we keep the probabilities in this order: + // p(a1|b1,c1) p(a1|b1,c2) p(a1|b2,c1) p(a1|b2,c2) p(a2|b1,c1) p(a2|b1,c2) + // p(a2|b2,c1) p(a2|b2,c2). + unsigned count = 0; + unsigned rowSize = params.size() / domainSize; + ParamSet reordered; + while (reordered.size() < params.size()) { + unsigned idx = count; + for (unsigned i = 0; i < rowSize; i++) { + reordered.push_back (params[idx]); + idx += domainSize; + } + count++; + } + return reordered; +} + + + +ParamSet +BayesNet::revertParameterReorder (const ParamSet& params, + int domainSize) const +{ + unsigned count = 0; + unsigned rowSize = params.size() / domainSize; + ParamSet reordered; + while (reordered.size() < params.size()) { + unsigned idx = count; + for (int i = 0; i < domainSize; i++) { + reordered.push_back (params[idx]); + idx += rowSize; + } + count ++; + } + return reordered; +} + diff --git a/packages/CLPBN/clpbn/bp/BayesNet.h b/packages/CLPBN/clpbn/bp/BayesNet.h new file mode 100755 index 000000000..547671f31 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/BayesNet.h @@ -0,0 +1,129 @@ +#ifndef BP_BAYES_NET_H +#define BP_BAYES_NET_H + +#include +#include +#include +#include +#include +#include + +#include "GraphicalModel.h" +#include "BayesNode.h" +#include "Shared.h" + + +using namespace std; + +class Distribution; + +struct ScheduleInfo +{ + ScheduleInfo (BayesNode* n, bool vfp, bool vfc) + { + node = n; + visitedFromParent = vfp; + visitedFromChild = vfc; + } + BayesNode* node; + bool visitedFromParent; + bool visitedFromChild; +}; + + +struct StateInfo +{ + StateInfo (void) + { + visited = true; + markedOnTop = false; + markedOnBottom = false; + } + bool visited; + bool markedOnTop; + bool markedOnBottom; +}; + +typedef vector DistSet; +typedef queue > Scheduling; +typedef unordered_map Histogram; +typedef unordered_map Times; + + +class BayesNet : public GraphicalModel +{ + public: + BayesNet (void); + BayesNet (const char*); + ~BayesNet (void); + + BayesNode* addNode (unsigned); + BayesNode* addNode (unsigned, unsigned, int, NodeSet&, Distribution*); + BayesNode* addNode (string, Domain, NodeSet&, ParamSet&); + BayesNode* getNode (unsigned) const; + BayesNode* getNode (string) const; + void addDistribution (Distribution*); + Distribution* getDistribution (unsigned) const; + const NodeSet& getNodes (void) const; + int getNumberOfNodes (void) const; + NodeSet getRootNodes (void) const; + NodeSet getLeafNodes (void) const; + VarSet getVariables (void) const; + BayesNet* pruneNetwork (BayesNode*) const; + BayesNet* pruneNetwork (const NodeSet& queryNodes) const; + void constructGraph (BayesNet*, const vector&) const; + bool isSingleConnected (void) const; + static vector getDomainConfigurationsOf (const NodeSet&); + static vector getInstantiations (const NodeSet& nodes); + void setIndexes (void); + void freeDistributions (void); + void printNetwork (void) const; + void printNetworkToFile (const char*) const; + void exportToDotFile (const char*, bool = true, + const NodeSet& = NodeSet()) const; + void exportToBifFile (const char*) const; + + static Histogram histogram_; + static Times times_; + + private: + DISALLOW_COPY_AND_ASSIGN (BayesNet); + + bool containsUndirectedCycle (void) const; + bool containsUndirectedCycle (int, int, + vector&)const; + vector getAdjacentNodes (int) const ; + ParamSet reorderParameters (const ParamSet&, int) const; + ParamSet revertParameterReorder (const ParamSet&, int) const; + void scheduleParents (const BayesNode*, Scheduling&) const; + void scheduleChilds (const BayesNode*, Scheduling&) const; + + NodeSet nodes_; + DistSet dists_; + IndexMap indexMap_; +}; + + + +inline void +BayesNet::scheduleParents (const BayesNode* n, Scheduling& sch) const +{ + const NodeSet& ps = n->getParents(); + for (NodeSet::const_iterator it = ps.begin(); it != ps.end(); it++) { + sch.push (ScheduleInfo (*it, false, true)); + } +} + + + +inline void +BayesNet::scheduleChilds (const BayesNode* n, Scheduling& sch) const +{ + const NodeSet& cs = n->getChilds(); + for (NodeSet::const_iterator it = cs.begin(); it != cs.end(); it++) { + sch.push (ScheduleInfo (*it, true, false)); + } +} + +#endif + diff --git a/packages/CLPBN/clpbn/bp/BayesNode.cpp b/packages/CLPBN/clpbn/bp/BayesNode.cpp new file mode 100755 index 000000000..72ed5febd --- /dev/null +++ b/packages/CLPBN/clpbn/bp/BayesNode.cpp @@ -0,0 +1,355 @@ +#include +#include +#include +#include +#include + +#include "BayesNode.h" + + +BayesNode::BayesNode (unsigned varId) : Variable (varId) +{ +} + + + +BayesNode::BayesNode (unsigned varId, + unsigned dsize, + int evidence, + const NodeSet& parents, + Distribution* dist) : Variable(varId, dsize, evidence) +{ + parents_ = parents; + dist_ = dist; + for (unsigned int i = 0; i < parents.size(); i++) { + parents[i]->addChild (this); + } +} + + + +BayesNode::BayesNode (unsigned varId, + string label, + const Domain& domain, + const NodeSet& parents, + Distribution* dist) : Variable(varId, domain) +{ + label_ = new string (label); + parents_ = parents; + dist_ = dist; + for (unsigned int i = 0; i < parents.size(); i++) { + parents[i]->addChild (this); + } +} + + + +void +BayesNode::setData (unsigned dsize, + int evidence, + const NodeSet& parents, + Distribution* dist) +{ + setDomainSize (dsize); + evidence_ = evidence; + parents_ = parents; + dist_ = dist; + for (unsigned int i = 0; i < parents.size(); i++) { + parents[i]->addChild (this); + } +} + + + +void +BayesNode::addChild (BayesNode* node) +{ + childs_.push_back (node); +} + + + +Distribution* +BayesNode::getDistribution (void) +{ + return dist_; +} + + + +const ParamSet& +BayesNode::getParameters (void) +{ + return dist_->params; +} + + + +ParamSet +BayesNode::getRow (int rowIndex) const +{ + int rowSize = getRowSize(); + int offset = rowSize * rowIndex; + ParamSet row (rowSize); + for (int i = 0; i < rowSize; i++) { + row[i] = dist_->params[offset + i] ; + } + return row; +} + + + +bool +BayesNode::isRoot (void) +{ + return getParents().empty(); +} + + + +bool +BayesNode::isLeaf (void) +{ + return getChilds().empty(); +} + + + +bool +BayesNode::hasNeighbors (void) const +{ + return childs_.size() != 0 || parents_.size() != 0; +} + + +int +BayesNode::getCptSize (void) +{ + return dist_->params.size(); +} + + + +const vector& +BayesNode::getCptEntries (void) +{ + if (dist_->entries.size() == 0) { + unsigned rowSize = getRowSize(); + unsigned nParents = parents_.size(); + vector confs (rowSize); + + for (unsigned i = 0; i < rowSize; i++) { + confs[i].resize (nParents); + } + + int nReps = 1; + for (int i = nParents - 1; i >= 0; i--) { + unsigned index = 0; + while (index < rowSize) { + for (int j = 0; j < parents_[i]->getDomainSize(); j++) { + for (int r = 0; r < nReps; r++) { + confs[index][i] = j; + index++; + } + } + } + nReps *= parents_[i]->getDomainSize(); + } + + dist_->entries.reserve (rowSize); + for (unsigned i = 0; i < rowSize; i++) { + dist_->entries.push_back (CptEntry (i, confs[i])); + } + } + return dist_->entries; +} + + + +int +BayesNode::getIndexOfParent (const BayesNode* parent) const +{ + for (unsigned int i = 0; i < parents_.size(); i++) { + if (parents_[i] == parent) { + return i; + } + } + return -1; +} + + + +string +BayesNode::cptEntryToString (const CptEntry& entry) const +{ + stringstream ss; + ss << "p(" ; + const DomainConf& conf = entry.getParentConfigurations(); + int row = entry.getParameterIndex() / getRowSize(); + ss << getDomain()[row]; + if (parents_.size() > 0) { + ss << "|" ; + for (unsigned int i = 0; i < conf.size(); i++) { + if (i != 0) { + ss << ","; + } + ss << parents_[i]->getDomain()[conf[i]]; + } + } + ss << ")" ; + return ss.str(); +} + + + +string +BayesNode::cptEntryToString (int row, const CptEntry& entry) const +{ + stringstream ss; + ss << "p(" ; + const DomainConf& conf = entry.getParentConfigurations(); + ss << getDomain()[row]; + if (parents_.size() > 0) { + ss << "|" ; + for (unsigned int i = 0; i < conf.size(); i++) { + if (i != 0) { + ss << ","; + } + ss << parents_[i]->getDomain()[conf[i]]; + } + } + ss << ")" ; + return ss.str(); +} + + + +vector +BayesNode::getDomainHeaders (void) const +{ + int nParents = parents_.size(); + int rowSize = getRowSize(); + int nReps = 1; + vector headers (rowSize); + for (int i = nParents - 1; i >= 0; i--) { + Domain domain = parents_[i]->getDomain(); + int index = 0; + while (index < rowSize) { + for (int j = 0; j < parents_[i]->getDomainSize(); j++) { + for (int r = 0; r < nReps; r++) { + if (headers[index] != "") { + headers[index] = domain[j] + "," + headers[index]; + } else { + headers[index] = domain[j]; + } + index++; + } + } + } + nReps *= parents_[i]->getDomainSize(); + } + return headers; +} + + + +ostream& +operator << (ostream& o, const BayesNode& node) +{ + o << "variable " << node.getIndex() << endl; + o << "Var Id: " << node.getVarId() << endl; + o << "Label: " << node.getLabel() << endl; + + o << "Evidence: " ; + if (node.hasEvidence()) { + o << node.getEvidence(); + } + else { + o << "no" ; + } + o << endl; + + o << "Parents: " ; + const NodeSet& parents = node.getParents(); + if (parents.size() != 0) { + for (unsigned int i = 0; i < parents.size() - 1; i++) { + o << parents[i]->getLabel() << ", " ; + } + o << parents[parents.size() - 1]->getLabel(); + } + o << endl; + + o << "Childs: " ; + const NodeSet& childs = node.getChilds(); + if (childs.size() != 0) { + for (unsigned int i = 0; i < childs.size() - 1; i++) { + o << childs[i]->getLabel() << ", " ; + } + o << childs[childs.size() - 1]->getLabel(); + } + o << endl; + + o << "Domain: " ; + Domain domain = node.getDomain(); + for (unsigned int i = 0; i < domain.size() - 1; i++) { + o << domain[i] << ", " ; + } + if (domain.size() != 0) { + o << domain[domain.size() - 1]; + } + o << endl; + + // min width of first column + const unsigned int MIN_DOMAIN_WIDTH = 4; + // min width of following columns + const unsigned int MIN_COMBO_WIDTH = 12; + + unsigned int domainWidth = domain[0].length(); + for (unsigned int i = 1; i < domain.size(); i++) { + if (domain[i].length() > domainWidth) { + domainWidth = domain[i].length(); + } + } + domainWidth = (domainWidth < MIN_DOMAIN_WIDTH) + ? MIN_DOMAIN_WIDTH + : domainWidth; + + o << left << setw (domainWidth) << "cpt" << right; + + vector widths; + int lineWidth = domainWidth; + vector headers = node.getDomainHeaders(); + + if (!headers.empty()) { + for (unsigned int i = 0; i < headers.size(); i++) { + unsigned int len = headers[i].length(); + int w = (len < MIN_COMBO_WIDTH) ? MIN_COMBO_WIDTH : len; + widths.push_back (w); + o << setw (w) << headers[i]; + lineWidth += w; + } + o << endl; + } else { + cout << endl; + widths.push_back (domainWidth); + lineWidth += MIN_COMBO_WIDTH; + } + + for (int i = 0; i < lineWidth; i++) { + o << "-" ; + } + o << endl; + + for (unsigned int i = 0; i < domain.size(); i++) { + ParamSet row = node.getRow (i); + o << left << setw (domainWidth) << domain[i] << right; + for (unsigned j = 0; j < node.getRowSize(); j++) { + o << setw (widths[j]) << row[j]; + } + o << endl; + } + o << endl; + + return o; +} + diff --git a/packages/CLPBN/clpbn/bp/BayesNode.h b/packages/CLPBN/clpbn/bp/BayesNode.h new file mode 100755 index 000000000..923cca0f1 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/BayesNode.h @@ -0,0 +1,91 @@ +#ifndef BP_BAYESNODE_H +#define BP_BAYESNODE_H + +#include +#include +#include + +#include "Variable.h" +#include "CptEntry.h" +#include "Distribution.h" +#include "Shared.h" + +using namespace std; + + +class BayesNode : public Variable +{ + public: + BayesNode (unsigned); + BayesNode (unsigned, unsigned, int, const NodeSet&, Distribution*); + BayesNode (unsigned, string, const Domain&, const NodeSet&, Distribution*); + + void setData (unsigned, int, const NodeSet&, Distribution*); + void addChild (BayesNode*); + Distribution* getDistribution (void); + const ParamSet& getParameters (void); + ParamSet getRow (int) const; + void setProbability (int, const CptEntry&, double); + bool isRoot (void); + bool isLeaf (void); + bool hasNeighbors (void) const; + int getCptSize (void); + const vector& getCptEntries (void); + int getIndexOfParent (const BayesNode*) const; + string cptEntryToString (const CptEntry&) const; + string cptEntryToString (int, const CptEntry&) const; + // inlines + const NodeSet& getParents (void) const; + const NodeSet& getChilds (void) const; + double getProbability (int, const CptEntry& entry); + unsigned getRowSize (void) const; + + private: + DISALLOW_COPY_AND_ASSIGN (BayesNode); + + Domain getDomainHeaders (void) const; + friend ostream& operator << (ostream&, const BayesNode&); + + NodeSet parents_; + NodeSet childs_; + Distribution* dist_; +}; + +ostream& operator << (ostream&, const BayesNode&); + + + +inline const NodeSet& +BayesNode::getParents (void) const +{ + return parents_; +} + + + +inline const NodeSet& +BayesNode::getChilds (void) const +{ + return childs_; +} + + + +inline double +BayesNode::getProbability (int row, const CptEntry& entry) +{ + int col = entry.getParameterIndex(); + int idx = (row * getRowSize()) + col; + return dist_->params[idx]; +} + + + +inline unsigned +BayesNode::getRowSize (void) const +{ + return dist_->params.size() / getDomainSize(); +} + +#endif + diff --git a/packages/CLPBN/clpbn/bp/BayesianNetwork.cpp b/packages/CLPBN/clpbn/bp/BayesianNetwork.cpp deleted file mode 100644 index 1dd17af03..000000000 --- a/packages/CLPBN/clpbn/bp/BayesianNetwork.cpp +++ /dev/null @@ -1,208 +0,0 @@ -#include -#include -#include -#include - -#include "BayesianNetwork.h" -#include "BayesianNode.h" - -BayesianNetwork::BayesianNetwork (void) -{ -} - - - -BayesianNetwork::~BayesianNetwork (void) -{ - for (unsigned int i = 0; i < nodes_.size(); i++) { - delete nodes_[i]; - } - for (unsigned int i = 0; i < dists_.size(); i++) { - delete dists_[i]; - } -} - - - -void -BayesianNetwork::addNode (string varName, - vector parents, - int evidence, - int distId) -{ - for (unsigned int i = 0; i < dists_.size(); i++) { - if (dists_[i]->id == distId) { - BayesianNode* node = new BayesianNode (varName, parents, - dists_[i], evidence); - nodes_.push_back (node); - break; - } - } -} - - -void -BayesianNetwork::addNode (string varName, - vector parents, - double* params, - int nParams, - vector domain) -{ - Distribution* dist = new Distribution (params, nParams, domain); - BayesianNode* node = new BayesianNode (varName, parents, dist); - dists_.push_back (dist); - nodes_.push_back (node); -} - - - -BayesianNode* -BayesianNetwork::getNode (string varName) const -{ - for (unsigned int i = 0; i < nodes_.size(); i++) { - if (nodes_[i]->getVariableName() == varName) { - return nodes_[i]; - } - } - return 0; -} - - - -void -BayesianNetwork::addDistribution (int distId, - double* params, - int nParams, - vector domain) -{ - dists_.push_back (new Distribution (distId, params, nParams, domain)); -} - - - -vector -BayesianNetwork::getNodes (void) const -{ - return nodes_; -} - - - -vector -BayesianNetwork::getRootNodes (void) const -{ - vector roots; - for (unsigned int i = 0; i < nodes_.size(); i++) { - if (nodes_[i]->isRoot()) { - roots.push_back (nodes_[i]); - } - } - return roots; -} - - - -vector -BayesianNetwork::getLeafNodes (void) const -{ - vector leafs; - for (unsigned int i = 0; i < nodes_.size(); i++) { - if (nodes_[i]->isLeaf()) { - leafs.push_back (nodes_[i]); - } - } - return leafs; -} - - - -bool -BayesianNetwork::isPolyTree (void) const -{ - return !containsCycle(); -} - - - -void -BayesianNetwork::printNetwork (void) const -{ - for (unsigned int i = 0; i < nodes_.size(); i++) { - cout << *nodes_[i]; - } -} - - - -bool -BayesianNetwork::containsCycle (void) const -{ - vector visited (nodes_.size()); - for (unsigned int v = 0; v < nodes_.size(); v++) { - visited[v] = false; - } - - for (unsigned int v = 0; v < nodes_.size(); v++) { - if (!visited[v]) { - if (containsCycle (v, -1, visited)) { - return true; - } - } - } - - return false; -} - - - -bool -BayesianNetwork::containsCycle (int v, - int predecessor, - vector& visited) const -{ - visited[v] = true; - vector adjs = getAdjacentVertexes (v); - for (unsigned int i = 0; i < adjs.size(); i++) { - int w = adjs[i]; - if (!visited[w]) { - if (containsCycle (w, v, visited)) { - return true; - } - } - else if (visited[w] && w != predecessor) { - return true; - } - } - return false; // no cycle detected in this component -} - - - -int -BayesianNetwork::getIndexOf (const BayesianNode* node) const -{ - for (unsigned int i = 0; i < nodes_.size(); i++) { - if (node == nodes_[i]) { - return i; - } - } - return -1; -} - - - -vector -BayesianNetwork::getAdjacentVertexes (int v) const -{ - vector adjs; - vector parents = nodes_[v]->getParents(); - vector childs = nodes_[v]->getChilds(); - for (unsigned int i = 0; i < parents.size(); i++) { - adjs.push_back (getIndexOf (parents[i])); - } - for (unsigned int i = 0; i < childs.size(); i++) { - adjs.push_back (getIndexOf (childs[i])); - } - return adjs; -} - diff --git a/packages/CLPBN/clpbn/bp/BayesianNetwork.h b/packages/CLPBN/clpbn/bp/BayesianNetwork.h deleted file mode 100644 index 5003faaed..000000000 --- a/packages/CLPBN/clpbn/bp/BayesianNetwork.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef BAYESIAN_NETWORK_H -#define BAYESIAN_NETWORK_H - -#include -#include - -using namespace std; - -class BayesianNode; -class Distribution; - -class BayesianNetwork -{ - public: - // constructs - BayesianNetwork (void); - // destruct - virtual ~BayesianNetwork (void); - // methods - virtual void addNode (string, vector, int, int); - virtual void addNode (string, vector, - double*, int, vector); - BayesianNode* getNode (string) const; - void addDistribution (int, double*, int, vector); - vector getNodes (void) const; - vector getRootNodes (void) const; - vector getLeafNodes (void) const; - bool isPolyTree (void) const; - void printNetwork (void) const; - - protected: - // members - vector nodes_; - vector dists_; - - private: - BayesianNetwork (const BayesianNetwork&); // disallow copy - void operator= (const BayesianNetwork&); // disallow assign - bool containsCycle (void) const; - bool containsCycle (int, int, vector&) const; - int getIndexOf (const BayesianNode*) const; - vector getAdjacentVertexes (int) const ; -}; - -#endif // BAYESIAN_NETWORK_H - diff --git a/packages/CLPBN/clpbn/bp/BayesianNode.cpp b/packages/CLPBN/clpbn/bp/BayesianNode.cpp deleted file mode 100644 index 26a3106e5..000000000 --- a/packages/CLPBN/clpbn/bp/BayesianNode.cpp +++ /dev/null @@ -1,382 +0,0 @@ -#include -#include -#include - -#include "BayesianNode.h" -#include "CptEntry.h" - - -BayesianNode::BayesianNode (string varName, - vector parents, - Distribution* dist, - int evidence) -{ - varName_ = varName; - parents_ = parents; - dist_ = dist; - evidence_ = evidence; - for (unsigned int i = 0; i < parents.size(); i++) { - parents[i]->addChild (this); - } -} - - - -BayesianNode::~BayesianNode (void) -{ -} - - - -string -BayesianNode::getVariableName (void) const -{ - return varName_; -} - - - -vector -BayesianNode::getParents (void) const -{ - return parents_; -} - - - -vector -BayesianNode::getChilds (void) const -{ - return childs_; -} - - - -void -BayesianNode::addChild (BayesianNode* node) -{ - childs_.push_back (node); -} - - - -double* -BayesianNode::getParameters (void) -{ - return dist_->params; -} - - - -double* -BayesianNode::getRow (int rowIndex) const -{ - int offset = getRowSize() * rowIndex; - return &dist_->params[offset]; -} - - - -double -BayesianNode::getProbability (CptEntry& entry) -{ - int index = entry.getCptIndex(); - return dist_->params[index]; -} - - - -void -BayesianNode::setProbability (CptEntry& entry, double prob) -{ - int index = entry.getCptIndex(); - dist_->params[index] = prob; -} - - - -bool -BayesianNode::isRoot (void) -{ - return parents_.empty(); -} - - - -bool -BayesianNode::isLeaf (void) -{ - return childs_.empty(); -} - - - -int -BayesianNode::getRowSize (void) const -{ - return dist_->nParams / dist_->domain.size(); -} - - - -int -BayesianNode::getCptSize (void) -{ - return dist_->nParams; -} - - - -vector -BayesianNode::getDomain (void) const -{ - return dist_->domain; -} - - - -int -BayesianNode::getDomainSize (void) const -{ - return dist_->domain.size(); -} - - - -vector -BayesianNode::getCptEntries (const vector >& constraints) -{ - vector matchedEntries; - if (constraints.size() > 0 && constraints[0].first == 0) { - vector entries = getCptEntriesOfRow (constraints[0].second); - for (unsigned int i = 0; i < entries.size(); i++) { - if (entries[i].matchConstraints (constraints)) { - matchedEntries.push_back (entries[i]); - } - } - } - else { - for (unsigned int i = 0; i < dist_->domain.size(); i++) { - vector entries = getCptEntriesOfRow (i); - for (unsigned int j = 0; j < entries.size(); j++) { - if (entries[j].matchConstraints (constraints)) { - matchedEntries.push_back (entries[j]); - } - } - } - } - return matchedEntries; -} - - - -vector -BayesianNode::getCptEntriesOfRow (int rowIndex) -{ - int rowSize = getRowSize(); - int nParents = parents_.size(); - vector > insts (rowSize); - - for (int i = 0; i < rowSize; i++) { - insts[i].resize (nParents + 1); - insts[i][0] = rowIndex; - } - - int reps = 1; - for (int i = nParents - 1; i >= 0; i--) { - int index = 0; - while (index < rowSize) { - for (int j = 0; j < parents_[i]->getDomainSize(); j++) { - for (int k = 0; k < reps; k++) { - insts[index][i + 1] = j; - index++; - } - } - } - reps *= parents_[i]->getDomainSize(); - } - - vector entries; - for (int i = 0; i < rowSize; i++ ) { - entries.push_back (CptEntry ((rowIndex * rowSize) + i, insts[i])); - } - - return entries; -} - - - -int -BayesianNode::getIndexOfParent (const BayesianNode* myParent) const -{ - for (unsigned int i = 0; i < parents_.size(); i++) { - if (myParent == parents_[i]) { - return i; - } - } - return -1; -} - - - -bool -BayesianNode::hasEvidence (void) -{ - return evidence_ != -1; -} - - - -int -BayesianNode::getEvidence (void) -{ - return evidence_; -} - - - -void -BayesianNode::setEvidence (int evidence) -{ - evidence_ = evidence; -} - - - -string -BayesianNode::entryToString (const CptEntry& entry) const -{ - string s = "p(" ; - vector insts = entry.getDomainInstantiations(); - s += getDomain()[insts[0]]; - if (parents_.size() > 0) { - s += "|" ; - for (unsigned int i = 1; i < insts.size() - 1; i++) { - s += parents_[i - 1]->getDomain()[insts[i]] + ","; - } - BayesianNode* lastParent = parents_[parents_.size() - 1]; - int lastIndex = insts[insts.size() - 1]; - s += lastParent->getDomain()[lastIndex]; - } - s += ")" ; - return s; -} - - - -vector -BayesianNode::getDomainHeaders (void) const -{ - int rowSize = getRowSize(); - int nParents = parents_.size(); - int reps = 1; - vector headers (rowSize); - for (int i = nParents - 1; i >= 0; i--) { - vector domain = parents_[i]->getDomain(); - int index = 0; - while (index < rowSize) { - for (int j = 0; j < parents_[i]->getDomainSize(); j++) { - for (int k = 0; k < reps; k++) { - if (headers[index] != "") { - headers[index] = domain[j] + "," + headers[index]; - } else { - headers[index] = domain[j]; - } - index++; - } - } - } - reps *= parents_[i]->getDomainSize(); - } - return headers; -} - - - -ostream& -operator << (ostream& o, const BayesianNode& node) -{ - o << "Variable: " << node.getVariableName() << endl; - - o << "Domain: " ; - vector domain = node.dist_->domain; - for (unsigned int i = 0; i < domain.size() - 1; i++) { - o << domain[i] << ", " ; - } - if (domain.size() != 0) { - o << domain[domain.size() - 1]; - } - o << endl; - - o << "Parents: " ; - vector parents = node.getParents(); - if (parents.size() != 0) { - for (unsigned int i = 0; i < parents.size() - 1; i++) { - o << parents[i]->getVariableName() << ", " ; - } - o << parents[parents.size() - 1]->getVariableName(); - } - o << endl; - - o << "Childs: " ; - vector childs = node.getChilds(); - if (childs.size() != 0) { - for (unsigned int i = 0; i < childs.size() - 1; i++) { - o << childs[i]->getVariableName() << ", " ; - } - o << childs[childs.size() - 1]->getVariableName(); - } - o << endl; - - const unsigned int MIN_DOMAIN_WIDTH = 4; // min width of first column - const unsigned int MIN_COMBO_WIDTH = 12; // min width of following columns - - unsigned int domainWidth = domain[0].length(); - for (unsigned int i = 1; i < domain.size(); i++) { - if (domain[i].length() > domainWidth) { - domainWidth = domain[i].length(); - } - } - - domainWidth = (domainWidth < MIN_DOMAIN_WIDTH) - ? MIN_DOMAIN_WIDTH - : domainWidth; - - o << left << setw (domainWidth) << "cpt" << right; - - vector widths; - int lineWidth = domainWidth; - vector headers = node.getDomainHeaders(); - if (!headers.empty()) { - for (unsigned int i = 0; i < headers.size(); i++) { - unsigned int len = headers[i].length(); - int w = (len < MIN_COMBO_WIDTH) ? MIN_COMBO_WIDTH : len; - widths.push_back (w); - o << setw (w) << headers[i]; - lineWidth += w; - } - o << endl; - } else { - cout << endl; - widths.push_back (domainWidth); - lineWidth += MIN_COMBO_WIDTH; - } - - for (int i = 0; i < lineWidth; i++) { - o << "-" ; - } - o << endl; - - for (unsigned int i = 0; i < domain.size(); i++) { - double* row = node.getRow (i); - o << left << setw (domainWidth) << domain[i] << right; - for (int j = 0; j < node.getRowSize(); j++) { - o << setw (widths[j]) << row[j]; - } - o << endl; - } - o << endl; - - return o; -} - diff --git a/packages/CLPBN/clpbn/bp/BayesianNode.h b/packages/CLPBN/clpbn/bp/BayesianNode.h deleted file mode 100644 index 63b1dc301..000000000 --- a/packages/CLPBN/clpbn/bp/BayesianNode.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef BAYESIAN_NODE_H -#define BAYESIAN_NODE_H - -#include -#include - -#include "Distribution.h" -#include "CptEntry.h" - -using namespace std; - -class BayesianNode -{ - public: - // constructs - BayesianNode (string, vector, Distribution*, int = -1); - // destruct - ~BayesianNode (void); - // methods - string getVariableName (void) const; - vector getParents (void) const; - vector getChilds (void) const; - void addChild (BayesianNode*); - double* getParameters (void); - double* getRow (int) const; - double getProbability (CptEntry&); - void setProbability (CptEntry&, double); - bool isRoot (void); - bool isLeaf (void); - int getRowSize (void) const; - int getCptSize (void); - vector getDomain (void) const; - int getDomainSize (void) const; - vector getCptEntries (const vector >&); - vector getCptEntriesOfRow (int); - int getIndexOfParent (const BayesianNode*) const; - bool hasEvidence (void); - int getEvidence (void); - void setEvidence (int); - string entryToString (const CptEntry& entry) const; - - private: - BayesianNode (const BayesianNode&); // disallow copy - void operator= (const BayesianNode&); // disallow assign - // methods - vector getDomainHeaders (void) const; - friend ostream& operator << (ostream&, const BayesianNode&); - // members - string varName_; // variable name - vector parents_; // parents of this node - vector childs_; // children of this node - Distribution* dist_; - int evidence_; -}; - -ostream& operator << (ostream&, const BayesianNode&); - -#endif // BAYESIAN_NODE_H - diff --git a/packages/CLPBN/clpbn/bp/BifInterface.cpp b/packages/CLPBN/clpbn/bp/BifInterface.cpp deleted file mode 100644 index ba38030af..000000000 --- a/packages/CLPBN/clpbn/bp/BifInterface.cpp +++ /dev/null @@ -1,117 +0,0 @@ -#include -#include -#include - -#include "xmlParser/xmlParser.h" - -#include "BifInterface.h" -#include "BayesianNetwork.h" -#include "BayesianNode.h" - - -void -BifInterface::createNetworkFromXML (BayesianNetwork* bn, const char* fileName) -{ - map > domains; - XMLNode xMainNode = XMLNode::openFileHelper (fileName, "BIF"); - // only the first network is parsed, others are ignored - XMLNode xNode = xMainNode.getChildNode ("NETWORK"); - int nVars = xNode.nChildNode ("VARIABLE"); - for (int i = 0; i < nVars; i++) { - XMLNode var = xNode.getChildNode ("VARIABLE", i); - string type = var.getAttribute ("TYPE"); - if (type != "nature") { - cerr << "error: only \"nature\" variables are supported" << endl; - abort(); - } - vector domain; - string varName = var.getChildNode("NAME").getText(); - int domainSize = var.nChildNode ("OUTCOME"); - for (int j = 0; j < domainSize; j++) { - domain.push_back (var.getChildNode("OUTCOME", j).getText()); - } - domains.insert (make_pair (varName, domain)); - } - - int nDefs = xNode.nChildNode ("DEFINITION"); - if (nVars != nDefs) { - cerr << "error: different number of variables and definitions"; - cerr << endl; - } - - for (int i = 0; i < nDefs; i++) { - XMLNode def = xNode.getChildNode ("DEFINITION", i); - string nodeName = def.getChildNode("FOR").getText(); - map >::const_iterator iter = domains.find (nodeName); - if (iter == domains.end()) { - cerr << "error: unknow variable `" << nodeName << "'" << endl; - abort(); - } - vector parents; - int nParams = iter->second.size(); - for (int j = 0; j < def.nChildNode ("GIVEN"); j++) { - string parentName = def.getChildNode("GIVEN", j).getText(); - BayesianNode* parentNode = bn->getNode (parentName); - if (parentNode) { - nParams *= parentNode->getDomainSize(); - parents.push_back (parentNode); - } - else { - cerr << "error: unknow variable `" << parentName << "'" << endl; - abort(); - } - } - - int c = 0; - double* params = new double [nParams]; - stringstream s (def.getChildNode("TABLE").getText()); - while (!s.eof() && c < nParams) { - s >> params[c]; - c++; - } - if (c != nParams) { - cerr << "error: invalid number of parameters " ; - cerr << "for variable `" << nodeName << "'" << endl; - abort(); - } - - params = reorderParameters (params, nParams, iter->second.size()); - bn->addNode (nodeName, parents, params, nParams, iter->second); - } -} - - -double* -BifInterface::reorderParameters (double* params, - int nParams, - int domainSize) -{ - // the interchange format for bayesian networks saves the probabilities - // in the following order: - // p(a1|b1,c1) p(a2|b1,c1) p(a1|b1,c2) p(a2|b1,c2) p(a1|b2,c1) p(a2|b2,c1) - // p(a1|b2,c2) p(a2|b2,c2). - // - // however, in clpbn we keep the probabilities in this order: - // p(a1|b1,c1) p(a1|b1,c2) p(a1|b2,c1) p(a1|b2,c2) p(a2|b1,c1) p(a2|b1,c2) - // p(a2|b2,c1) p(a2|b2,c2). - - int count = 0; - int index1 = 0; - int index2 = 0; - int rowSize = nParams / domainSize; - double* reordered = new double [nParams]; - - while (index1 < nParams) { - index2 = count; - for (int i = 0; i < domainSize; i++) { - reordered[index2] = params[index1]; - index1 += 1; - index2 += rowSize; - } - count++; - } - - delete [] params; - return reordered; -} - diff --git a/packages/CLPBN/clpbn/bp/BifInterface.h b/packages/CLPBN/clpbn/bp/BifInterface.h deleted file mode 100644 index 84f3cceb0..000000000 --- a/packages/CLPBN/clpbn/bp/BifInterface.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef BIF_INTERFACE_H -#define BIF_INTERFACE_H - -using namespace std; - -class BayesianNetwork; -class BayesianNode; - -class BifInterface -{ - public: - static void createNetworkFromXML (BayesianNetwork*, const char*); - - private: - static double* reorderParameters (double*, int, int); -}; - -#endif // BIF_INTERFACE_H - - diff --git a/packages/CLPBN/clpbn/bp/BifTest.cpp b/packages/CLPBN/clpbn/bp/BifTest.cpp deleted file mode 100644 index 13420e6aa..000000000 --- a/packages/CLPBN/clpbn/bp/BifTest.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include - -#include "BayesianNetwork.h" -#include "BayesianNode.h" -#include "BpNetwork.h" -#include "BpNode.h" -#include "BifInterface.h" - -using namespace std; - -int main (int argc, char* argv[]) -{ - BpNetwork bn; - // BayesianNetwork bn; - BifInterface::createNetworkFromXML (&bn, argv[1]); - bn.printNetwork(); - - // bn.getNode("FreightTruck")->setEvidence (0); - // bn.getNode("Alarm")->setEvidence (0); - - // bn.setSolverParameters (SEQUENTIAL_SCHEDULE, 500, 0.001); - // bn.setSolverParameters (PARALLEL_SCHEDULE, 500, 0.00000000000001); - // bn.setSolverParameters (PARALLEL_SCHEDULE, 500, 0.0000000000000000000001); - - //bn.getNode ("F")->setEvidence (0); - vector queryVars; - //queryVars.push_back (bn.getNode ("D")); - //queryVars.push_back (bn.getNode ("Burglar")); - queryVars.push_back (bn.getNode ("FreightTruck")); - queryVars.push_back (bn.getNode ("Alarm")); - bn.runSolver (queryVars); - - // bn.printCurrentStatus(); - // bn.printBeliefs(); - return 0; -} diff --git a/packages/CLPBN/clpbn/bp/BpNode.cpp b/packages/CLPBN/clpbn/bp/BpNode.cpp index 8f784ab16..4fd52f95c 100644 --- a/packages/CLPBN/clpbn/bp/BpNode.cpp +++ b/packages/CLPBN/clpbn/bp/BpNode.cpp @@ -4,226 +4,44 @@ #include "BpNode.h" +bool BpNode::calculateMessageResidual_ = true; -bool BpNode::parallelSchedule_ = false; -BpNode::BpNode (string varName, - vector parents, - Distribution* dist, - int evidence) : BayesianNode (varName, parents, dist, evidence) +BpNode::BpNode (BayesNode* node) { - -} - - - -BpNode::~BpNode (void) -{ - delete [] piValues_; - delete [] lambdaValues_; - delete [] oldBeliefs_; - map::iterator iter; - for (iter = lambdaMessages_.begin(); iter != lambdaMessages_.end(); ++iter) { - delete [] iter->second; + ds_ = node->getDomainSize(); + const NodeSet& childs = node->getChilds(); + piVals_.resize (ds_, 1); + ldVals_.resize (ds_, 1); + if (calculateMessageResidual_) { + piResiduals_.resize (childs.size(), 0.0); + ldResiduals_.resize (childs.size(), 0.0); } - for (iter = piMessages_.begin(); iter != piMessages_.end(); ++iter) { - delete [] iter->second; - } - // FIXME delete new messages -} - - - -void -BpNode::enableParallelSchedule (void) -{ - parallelSchedule_ = true; -} - - - -void -BpNode::allocateMemory (void) -{ - // FIXME do i need this !? - int domainSize = getDomainSize(); - piValues_ = new double [domainSize]; - lambdaValues_ = new double [domainSize]; - if (parallelSchedule_) { - newPiMessages_ = new map; - newLambdaMessages_ = new map; - } - oldBeliefs_ = 0; - vector childs = getChilds(); - for (unsigned int i = 0; i < childs.size(); i++) { - BpNode* child = static_cast (childs[i]); - piMessages_.insert (make_pair (child, new double [domainSize])); - lambdaMessages_.insert (make_pair (child, new double [domainSize])); - if (parallelSchedule_) { - newPiMessages_->insert (make_pair (child, new double [domainSize])); - newLambdaMessages_->insert (make_pair (child, new double [domainSize])); - } + childs_ = &childs; + for (unsigned i = 0; i < childs.size(); i++) { + //indexMap_.insert (make_pair (childs[i]->getVarId(), i)); + currPiMsgs_.push_back (ParamSet (ds_, 1)); + currLdMsgs_.push_back (ParamSet (ds_, 1)); + nextPiMsgs_.push_back (ParamSet (ds_, 1)); + nextLdMsgs_.push_back (ParamSet (ds_, 1)); } } -double* -BpNode::getPiValues (void) const +ParamSet +BpNode::getBeliefs (void) const { - return piValues_; -} - - - -double -BpNode::getPiValue (int index) const -{ - const int c = getDomainSize(); - assert (index >=0 && index < c); - return piValues_[index]; -} - - - -void -BpNode::setPiValue (int index, double value) -{ - const int c = getDomainSize(); - assert (index >=0 && index < c); - piValues_[index] = value; -} - - - -double* -BpNode::getLambdaValues (void) const -{ - return lambdaValues_; -} - - - -double -BpNode::getLambdaValue (int index) const -{ - const int c = getDomainSize(); - assert (index >=0 && index < c); - return lambdaValues_[index]; -} - - - -void -BpNode::setLambdaValue (int index, double value) -{ - const int c = getDomainSize(); - assert (index >=0 && index < c); - lambdaValues_[index] = value; -} - - - -double* -BpNode::getPiMessages (BpNode* node) const -{ - assert (node); - map::const_iterator iter = piMessages_.find (node); - assert (iter != piMessages_.end()); - return iter->second; -} - - - -double -BpNode::getPiMessage (BpNode* node, int index) const -{ - assert (node); - const int c = getDomainSize(); - assert (index >=0 && index < c); - map::const_iterator iter = piMessages_.find (node); - assert (iter != piMessages_.end()); - return iter->second[index]; -} - - - -void -BpNode::setPiMessage (BpNode* node, int index, double probability) -{ - assert (node); - const int c = getDomainSize(); - assert (index >=0 && index < c); - map::const_iterator iter; - if (parallelSchedule_) { - // cerr << "set_pi_message" << endl; - iter = newPiMessages_->find (node); - assert (iter != newPiMessages_->end()); - } else { - iter = piMessages_.find (node); - assert (iter != piMessages_.end()); - } - iter->second[index] = probability; -} - - - -double* -BpNode::getLambdaMessages (BpNode* node) const -{ - assert (node); - map::const_iterator iter = lambdaMessages_.find (node); - assert (iter != piMessages_.end()); - return iter->second; -} - - - -double -BpNode::getLambdaMessage (BpNode* node, int index) const -{ - assert (node); - const int c = getDomainSize(); - assert (index >=0 && index < c); - map::const_iterator iter = lambdaMessages_.find (node); - assert (iter != piMessages_.end()); - return iter->second[index]; -} - - - -void -BpNode::setLambdaMessage (BpNode* node, int index, double probability) -{ - assert (node); - const int c = getDomainSize(); - assert (index >=0 && index < c); - map::const_iterator iter; - if (parallelSchedule_) { - //cerr << "set_lambda_message" << endl; - iter = newLambdaMessages_->find (node); - assert (iter != newLambdaMessages_->end()); - } else { - iter = lambdaMessages_.find (node); - assert (iter != lambdaMessages_.end()); - } - iter->second[index] = probability; -} - - - -double* -BpNode::getBeliefs (void) -{ - double sum = 0.0; - double* beliefs = new double [getDomainSize()]; - for (int xi = 0; xi < getDomainSize(); xi++) { - double prod = piValues_[xi] * lambdaValues_[xi]; + double sum = 0.0; + ParamSet beliefs (ds_); + for (int xi = 0; xi < ds_; xi++) { + double prod = piVals_[xi] * ldVals_[xi]; beliefs[xi] = prod; sum += prod; } - // normalize the beliefs - for (int xi = 0; xi < getDomainSize(); xi++) { + assert (sum); + //normalize the beliefs + for (int xi = 0; xi < ds_; xi++) { beliefs[xi] /= sum; } return beliefs; @@ -231,91 +49,202 @@ BpNode::getBeliefs (void) +double +BpNode::getPiValue (int idx) const +{ + assert (idx >=0 && idx < ds_); + return piVals_[idx]; +} + + + +void +BpNode::setPiValue (int idx, double value) +{ + assert (idx >=0 && idx < ds_); + piVals_[idx] = value; +} + + + +double +BpNode::getLambdaValue (int idx) const +{ + assert (idx >=0 && idx < ds_); + return ldVals_[idx]; +} + + + +void +BpNode::setLambdaValue (int idx, double value) +{ + assert (idx >=0 && idx < ds_); + ldVals_[idx] = value; +} + + + +ParamSet& +BpNode::getPiValues (void) +{ + return piVals_; +} + + + +ParamSet& +BpNode::getLambdaValues (void) +{ + return ldVals_; +} + + + +double +BpNode::getPiMessageValue (const BayesNode* destination, int idx) const +{ + assert (idx >=0 && idx < ds_); + return currPiMsgs_[getIndex(destination)][idx]; +} + + + +double +BpNode::getLambdaMessageValue (const BayesNode* source, int idx) const +{ + assert (idx >=0 && idx < ds_); + return currLdMsgs_[getIndex(source)][idx]; +} + + + +const ParamSet& +BpNode::getPiMessage (const BayesNode* destination) const +{ + return currPiMsgs_[getIndex(destination)]; +} + + + +const ParamSet& +BpNode::getLambdaMessage (const BayesNode* source) const +{ + return currLdMsgs_[getIndex(source)]; +} + + + +ParamSet& +BpNode::piNextMessageReference (const BayesNode* destination) +{ + return nextPiMsgs_[getIndex(destination)]; +} + + + +ParamSet& +BpNode::lambdaNextMessageReference (const BayesNode* source) +{ + return nextLdMsgs_[getIndex(source)]; +} + + + +void +BpNode::updatePiMessage (const BayesNode* destination) +{ + int idx = getIndex (destination); + currPiMsgs_[idx] = nextPiMsgs_[idx]; + Util::normalize (currPiMsgs_[idx]); +} + + + +void +BpNode::updateLambdaMessage (const BayesNode* source) +{ + int idx = getIndex (source); + currLdMsgs_[idx] = nextLdMsgs_[idx]; + Util::normalize (currLdMsgs_[idx]); +} + + + double BpNode::getBeliefChange (void) { double change = 0.0; - if (!oldBeliefs_) { + if (oldBeliefs_.size() == 0) { oldBeliefs_ = getBeliefs(); - change = MAX_CHANGE_; + change = 9999999999.0; } else { - double* currentBeliefs = getBeliefs(); - for (int xi = 0; xi < getDomainSize(); xi++) { + ParamSet currentBeliefs = getBeliefs(); + for (int xi = 0; xi < ds_; xi++) { change += abs (currentBeliefs[xi] - oldBeliefs_[xi]); } oldBeliefs_ = currentBeliefs; } - //FIXME memory leak return change; } void -BpNode::normalizeMessages (void) +BpNode::updatePiResidual (const BayesNode* destination) { - map::iterator iter; - - iter = lambdaMessages_.begin(); - while (iter != lambdaMessages_.end()) { - double* v = iter->second; - double sum = 0.0; - for (int xi = 0; xi < getDomainSize(); xi++) { - sum += v[xi]; - } - for (int xi = 0; xi < getDomainSize(); xi++) { - v[xi] /= sum; - } - iter ++; - } - - iter = piMessages_.begin(); - while (iter != piMessages_.end()) { - double* v = iter->second; - double sum = 0.0; - for (int xi = 0; xi < getDomainSize(); xi++) { - sum += v[xi]; - } - for (int xi = 0; xi < getDomainSize(); xi++) { - v[xi] /= sum; - } - iter ++; - } + int idx = getIndex (destination); + Util::normalize (nextPiMsgs_[idx]); + //piResiduals_[idx] = Util::getL1dist ( + // currPiMsgs_[idx], nextPiMsgs_[idx]); + piResiduals_[idx] = Util::getMaxNorm ( + currPiMsgs_[idx], nextPiMsgs_[idx]); } void -BpNode::swapMessages (void) +BpNode::updateLambdaResidual (const BayesNode* source) { - //FIXME fast way to do this - map::iterator iter1; - map::iterator iter2; - - iter1 = lambdaMessages_.begin(); - iter2 = newLambdaMessages_->begin(); - while (iter1 != lambdaMessages_.end()) { - double* v1 = iter1->second; - double* v2 = iter2->second; - for (int xi = 0; xi < getDomainSize(); xi++) { - //v1[xi] = v2[xi]; - v1[xi] = (v1[xi] + v2[xi]) / 2; - } - iter1 ++; - iter2 ++; - } - - iter1 = piMessages_.begin(); - iter2 = newPiMessages_->begin(); - while (iter1 != piMessages_.end()) { - double* v1 = iter1->second; - double* v2 = iter2->second; - for (int xi = 0; xi < getDomainSize(); xi++) { - //v1[xi] = v2[xi]; - v1[xi] = (v1[xi] + v2[xi]) / 2; - } - iter1 ++; - iter2 ++; - } + int idx = getIndex (source); + Util::normalize (nextLdMsgs_[idx]); + //ldResiduals_[idx] = Util::getL1dist ( + // currLdMsgs_[idx], nextLdMsgs_[idx]); + ldResiduals_[idx] = Util::getMaxNorm ( + currLdMsgs_[idx], nextLdMsgs_[idx]); +} + + + +void +BpNode::clearPiResidual (const BayesNode* destination) +{ + piResiduals_[getIndex(destination)] = 0; +} + + + +void +BpNode::clearLambdaResidual (const BayesNode* source) +{ + ldResiduals_[getIndex(source)] = 0; +} + + + +bool +BpNode::hasReceivedChildInfluence (void) const +{ + // if all lambda values are equal, then neither + // this node neither its descendents have evidence, + // we can use this to don't send lambda messages his parents + bool childInfluenced = false; + for (int xi = 1; xi < ds_; xi++) { + if (ldVals_[xi] != ldVals_[0]) { + childInfluenced = true; + break; + } + } + return childInfluenced; } diff --git a/packages/CLPBN/clpbn/bp/BpNode.h b/packages/CLPBN/clpbn/bp/BpNode.h index 2d796365e..2b84a298d 100644 --- a/packages/CLPBN/clpbn/bp/BpNode.h +++ b/packages/CLPBN/clpbn/bp/BpNode.h @@ -1,56 +1,99 @@ -#ifndef BP_BP_NODE_H -#define BP_BP_NODE_H +#ifndef BP_BPNODE_H +#define BP_BPNODE_H #include #include -#include #include +#include -#include "BayesianNode.h" +#include "BayesNode.h" +#include "Shared.h" using namespace std; -class BpNode : public BayesianNode +class BpNode { public: - // constructs - BpNode (string, vector, Distribution* dist, int = -1); - // destruct - ~BpNode (void); - // methods - static void enableParallelSchedule (void); - void allocateMemory (void); - double* getPiValues (void) const; - double getPiValue (int) const; - void setPiValue (int, double); - double* getLambdaValues (void) const; - double getLambdaValue (int) const; - void setLambdaValue (int, double); - double* getPiMessages (BpNode*) const; - double getPiMessage (BpNode*, int) const; - void setPiMessage (BpNode*, int, double); - double* getLambdaMessages (BpNode*) const; - double getLambdaMessage (BpNode*, int) const; - void setLambdaMessage (BpNode*, int, double); - double* getBeliefs (void); - double getBeliefChange (void); - void normalizeMessages (void); - void swapMessages (void); + BpNode (int); + BpNode (BayesNode*); + + ParamSet getBeliefs (void) const; + double getPiValue (int) const; + void setPiValue (int, double); + double getLambdaValue (int) const; + void setLambdaValue (int, double); + ParamSet& getPiValues (void); + ParamSet& getLambdaValues (void); + double getPiMessageValue (const BayesNode*, int) const; + double getLambdaMessageValue (const BayesNode*, int) const; + const ParamSet& getPiMessage (const BayesNode*) const; + const ParamSet& getLambdaMessage (const BayesNode*) const; + ParamSet& piNextMessageReference (const BayesNode*); + ParamSet& lambdaNextMessageReference (const BayesNode*); + void updatePiMessage (const BayesNode*); + void updateLambdaMessage (const BayesNode*); + double getBeliefChange (void); + void updatePiResidual (const BayesNode*); + void updateLambdaResidual (const BayesNode*); + void clearPiResidual (const BayesNode*); + void clearLambdaResidual (const BayesNode*); + bool hasReceivedChildInfluence (void) const; + // inlines + double getPiResidual (const BayesNode*); + double getLambdaResidual (const BayesNode*); + int getIndex (const BayesNode*) const; private: - BpNode (const BpNode&); // disallow copy - void operator= (const BpNode&); // disallow assign - // members - double* lambdaValues_; - double* piValues_; - map piMessages_; - map lambdaMessages_; - map* newPiMessages_; - map* newLambdaMessages_; - double* oldBeliefs_; - static bool parallelSchedule_; - static const double MAX_CHANGE_ = 1.0; + DISALLOW_COPY_AND_ASSIGN (BpNode); + + IndexMap indexMap_; + ParamSet piVals_; // pi values + ParamSet ldVals_; // lambda values + vector currPiMsgs_; // current pi messages + vector currLdMsgs_; // current lambda messages + vector nextPiMsgs_; + vector nextLdMsgs_; + ParamSet oldBeliefs_; + ParamSet piResiduals_; + ParamSet ldResiduals_; + int ds_; + const NodeSet* childs_; + static bool calculateMessageResidual_; +// static const double MAX_CHANGE_ = 10000000.0; }; -#endif // BP_BP_NODE_H + + +inline double +BpNode::getPiResidual (const BayesNode* destination) +{ + return piResiduals_[getIndex(destination)]; +} + + +inline double +BpNode::getLambdaResidual (const BayesNode* source) +{ + return ldResiduals_[getIndex(source)]; +} + + + +inline int +BpNode::getIndex (const BayesNode* node) const +{ + assert (node); + //assert (indexMap_.find(node->getVarId()) != indexMap_.end()); + //return indexMap_.find(node->getVarId())->second; + for (unsigned i = 0; childs_->size(); i++) { + if ((*childs_)[i]->getVarId() == node->getVarId()) { + return i; + } + } + assert (false); + return -1; +} + + +#endif diff --git a/packages/CLPBN/clpbn/bp/CptEntry.h b/packages/CLPBN/clpbn/bp/CptEntry.h index 7289212d7..9229b2564 100644 --- a/packages/CLPBN/clpbn/bp/CptEntry.h +++ b/packages/CLPBN/clpbn/bp/CptEntry.h @@ -1,23 +1,71 @@ -#ifndef CPT_ENTRY_H -#define CPT_ENTRY_H +#ifndef BP_CPTENTRY_H +#define BP_CPTENTRY_H #include +#include "Shared.h" + using namespace std; class CptEntry { public: - // constructs - CptEntry (int, vector); - // methods - int getCptIndex (void) const; - vector getDomainInstantiations (void) const; - bool matchConstraints (const vector >&) const; + CptEntry (unsigned, const vector&); + + unsigned getParameterIndex (void) const; + const vector& getParentConfigurations (void) const; + bool matchConstraints (const DomainConstr&) const; + bool matchConstraints (const vector&) const; + private: - // members - int cptIndex_; - vector instantiations_; + unsigned index_; + vector confs_; }; -#endif // CPT_ENTRY_H + + +inline +CptEntry::CptEntry (unsigned index, const vector& confs) +{ + index_ = index; + confs_ = confs; +} + + + +inline unsigned +CptEntry::getParameterIndex (void) const +{ + return index_; +} + + + +inline const vector& +CptEntry::getParentConfigurations (void) const +{ + return confs_; +} + + + +inline bool +CptEntry::matchConstraints (const DomainConstr& constr) const +{ + return confs_[constr.first] == constr.second; +} + + + +inline bool +CptEntry::matchConstraints (const vector& constrs) const +{ + for (unsigned j = 0; j < constrs.size(); j++) { + if (confs_[constrs[j].first] != constrs[j].second) { + return false; + } + } + return true; +} + +#endif diff --git a/packages/CLPBN/clpbn/bp/Distribution.h b/packages/CLPBN/clpbn/bp/Distribution.h index 51a540b4c..63b562be4 100644 --- a/packages/CLPBN/clpbn/bp/Distribution.h +++ b/packages/CLPBN/clpbn/bp/Distribution.h @@ -1,24 +1,40 @@ -#ifndef DISTRIBUTION_H -#define DISTRIBUTION_H +#ifndef BP_DISTRIBUTION_H +#define BP_DISTRIBUTION_H #include #include +#include "Shared.h" + using namespace std; -class CptEntry; - -class Distribution +struct Distribution { public: - Distribution (int, double*, int, vector); - Distribution (double*, int, vector); - int id; - double* params; - int nParams; - vector domain; - int* offsets; + Distribution (unsigned id) + { + this->id = id; + this->params = params; + } + + Distribution (const ParamSet& params) + { + this->id = -1; + this->params = params; + } + + void updateParameters (const ParamSet& params) + { + this->params = params; + } + + unsigned id; + ParamSet params; + vector entries; + + private: + DISALLOW_COPY_AND_ASSIGN (Distribution); }; -#endif // DISTRIBUTION +#endif diff --git a/packages/CLPBN/clpbn/bp/Factor.cpp b/packages/CLPBN/clpbn/bp/Factor.cpp new file mode 100755 index 000000000..66d2296e0 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/Factor.cpp @@ -0,0 +1,346 @@ +#include +#include +#include +#include + +#include "Factor.h" +#include "FgVarNode.h" + + +int Factor::indexCount_ = 0; + +Factor::Factor (FgVarNode* var) { + vs_.push_back (var); + int nParams = var->getDomainSize(); + // create a uniform distribution + double val = 1.0 / nParams; + ps_ = ParamSet (nParams, val); + id_ = indexCount_; + indexCount_ ++; +} + + + +Factor::Factor (const FgVarSet& vars) { + vs_ = vars; + int nParams = 1; + for (unsigned i = 0; i < vs_.size(); i++) { + nParams *= vs_[i]->getDomainSize(); + } + // create a uniform distribution + double val = 1.0 / nParams; + ps_ = ParamSet (nParams, val); + id_ = indexCount_; + indexCount_ ++; +} + + + +Factor::Factor (FgVarNode* var, + const ParamSet& params) +{ + vs_.push_back (var); + ps_ = params; + id_ = indexCount_; + indexCount_ ++; +} + + + +Factor::Factor (const FgVarSet& vars, + const ParamSet& params) +{ + vs_ = vars; + ps_ = params; + id_ = indexCount_; + indexCount_ ++; +} + + + +const FgVarSet& +Factor::getFgVarNodes (void) const +{ + return vs_; +} + + + +FgVarSet& +Factor::getFgVarNodes (void) +{ + return vs_; +} + + + +const ParamSet& +Factor::getParameters (void) const +{ + return ps_; +} + + + +ParamSet& +Factor::getParameters (void) +{ + return ps_; +} + + + +void +Factor::setParameters (const ParamSet& params) +{ + //cout << "ps size: " << ps_.size() << endl; + //cout << "params size: " << params.size() << endl; + assert (ps_.size() == params.size()); + ps_ = params; +} + + + +Factor& +Factor::operator= (const Factor& g) +{ + FgVarSet vars = g.getFgVarNodes(); + ParamSet params = g.getParameters(); + return *this; +} + + + +Factor& +Factor::operator*= (const Factor& g) +{ + FgVarSet gVs = g.getFgVarNodes(); + const ParamSet& gPs = g.getParameters(); + + bool hasCommonVars = false; + vector varIndexes; + for (unsigned i = 0; i < gVs.size(); i++) { + int idx = getIndexOf (gVs[i]); + if (idx == -1) { + insertVariable (gVs[i]); + varIndexes.push_back (vs_.size() - 1); + } else { + hasCommonVars = true; + varIndexes.push_back (idx); + } + } + + if (hasCommonVars) { + vector offsets (gVs.size()); + offsets[gVs.size() - 1] = 1; + for (int i = gVs.size() - 2; i >= 0; i--) { + offsets[i] = offsets[i + 1] * gVs[i + 1]->getDomainSize(); + } + vector entries = getCptEntries(); + for (unsigned i = 0; i < entries.size(); i++) { + int idx = 0; + const DomainConf conf = entries[i].getParentConfigurations(); + for (unsigned j = 0; j < varIndexes.size(); j++) { + idx += offsets[j] * conf[varIndexes[j]]; + } + //cout << "ps_[" << i << "] = " << ps_[i] << " * " ; + //cout << gPs[idx] << " , idx = " << idx << endl; + ps_[i] = ps_[i] * gPs[idx]; + } + } else { + // if the originally factors doesn't have common factors. + // we don't have to make domain comparations + unsigned idx = 0; + for (unsigned i = 0; i < ps_.size(); i++) { + //cout << "ps_[" << i << "] = " << ps_[i] << " * " ; + //cout << gPs[idx] << " , idx = " << idx << endl; + ps_[i] = ps_[i] * gPs[idx]; + idx ++; + if (idx >= gPs.size()) { + idx = 0; + } + } + } + return *this; +} + + + +void +Factor::insertVariable (FgVarNode* var) +{ + int c = 0; + ParamSet newPs (ps_.size() * var->getDomainSize()); + for (unsigned i = 0; i < ps_.size(); i++) { + for (int j = 0; j < var->getDomainSize(); j++) { + newPs[c] = ps_[i]; + c ++; + } + } + vs_.push_back (var); + ps_ = newPs; +} + + + +void +Factor::marginalizeVariable (const FgVarNode* var) { + int varIndex = getIndexOf (var); + marginalizeVariable (varIndex); +} + + + +void +Factor::marginalizeVariable (unsigned varIndex) +{ + assert (varIndex >= 0 && varIndex < vs_.size()); + int distOffset = 1; + int leftVarOffset = 1; + for (unsigned i = vs_.size() - 1; i > varIndex; i--) { + distOffset *= vs_[i]->getDomainSize(); + leftVarOffset *= vs_[i]->getDomainSize(); + } + leftVarOffset *= vs_[varIndex]->getDomainSize(); + + int ds = vs_[varIndex]->getDomainSize(); + int count = 0; + int offset = 0; + int startIndex = 0; + int currDomainIdx = 0; + unsigned newPsSize = ps_.size() / ds; + ParamSet newPs; + newPs.reserve (newPsSize); + + stringstream ss; + ss << "marginalizing " << vs_[varIndex]->getLabel(); + ss << " from factor " << getLabel() << endl; + while (newPs.size() < newPsSize) { + ss << " sum = "; + double sum = 0.0; + for (int j = 0; j < ds; j++) { + if (j != 0) ss << " + "; + ss << ps_[offset]; + sum = sum + ps_[offset]; + offset = offset + distOffset; + } + newPs.push_back (sum); + count ++; + if (varIndex == vs_.size() - 1) { + offset = count * ds; + } else { + offset = offset - distOffset + 1; + if ((offset % leftVarOffset) == 0) { + currDomainIdx ++; + startIndex = leftVarOffset * currDomainIdx; + offset = startIndex; + count = 0; + } else { + offset = startIndex + count; + } + } + ss << " = " << sum << endl; + } + //cout << ss.str() << endl; + ps_ = newPs; + vs_.erase (vs_.begin() + varIndex); +} + + + +string +Factor::getLabel (void) const +{ + stringstream ss; + ss << "f(" ; + // ss << "Φ(" ; + for (unsigned i = 0; i < vs_.size(); i++) { + if (i != 0) ss << ", " ; + ss << "v" << vs_[i]->getVarId(); + } + ss << ")" ; + return ss.str(); +} + + + +string +Factor::toString (void) const +{ + stringstream ss; + ss << "vars: " ; + for (unsigned i = 0; i < vs_.size(); i++) { + if (i != 0) ss << ", " ; + ss << "v" << vs_[i]->getVarId(); + } + ss << endl; + vector entries = getCptEntries(); + for (unsigned i = 0; i < entries.size(); i++) { + ss << "Φ(" ; + char s = 'a' ; + const DomainConf& conf = entries[i].getParentConfigurations(); + for (unsigned j = 0; j < conf.size(); j++) { + if (j != 0) ss << "," ; + ss << s << conf[j] + 1; + s++; + } + ss << ") = " << ps_[entries[i].getParameterIndex()] << endl; + } + return ss.str(); +} + + + +vector +Factor::getCptEntries (void) const +{ + vector confs (ps_.size()); + for (unsigned i = 0; i < ps_.size(); i++) { + confs[i].resize (vs_.size()); + } + + int nReps = 1; + for (int i = vs_.size() - 1; i >= 0; i--) { + unsigned index = 0; + while (index < ps_.size()) { + for (int j = 0; j < vs_[i]->getDomainSize(); j++) { + for (int r = 0; r < nReps; r++) { + confs[index][i] = j; + index++; + } + } + } + nReps *= vs_[i]->getDomainSize(); + } + + vector entries; + for (unsigned i = 0; i < ps_.size(); i++) { + for (unsigned j = 0; j < vs_.size(); j++) { + } + entries.push_back (CptEntry (i, confs[i])); + } + return entries; +} + + + +int +Factor::getIndexOf (const FgVarNode* var) const +{ + for (unsigned i = 0; i < vs_.size(); i++) { + if (vs_[i] == var) { + return i; + } + } + return -1; +} + + + +Factor operator* (const Factor& f, const Factor& g) +{ + Factor r = f; + r *= g; + return r; +} + diff --git a/packages/CLPBN/clpbn/bp/Factor.h b/packages/CLPBN/clpbn/bp/Factor.h new file mode 100755 index 000000000..71b14df07 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/Factor.h @@ -0,0 +1,45 @@ +#ifndef BP_FACTOR_H +#define BP_FACTOR_H + +#include + +#include "CptEntry.h" + +using namespace std; + +class FgVarNode; + +class Factor +{ + public: + Factor (FgVarNode*); + Factor (const FgVarSet&); + Factor (FgVarNode*, const ParamSet&); + Factor (const FgVarSet&, const ParamSet&); + + const FgVarSet& getFgVarNodes (void) const; + FgVarSet& getFgVarNodes (void); + const ParamSet& getParameters (void) const; + ParamSet& getParameters (void); + void setParameters (const ParamSet&); + Factor& operator= (const Factor& f); + Factor& operator*= (const Factor& f); + void insertVariable (FgVarNode* index); + void marginalizeVariable (const FgVarNode* var); + void marginalizeVariable (unsigned); + string getLabel (void) const; + string toString (void) const; + + private: + vector getCptEntries() const; + int getIndexOf (const FgVarNode*) const; + + FgVarSet vs_; + ParamSet ps_; + int id_; + static int indexCount_; +}; + +Factor operator* (const Factor&, const Factor&); + +#endif diff --git a/packages/CLPBN/clpbn/bp/FactorGraph.cpp b/packages/CLPBN/clpbn/bp/FactorGraph.cpp new file mode 100755 index 000000000..0a85d2b5b --- /dev/null +++ b/packages/CLPBN/clpbn/bp/FactorGraph.cpp @@ -0,0 +1,173 @@ +#include +#include +#include +#include +#include + +#include "FactorGraph.h" +#include "FgVarNode.h" +#include "Factor.h" + + +FactorGraph::FactorGraph (const char* fileName) +{ + string line; + ifstream is (fileName); + if (!is.is_open()) { + cerr << "error: cannot read from file " + std::string (fileName) << endl; + abort(); + } + + while (is.peek() == '#' || is.peek() == '\n') getline (is, line); + getline (is, line); + if (line != "MARKOV") { + cerr << "error: the network must be a MARKOV network " << endl; + abort(); + } + + while (is.peek() == '#' || is.peek() == '\n') getline (is, line); + int nVars; + is >> nVars; + + while (is.peek() == '#' || is.peek() == '\n') getline (is, line); + vector domainSizes (nVars); + for (int i = 0; i < nVars; i++) { + int ds; + is >> ds; + domainSizes[i] = ds; + } + + while (is.peek() == '#' || is.peek() == '\n') getline (is, line); + for (int i = 0; i < nVars; i++) { + varNodes_.push_back (new FgVarNode (i, domainSizes[i])); + } + + int nFactors; + is >> nFactors; + for (int i = 0; i < nFactors; i++) { + while (is.peek() == '#' || is.peek() == '\n') getline (is, line); + int nFactorVars; + is >> nFactorVars; + FgVarSet factorVars; + for (int j = 0; j < nFactorVars; j++) { + int varId; + is >> varId; + FgVarNode* var = getVariableById (varId); + if (var == 0) { + cerr << "error: invalid variable identifier (" << varId << ")" << endl; + abort(); + } + factorVars.push_back (var); + } + Factor* f = new Factor (factorVars); + factors_.push_back (f); + for (unsigned j = 0; j < factorVars.size(); j++) { + factorVars[j]->addFactor (f); + } + } + + for (int i = 0; i < nFactors; i++) { + while (is.peek() == '#' || is.peek() == '\n') getline (is, line); + int nParams; + is >> nParams; + ParamSet params (nParams); + for (int j = 0; j < nParams; j++) { + double param; + is >> param; + params[j] = param; + } + factors_[i]->setParameters (params); + } + is.close(); + + for (unsigned i = 0; i < varNodes_.size(); i++) { + varNodes_[i]->setIndex (i); + } +} + + + +FactorGraph::~FactorGraph (void) +{ + for (unsigned i = 0; i < varNodes_.size(); i++) { + delete varNodes_[i]; + } + for (unsigned i = 0; i < factors_.size(); i++) { + delete factors_[i]; + } +} + + + +FgVarSet +FactorGraph::getFgVarNodes (void) const +{ + return varNodes_; +} + + + +vector +FactorGraph::getFactors (void) const +{ + return factors_; +} + + + +VarSet +FactorGraph::getVariables (void) const +{ + VarSet vars; + for (unsigned i = 0; i < varNodes_.size(); i++) { + vars.push_back (varNodes_[i]); + } + return vars; +} + + + +FgVarNode* +FactorGraph::getVariableById (unsigned id) const +{ + for (unsigned i = 0; i < varNodes_.size(); i++) { + if (varNodes_[i]->getVarId() == id) { + return varNodes_[i]; + } + } + return 0; +} + + + +FgVarNode* +FactorGraph::getVariableByLabel (string label) const +{ + for (unsigned i = 0; i < varNodes_.size(); i++) { + stringstream ss; + ss << "v" << varNodes_[i]->getVarId(); + if (ss.str() == label) { + return varNodes_[i]; + } + } + return 0; +} + + + +void +FactorGraph::printFactorGraph (void) const +{ + for (unsigned i = 0; i < varNodes_.size(); i++) { + cout << "variable number " << varNodes_[i]->getIndex() << endl; + cout << "Id = " << varNodes_[i]->getVarId() << endl; + cout << "Domain size = " << varNodes_[i]->getDomainSize() << endl; + cout << "Evidence = " << varNodes_[i]->getEvidence() << endl; + cout << endl; + } + cout << endl; + for (unsigned i = 0; i < factors_.size(); i++) { + cout << factors_[i]->toString() << endl; + } +} + diff --git a/packages/CLPBN/clpbn/bp/FactorGraph.h b/packages/CLPBN/clpbn/bp/FactorGraph.h new file mode 100755 index 000000000..9809f25b8 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/FactorGraph.h @@ -0,0 +1,35 @@ +#ifndef BP_FACTORGRAPH_H +#define BP_FACTORGRAPH_H + +#include +#include + +#include "GraphicalModel.h" +#include "Shared.h" + +using namespace std; + +class FgVarNode; +class Factor; + +class FactorGraph : public GraphicalModel +{ + public: + FactorGraph (const char* fileName); + ~FactorGraph (void); + + FgVarSet getFgVarNodes (void) const; + vector getFactors (void) const; + VarSet getVariables (void) const; + FgVarNode* getVariableById (unsigned) const; + FgVarNode* getVariableByLabel (string) const; + void printFactorGraph (void) const; + + private: + DISALLOW_COPY_AND_ASSIGN (FactorGraph); + + FgVarSet varNodes_; + vector factors_; +}; + +#endif diff --git a/packages/CLPBN/clpbn/bp/FgVarNode.h b/packages/CLPBN/clpbn/bp/FgVarNode.h new file mode 100755 index 000000000..e82ab0c52 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/FgVarNode.h @@ -0,0 +1,28 @@ +#ifndef BP_VARIABLE_H +#define BP_VARIABLE_H + +#include +#include + +#include "Variable.h" +#include "Shared.h" + +using namespace std; + +class Factor; + +class FgVarNode : public Variable +{ + public: + FgVarNode (int varId, int dsize) : Variable (varId, dsize) { } + + void addFactor (Factor* f) { factors_.push_back (f); } + vector getFactors (void) const { return factors_; } + + private: + DISALLOW_COPY_AND_ASSIGN (FgVarNode); + // members + vector factors_; +}; + +#endif // BP_VARIABLE_H diff --git a/packages/CLPBN/clpbn/bp/GraphicalModel.h b/packages/CLPBN/clpbn/bp/GraphicalModel.h new file mode 100755 index 000000000..4aaf4baf3 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/GraphicalModel.h @@ -0,0 +1,17 @@ +#ifndef BP_GRAPHICALMODEL_H +#define BP_GRAPHICALMODEL_H + +#include "Variable.h" +#include "Shared.h" + +using namespace std; + +class GraphicalModel +{ + public: + virtual VarSet getVariables (void) const = 0; + + private: +}; + +#endif diff --git a/packages/CLPBN/clpbn/bp/Horus.cpp b/packages/CLPBN/clpbn/bp/Horus.cpp deleted file mode 100755 index 43770b689..000000000 --- a/packages/CLPBN/clpbn/bp/Horus.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include -#include -#include -#include - -#include - -#include -#include -#include -#include - - -using namespace std; - -int addVariables (BayesianNetwork&, YAP_Term, int); -int addDistributions (BayesianNetwork&, YAP_Term, int); - -int createNetwork (void) -{ - BayesianNetwork* bn = new BpNetwork(); - addDistributions (*bn, YAP_ARG3, (int) YAP_IntOfTerm (YAP_ARG4)); - addVariables (*bn, YAP_ARG1, (int) YAP_IntOfTerm (YAP_ARG2)); - YAP_Int p = (YAP_Int) (bn); - return YAP_Unify (YAP_MkIntTerm (p), YAP_ARG5); -} - - - -int addVariables (BayesianNetwork& bn, YAP_Term varList, int nVars) -{ - for (int i = 0; i < nVars; i++) { - YAP_Term var = YAP_HeadOfTerm (varList); - int varId = (int) YAP_IntOfTerm (YAP_ArgOfTerm (1, var)); - int distId = (int) YAP_IntOfTerm (YAP_ArgOfTerm (2, var)); - YAP_Term parentsList = YAP_ArgOfTerm (3, var); - int nParents = (int) YAP_IntOfTerm (YAP_ArgOfTerm (4, var)); - vector parents; - for (int j = 0; j < nParents; j++) { - int parentId = (int) YAP_IntOfTerm (YAP_HeadOfTerm (parentsList)); - stringstream parentName; - parentName << parentId; - parents.push_back (bn.getNode (parentName.str())); - parentsList = YAP_TailOfTerm (parentsList); - } - stringstream nodeName; - nodeName << varId; - int evidence = (int) YAP_IntOfTerm (YAP_ArgOfTerm (5, var)); - bn.addNode (nodeName.str(), parents, evidence, distId); - varList = YAP_TailOfTerm (varList); - } - return TRUE; -} - - - -int addDistributions (BayesianNetwork& bn, YAP_Term distList, int nDists) -{ - for (int i = 0; i < nDists; i++) { - YAP_Term dist = YAP_HeadOfTerm (distList); - int distId = (int) YAP_IntOfTerm (YAP_ArgOfTerm (1, dist)); - YAP_Term domainList = YAP_ArgOfTerm (2, dist); - int domainSize = (int) YAP_IntOfTerm (YAP_ArgOfTerm (3, dist)); - vector domain (domainSize); - for (int j = 0; j < domainSize; j++) { - YAP_Atom atom = YAP_AtomOfTerm (YAP_HeadOfTerm (domainList)); - domain[j] = (char*) YAP_AtomName (atom);; - domainList = YAP_TailOfTerm (domainList); - } - YAP_Term paramsList = YAP_ArgOfTerm (4, dist); - int nParams = (int) YAP_IntOfTerm (YAP_ArgOfTerm (5, dist)); - double* params = new double [nParams]; - for (int j = 0; j < nParams; j++) { - params[j] = (double) YAP_FloatOfTerm (YAP_HeadOfTerm (paramsList)); - paramsList = YAP_TailOfTerm (paramsList); - } - bn.addDistribution (distId, params, nParams, domain); - distList = YAP_TailOfTerm (distList); - } - return TRUE; -} - - - -int runSolver (void) -{ - BpNetwork* bn = (BpNetwork*) YAP_IntOfTerm (YAP_ARG1); - YAP_Term queryVarsList = YAP_ARG2; - int nQueryVars = (int) YAP_IntOfTerm (YAP_ARG3); - vector queryVars; - for (int i = 0; i < nQueryVars; i++) { - int queryVarId = (int) YAP_IntOfTerm (YAP_HeadOfTerm (queryVarsList)); - stringstream queryVarName; - queryVarName << queryVarId; - queryVars.push_back (bn->getNode (queryVarName.str())); - queryVarsList = YAP_TailOfTerm (queryVarsList); - } - bn->runSolver (queryVars); - vector beliefs = bn->getBeliefs(); - YAP_Term beliefsList = YAP_TermNil(); - for (int i = beliefs.size() - 1; i >= 0; i--) { - YAP_Term belief = YAP_MkFloatTerm (beliefs[i]); - beliefsList = YAP_MkPairTerm (belief, beliefsList); - } - return YAP_Unify (beliefsList, YAP_ARG4); -} - - - -int freeMemory (void) -{ - BpNetwork* bn = (BpNetwork*) YAP_IntOfTerm (YAP_ARG1); - delete bn; - return TRUE; -} - - - -extern "C" void init_predicates (void) -{ - YAP_UserCPredicate ("create_network", createNetwork, 5); - YAP_UserCPredicate ("run_solver", runSolver, 4); - YAP_UserCPredicate ("free_memory", freeMemory, 1); -} - diff --git a/packages/CLPBN/clpbn/bp/HorusCli.cpp b/packages/CLPBN/clpbn/bp/HorusCli.cpp new file mode 100755 index 000000000..a4619566f --- /dev/null +++ b/packages/CLPBN/clpbn/bp/HorusCli.cpp @@ -0,0 +1,214 @@ +#include +#include +#include + +#include "BayesNet.h" +#include "BPSolver.h" + +#include "FactorGraph.h" +#include "SPSolver.h" + +using namespace std; + +void BayesianNetwork (int, const char* []); +void markovNetwork (int, const char* []); + +const string USAGE = "usage: \ +./hcli FILE [VARIABLE | OBSERVED_VARIABLE=EVIDENCE]..." ; + + +int +main (int argc, const char* argv[]) +{ + if (!argv[1]) { + cerr << "error: no graphical model specified" << endl; + cerr << USAGE << endl; + exit (0); + } + string fileName = argv[1]; + string extension = fileName.substr (fileName.find_last_of ('.') + 1); + if (extension == "xml") { + BayesianNetwork (argc, argv); + } else if (extension == "uai") { + markovNetwork (argc, argv); + } else { + cerr << "error: the graphical model must be defined either " ; + cerr << "in a xml file or uai file" << endl; + exit (0); + } + return 0; +} + + + +void +BayesianNetwork (int argc, const char* argv[]) +{ + BayesNet bn (argv[1]); + //bn.printNetwork(); + + NodeSet queryVars; + for (int i = 2; i < argc; i++) { + string arg = argv[i]; + if (arg.find ('=') == std::string::npos) { + BayesNode* queryVar = bn.getNode (arg); + if (queryVar) { + queryVars.push_back (queryVar); + } else { + cerr << "error: there isn't a variable labeled of " ; + cerr << "`" << arg << "'" ; + cerr << endl; + exit (0); + } + } else { + size_t pos = arg.find ('='); + string label = arg.substr (0, pos); + string state = arg.substr (pos + 1); + if (label.empty()) { + cerr << "error: missing left argument" << endl; + cerr << USAGE << endl; + exit (0); + } + if (state.empty()) { + cerr << "error: missing right argument" << endl; + cerr << USAGE << endl; + exit (0); + } + BayesNode* node = bn.getNode (label); + if (node) { + if (node->isValidState (state)) { + node->setEvidence (state); + } else { + cerr << "error: `" << state << "' " ; + cerr << "is not a valid state for " ; + cerr << "`" << node->getLabel() << "'" ; + cerr << endl; + exit (0); + } + } else { + cerr << "error: there isn't a variable labeled of " ; + cerr << "`" << label << "'" ; + cerr << endl; + exit (0); + } + } + } + + BPSolver solver (bn); + if (queryVars.size() == 0) { + solver.runSolver(); + solver.printAllPosterioris(); + } else if (queryVars.size() == 1) { + solver.runSolver(); + solver.printPosterioriOf (queryVars[0]); + } else { + Domain domain = BayesNet::getInstantiations(queryVars); + ParamSet params = solver.getJointDistribution (queryVars); + for (unsigned i = 0; i < params.size(); i++) { + cout << domain[i] << "\t" << params[i] << endl; + } + } + bn.freeDistributions(); +} + + + +void +markovNetwork (int argc, const char* argv[]) +{ + FactorGraph fg (argv[1]); + //fg.printFactorGraph(); + + VarSet queryVars; + for (int i = 2; i < argc; i++) { + string arg = argv[i]; + if (arg.find ('=') == std::string::npos) { + if (!Util::isInteger (arg)) { + cerr << "error: `" << arg << "' " ; + cerr << "is not a valid variable id" ; + cerr << endl; + exit (0); + } + unsigned varId; + stringstream ss; + ss << arg; + ss >> varId; + Variable* queryVar = fg.getVariableById (varId); + if (queryVar) { + queryVars.push_back (queryVar); + } else { + cerr << "error: there isn't a variable with " ; + cerr << "`" << varId << "' as id" ; + cerr << endl; + exit (0); + } + } else { + size_t pos = arg.find ('='); + if (arg.substr (0, pos).empty()) { + cerr << "error: missing left argument" << endl; + cerr << USAGE << endl; + exit (0); + } + if (arg.substr (pos + 1).empty()) { + cerr << "error: missing right argument" << endl; + cerr << USAGE << endl; + exit (0); + } + if (!Util::isInteger (arg.substr (0, pos))) { + cerr << "error: `" << arg.substr (0, pos) << "' " ; + cerr << "is not a variable id" ; + cerr << endl; + exit (0); + } + unsigned varId; + stringstream ss; + ss << arg.substr (0, pos); + ss >> varId; + Variable* var = fg.getVariableById (varId); + if (var) { + if (!Util::isInteger (arg.substr (pos + 1))) { + cerr << "error: `" << arg.substr (pos + 1) << "' " ; + cerr << "is not a state index" ; + cerr << endl; + exit (0); + } + int stateIndex; + stringstream ss; + ss << arg.substr (pos + 1); + ss >> stateIndex; + cout << "si: " << stateIndex << endl; + if (var->isValidStateIndex (stateIndex)) { + var->setEvidence (stateIndex); + } else { + cerr << "error: `" << stateIndex << "' " ; + cerr << "is not a valid state index for variable " ; + cerr << "`" << var->getVarId() << "'" ; + cerr << endl; + exit (0); + } + } else { + cerr << "error: there isn't a variable with " ; + cerr << "`" << varId << "' as id" ; + cerr << endl; + exit (0); + } + } + } + + SPSolver solver (fg); + if (queryVars.size() == 0) { + solver.runSolver(); + solver.printAllPosterioris(); + } else if (queryVars.size() == 1) { + solver.runSolver(); + solver.printPosterioriOf (queryVars[0]); + } else { + assert (false); //FIXME + //Domain domain = BayesNet::getInstantiations(queryVars); + //ParamSet params = solver.getJointDistribution (queryVars); + //for (unsigned i = 0; i < params.size(); i++) { + // cout << domain[i] << "\t" << params[i] << endl; + //} + } +} + diff --git a/packages/CLPBN/clpbn/bp/HorusYap.cpp b/packages/CLPBN/clpbn/bp/HorusYap.cpp new file mode 100755 index 000000000..c4ccb8aa7 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/HorusYap.cpp @@ -0,0 +1,232 @@ +#include +#include +#include +#include +#include + +#include + +#include "callgrind.h" + +#include "BayesNet.h" +#include "BayesNode.h" +#include "BPSolver.h" + +using namespace std; + +int +createNetwork (void) +{ + Statistics::numCreatedNets ++; + cout << "creating network number " << Statistics::numCreatedNets << endl; + if (Statistics::numCreatedNets == 1) { + //CALLGRIND_START_INSTRUMENTATION; + } + BayesNet* bn = new BayesNet(); + + YAP_Term varList = YAP_ARG1; + while (varList != YAP_TermNil()) { + YAP_Term var = YAP_HeadOfTerm (varList); + unsigned varId = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (1, var)); + unsigned dsize = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (2, var)); + int evidence = (int) YAP_IntOfTerm (YAP_ArgOfTerm (3, var)); + YAP_Term parentL = YAP_ArgOfTerm (4, var); + unsigned distId = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (5, var)); + NodeSet parents; + while (parentL != YAP_TermNil()) { + unsigned parentId = (unsigned) YAP_IntOfTerm (YAP_HeadOfTerm (parentL)); + BayesNode* parent = bn->getNode (parentId); + if (!parent) { + parent = bn->addNode (parentId); + } + parents.push_back (parent); + parentL = YAP_TailOfTerm (parentL); + } + Distribution* dist = bn->getDistribution (distId); + if (!dist) { + dist = new Distribution (distId); + bn->addDistribution (dist); + } + BayesNode* node = bn->getNode (varId); + if (node) { + node->setData (dsize, evidence, parents, dist); + } else { + bn->addNode (varId, dsize, evidence, parents, dist); + } + varList = YAP_TailOfTerm (varList); + } + bn->setIndexes(); + + if (Statistics::numCreatedNets == 1688) { + Statistics::writeStats(); + //Statistics::writeStats(); + //CALLGRIND_STOP_INSTRUMENTATION; + //CALLGRIND_DUMP_STATS; + //exit (0); + } + YAP_Int p = (YAP_Int) (bn); + return YAP_Unify (YAP_MkIntTerm (p), YAP_ARG2); +} + + + +int +setExtraVarsInfo (void) +{ + BayesNet* bn = (BayesNet*) YAP_IntOfTerm (YAP_ARG1); + YAP_Term varsInfoL = YAP_ARG2; + while (varsInfoL != YAP_TermNil()) { + YAP_Term head = YAP_HeadOfTerm (varsInfoL); + unsigned varId = YAP_IntOfTerm (YAP_ArgOfTerm (1, head)); + YAP_Atom label = YAP_AtomOfTerm (YAP_ArgOfTerm (2, head)); + YAP_Term domainL = YAP_ArgOfTerm (3, head); + Domain domain; + while (domainL != YAP_TermNil()) { + YAP_Atom atom = YAP_AtomOfTerm (YAP_HeadOfTerm (domainL)); + domain.push_back ((char*) YAP_AtomName (atom)); + domainL = YAP_TailOfTerm (domainL); + } + BayesNode* node = bn->getNode (varId); + assert (node); + node->setLabel ((char*) YAP_AtomName (label)); + node->setDomain (domain); + varsInfoL = YAP_TailOfTerm (varsInfoL); + } + return TRUE; +} + + + +int +setParameters (void) +{ + BayesNet* bn = (BayesNet*) YAP_IntOfTerm (YAP_ARG1); + YAP_Term distList = YAP_ARG2; + while (distList != YAP_TermNil()) { + YAP_Term dist = YAP_HeadOfTerm (distList); + unsigned distId = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (1, dist)); + YAP_Term paramL = YAP_ArgOfTerm (2, dist); + ParamSet params; + while (paramL!= YAP_TermNil()) { + params.push_back ((double) YAP_FloatOfTerm (YAP_HeadOfTerm (paramL))); + paramL = YAP_TailOfTerm (paramL); + } + bn->getDistribution(distId)->updateParameters(params); + distList = YAP_TailOfTerm (distList); + } + return TRUE; +} + + + +int +runSolver (void) +{ + BayesNet* bn = (BayesNet*) YAP_IntOfTerm (YAP_ARG1); + YAP_Term taskList = YAP_ARG2; + + vector tasks; + NodeSet marginalVars; + + while (taskList != YAP_TermNil()) { + if (YAP_IsPairTerm (YAP_HeadOfTerm (taskList))) { + NodeSet jointVars; + YAP_Term jointList = YAP_HeadOfTerm (taskList); + while (jointList != YAP_TermNil()) { + unsigned varId = (unsigned) YAP_IntOfTerm (YAP_HeadOfTerm (jointList)); + assert (bn->getNode (varId)); + jointVars.push_back (bn->getNode (varId)); + jointList = YAP_TailOfTerm (jointList); + } + tasks.push_back (jointVars); + } else { + unsigned varId = (unsigned) YAP_IntOfTerm (YAP_HeadOfTerm (taskList)); + BayesNode* node = bn->getNode (varId); + assert (node); + tasks.push_back (NodeSet() = {node}); + marginalVars.push_back (node); + } + taskList = YAP_TailOfTerm (taskList); + } + /* + cout << "tasks to resolve:" << endl; + for (unsigned i = 0; i < tasks.size(); i++) { + cout << "i" << ": " ; + if (tasks[i].size() == 1) { + cout << tasks[i][0]->getVarId() << endl; + } else { + for (unsigned j = 0; j < tasks[i].size(); j++) { + cout << tasks[i][j]->getVarId() << " " ; + } + cout << endl; + } + } + */ + + cerr << "prunning now..." << endl; + BayesNet* prunedNet = bn->pruneNetwork (marginalVars); + bn->printNetworkToFile ("net.txt"); + BPSolver solver (*prunedNet); + cerr << "solving marginals now..." << endl; + solver.runSolver(); + cerr << "calculating joints now ..." << endl; + + vector results; + results.reserve (tasks.size()); + for (unsigned i = 0; i < tasks.size(); i++) { + if (tasks[i].size() == 1) { + BayesNode* node = prunedNet->getNode (tasks[i][0]->getVarId()); + results.push_back (solver.getPosterioriOf (node)); + } else { + BPSolver solver2 (*bn); + cout << "calculating an join dist on: " ; + for (unsigned j = 0; j < tasks[i].size(); j++) { + cout << tasks[i][j]->getVarId() << " " ; + } + cout << "..." << endl; + results.push_back (solver2.getJointDistribution (tasks[i])); + } + } + + delete prunedNet; + + YAP_Term list = YAP_TermNil(); + for (int i = results.size() - 1; i >= 0; i--) { + const ParamSet& beliefs = results[i]; + YAP_Term queryBeliefsL = YAP_TermNil(); + for (int j = beliefs.size() - 1; j >= 0; j--) { + YAP_Int sl1 = YAP_InitSlot(list); + YAP_Term belief = YAP_MkFloatTerm (beliefs[j]); + queryBeliefsL = YAP_MkPairTerm (belief, queryBeliefsL); + list = YAP_GetFromSlot(sl1); + YAP_RecoverSlots(1); + } + list = YAP_MkPairTerm (queryBeliefsL, list); + } + + return YAP_Unify (list, YAP_ARG3); +} + + + +int +deleteBayesNet (void) +{ + BayesNet* bn = (BayesNet*) YAP_IntOfTerm (YAP_ARG1); + bn->freeDistributions(); + delete bn; + return TRUE; +} + + + +extern "C" void +init_predicates (void) +{ + YAP_UserCPredicate ("create_network", createNetwork, 2); + YAP_UserCPredicate ("set_extra_vars_info", setExtraVarsInfo, 2); + YAP_UserCPredicate ("set_parameters", setParameters, 2); + YAP_UserCPredicate ("run_solver", runSolver, 3); + YAP_UserCPredicate ("delete_bayes_net", deleteBayesNet, 1); +} + diff --git a/packages/CLPBN/clpbn/bp/Makefile.in b/packages/CLPBN/clpbn/bp/Makefile.in index 201e1e76b..10f192755 100755 --- a/packages/CLPBN/clpbn/bp/Makefile.in +++ b/packages/CLPBN/clpbn/bp/Makefile.in @@ -21,7 +21,17 @@ YAPLIBDIR=@libdir@/Yap # CC=@CC@ CXX=@CXX@ -CXXFLAGS= @SHLIB_CXXFLAGS@ $(YAP_EXTRAS) $(DEFS) -D_YAP_NOT_INSTALLED_=1 -I$(srcdir) -I../../../.. -I$(srcdir)/../../../../include @CPPFLAGS@ + +# normal +CXXFLAGS= -std=c++0x @SHLIB_CXXFLAGS@ $(YAP_EXTRAS) $(DEFS) -D_YAP_NOT_INSTALLED_=1 -I$(srcdir) -I../../../.. -I$(srcdir)/../../../../include @CPPFLAGS@ -DNDEBUG + +# debug +#CXXFLAGS= -std=c++0x @SHLIB_CXXFLAGS@ $(YAP_EXTRAS) $(DEFS) -D_YAP_NOT_INSTALLED_=1 -I$(srcdir) -I../../../.. -I$(srcdir)/../../../../include @CPPFLAGS@ -g -O0 + +# profiling (callgrind) +#CXXFLAGS= -std=c++0x @SHLIB_CXXFLAGS@ $(YAP_EXTRAS) $(DEFS) -D_YAP_NOT_INSTALLED_=1 -I$(srcdir) -I../../../.. -I$(srcdir)/../../../../include @CPPFLAGS@ -g -DNDEBUG + + # # # You shouldn't need to change what follows. @@ -38,64 +48,75 @@ CWD=$(PWD) HEADERS = \ - $(srcdir)/BayesianNetwork.h \ - $(srcdir)/BayesianNode.h \ - $(srcdir)/BpNetwork.h \ - $(srcdir)/BpNode.h \ + $(srcdir)/GraphicalModel.h \ + $(srcdir)/Variable.h \ + $(srcdir)/BayesNet.h \ + $(srcdir)/BayesNode.h \ $(srcdir)/Distribution.h \ $(srcdir)/CptEntry.h \ - $(srcdir)/BifInterface.h \ + $(srcdir)/FactorGraph.h \ + $(srcdir)/FgVarNode.h \ + $(srcdir)/Factor.h \ + $(srcdir)/Solver.h \ + $(srcdir)/BPSolver.h \ + $(srcdir)/BpNode.h \ + $(srcdir)/SPSolver.h \ + $(srcdir)/Shared.h \ $(srcdir)/xmlParser/xmlParser.h - + CPP_SOURCES = \ - $(srcdir)/BayesianNetwork.cpp \ - $(srcdir)/BayesianNode.cpp \ - $(srcdir)/BpNetwork.cpp \ + $(srcdir)/BayesNet.cpp \ + $(srcdir)/BayesNode.cpp \ + $(srcdir)/FactorGraph.cpp \ + $(srcdir)/Factor.cpp \ + $(srcdir)/BPSolver.cpp \ $(srcdir)/BpNode.cpp \ - $(srcdir)/Distribution.cpp \ - $(srcdir)/CptEntry.cpp \ - $(srcdir)/Horus.cpp \ - $(srcdir)/BifInterface.cpp \ - $(srcdir)/BifTest.cpp \ + $(srcdir)/SPSolver.cpp \ + $(srcdir)/HorusYap.cpp \ + $(srcdir)/HorusCli.cpp \ $(srcdir)/xmlParser/xmlParser.cpp OBJS = \ - BayesianNetwork.o \ - BayesianNode.o \ - BpNetwork.o \ + BayesNet.o \ + BayesNode.o \ + FactorGraph.o \ + Factor.o \ + BPSolver.o \ BpNode.o \ - Distribution.o \ - CptEntry.o \ - Horus.o + SPSolver.o \ + HorusYap.o -BIF_OBJS = \ - BayesianNetwork.o \ - BayesianNode.o \ - BpNetwork.o \ - BpNode.o \ - Distribution.o \ - CptEntry.o \ - BifInterface.o \ - BifTest.o \ - xmlParser.o +HCLI_OBJS = \ + BayesNet.o \ + BayesNode.o \ + FactorGraph.o \ + Factor.o \ + BPSolver.o \ + BpNode.o \ + SPSolver.o \ + HorusCli.o \ + xmlParser.o SOBJS=horus.@SO@ -all: $(SOBJS) biftest +all: $(SOBJS) hcli # default rule +%.o : $(srcdir)/%.cpp + $(CXX) -c $(CXXFLAGS) $< -o $@ + + xmlParser.o : $(srcdir)/xmlParser/xmlParser.cpp $(CXX) -c $(CXXFLAGS) $< -o $@ -%.o : $(srcdir)/%.cpp - $(CXX) -c $(CXXFLAGS) $< -o $@ @DO_SECOND_LD@horus.@SO@: $(OBJS) @DO_SECOND_LD@ @SHLIB_CXX_LD@ -o horus.@SO@ $(OBJS) @EXTRA_LIBS_FOR_SWIDLLS@ -biftest: $(BIF_OBJS) - $(CXX) -o biftest $(BIF_OBJS) + +hcli: $(HCLI_OBJS) + $(CXX) -o hcli $(HCLI_OBJS) install: all @@ -103,12 +124,12 @@ install: all clean: - rm -f *.o *~ $(OBJS) $(SOBJS) *.BAK biftest xmlParser/*.o + rm -f *.o *~ $(OBJS) $(SOBJS) *.BAK hcli xmlParser/*.o depend: $(HEADERS) $(CPP_SOURCES) -@if test "$(GCC)" = yes; then\ - $(CC) -MM -MG $(CFLAGS) -I$(srcdir) -I$(srcdir)/../../../../include -I$(srcdir)/../../../../H $(CPP_SOURCES) >> Makefile;\ + $(CC) -std=c++0x -MM -MG $(CFLAGS) -I$(srcdir) -I$(srcdir)/../../../../include -I$(srcdir)/../../../../H $(CPP_SOURCES) >> Makefile;\ else\ makedepend -f - -- $(CFLAGS) -I$(srcdir)/../../../../H -I$(srcdir)/../../../../include -- $(CPP_SOURCES) |\ sed 's|.*/\([^:]*\):|\1:|' >> Makefile ;\ diff --git a/packages/CLPBN/clpbn/bp/SPSolver.cpp b/packages/CLPBN/clpbn/bp/SPSolver.cpp new file mode 100755 index 000000000..fe0ea1e69 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/SPSolver.cpp @@ -0,0 +1,295 @@ +#include +#include +#include + +#include "SPSolver.h" +#include "FactorGraph.h" +#include "FgVarNode.h" +#include "Factor.h" + +SPSolver* Link::klass = 0; + + +SPSolver::SPSolver (const FactorGraph& fg) : Solver (&fg) +{ + fg_ = &fg; + accuracy_ = 0.0001; + maxIter_ = 10000; + //schedule_ = S_SEQ_FIXED; + //schedule_ = S_SEQ_RANDOM; + //schedule_ = S_SEQ_PARALLEL; + schedule_ = S_MAX_RESIDUAL; + Link::klass = this; + FgVarSet vars = fg_->getFgVarNodes(); + for (unsigned i = 0; i < vars.size(); i++) { + msgs_.push_back (new MessageBanket (vars[i])); + } +} + + + +SPSolver::~SPSolver (void) +{ + for (unsigned i = 0; i < msgs_.size(); i++) { + delete msgs_[i]; + } +} + + + +void +SPSolver::runSolver (void) +{ + nIter_ = 0; + vector factors = fg_->getFactors(); + for (unsigned i = 0; i < factors.size(); i++) { + FgVarSet neighbors = factors[i]->getFgVarNodes(); + for (unsigned j = 0; j < neighbors.size(); j++) { + updateOrder_.push_back (Link (factors[i], neighbors[j])); + } + } + + while (!converged() && nIter_ < maxIter_) { + if (DL >= 1) { + cout << endl; + cout << "****************************************" ; + cout << "****************************************" ; + cout << endl; + cout << " Iteration " << nIter_ + 1 << endl; + cout << "****************************************" ; + cout << "****************************************" ; + cout << endl; + } + + switch (schedule_) { + + case S_SEQ_RANDOM: + random_shuffle (updateOrder_.begin(), updateOrder_.end()); + // no break + + case S_SEQ_FIXED: + for (unsigned c = 0; c < updateOrder_.size(); c++) { + Link& link = updateOrder_[c]; + calculateNextMessage (link.source, link.destination); + updateMessage (updateOrder_[c]); + } + break; + + case S_PARALLEL: + for (unsigned c = 0; c < updateOrder_.size(); c++) { + Link link = updateOrder_[c]; + calculateNextMessage (link.source, link.destination); + } + for (unsigned c = 0; c < updateOrder_.size(); c++) { + Link link = updateOrder_[c]; + updateMessage (updateOrder_[c]); + } + break; + + case S_MAX_RESIDUAL: + maxResidualSchedule(); + break; + } + + nIter_++; + } + cout << endl; + if (DL >= 1) { + if (nIter_ < maxIter_) { + cout << "Loopy Sum-Product converged in " ; + cout << nIter_ << " iterations" << endl; + } else { + cout << "The maximum number of iterations was hit, terminating..." ; + cout << endl; + } + } +} + + + +ParamSet +SPSolver::getPosterioriOf (const Variable* var) const +{ + assert (var); + assert (var == fg_->getVariableById (var->getVarId())); + assert (var->getIndex() < msgs_.size()); + + ParamSet probs (var->getDomainSize(), 1); + if (var->hasEvidence()) { + for (unsigned i = 0; i < probs.size(); i++) { + if ((int)i != var->getEvidence()) { + probs[i] = 0; + } + } + + } else { + + MessageBanket* mb = msgs_[var->getIndex()]; + const FgVarNode* varNode = fg_->getFgVarNodes()[var->getIndex()]; + vector neighbors = varNode->getFactors(); + for (unsigned i = 0; i < neighbors.size(); i++) { + const Message& msg = mb->getMessage (neighbors[i]); + for (unsigned j = 0; j < msg.size(); j++) { + probs[j] *= msg[j]; + } + } + Util::normalize (probs); + } + + return probs; +} + + + +bool +SPSolver::converged (void) +{ + if (nIter_ == 0 || nIter_ == 1) { + return false; + } + bool converged = true; + for (unsigned i = 0; i < updateOrder_.size(); i++) { + double residual = getResidual (updateOrder_[i]); + if (DL >= 1) { + cout << updateOrder_[i].toString(); + cout << " residual = " << residual << endl; + } + if (residual > accuracy_) { + converged = false; + if (DL == 0) { + break; + } + } + } + return converged; +} + + + +void +SPSolver::maxResidualSchedule (void) +{ + if (nIter_ == 0) { + for (unsigned c = 0; c < updateOrder_.size(); c++) { + Link& l = updateOrder_[c]; + calculateNextMessage (l.source, l.destination); + if (DL >= 1) { + cout << updateOrder_[c].toString() << " residual = " ; + cout << getResidual (updateOrder_[c]) << endl; + } + } + sort (updateOrder_.begin(), updateOrder_.end(), compareResidual); + } else { + + for (unsigned c = 0; c < updateOrder_.size(); c++) { + Link& link = updateOrder_.front(); + updateMessage (link); + resetResidual (link); + + // update the messages that depend on message source --> destination + vector fstLevelNeighbors = link.destination->getFactors(); + for (unsigned i = 0; i < fstLevelNeighbors.size(); i++) { + if (fstLevelNeighbors[i] != link.source) { + FgVarSet sndLevelNeighbors; + sndLevelNeighbors = fstLevelNeighbors[i]->getFgVarNodes(); + for (unsigned j = 0; j < sndLevelNeighbors.size(); j++) { + if (sndLevelNeighbors[j] != link.destination) { + calculateNextMessage (fstLevelNeighbors[i], sndLevelNeighbors[j]); + } + } + } + } + sort (updateOrder_.begin(), updateOrder_.end(), compareResidual); + } + } +} + + + +void +SPSolver::updateMessage (const Link& link) +{ + updateMessage (link.source, link.destination); +} + + + +void +SPSolver::updateMessage (const Factor* src, const FgVarNode* dest) +{ + msgs_[dest->getIndex()]->updateMessage (src); +/* cout << src->getLabel() << " --> " << dest->getLabel() << endl; + cout << " m: " ; + Message msg = msgs_[dest->getIndex()]->getMessage (src); + for (unsigned i = 0; i < msg.size(); i++) { + if (i != 0) cout << ", " ; + cout << msg[i]; + } + cout << endl; +*/ +} + + + +void +SPSolver::calculateNextMessage (const Link& link) +{ + calculateNextMessage (link.source, link.destination); +} + + +void +SPSolver::calculateNextMessage (const Factor* src, const FgVarNode* dest) +{ + FgVarSet neighbors = src->getFgVarNodes(); + // calculate the product of MessageBankets sended + // to factor `src', except from var `dest' + Factor result = *src; + for (unsigned i = 0; i < neighbors.size(); i++) { + if (neighbors[i] != dest) { + Message msg (neighbors[i]->getDomainSize(), 1); + calculateVarFactorMessage (neighbors[i], src, msg); + result *= Factor (neighbors[i], msg); + } + } + // marginalize all vars except `dest' + for (unsigned i = 0; i < neighbors.size(); i++) { + if (neighbors[i] != dest) { + result.marginalizeVariable (neighbors[i]); + } + } + msgs_[dest->getIndex()]->setNextMessage (src, result.getParameters()); +} + + + +void +SPSolver::calculateVarFactorMessage (const FgVarNode* src, + const Factor* dest, + Message& placeholder) const +{ + assert (src->getDomainSize() == (int)placeholder.size()); + if (src->hasEvidence()) { + for (unsigned i = 0; i < placeholder.size(); i++) { + if ((int)i != src->getEvidence()) { + placeholder[i] = 0.0; + } else { + placeholder[i] = 1.0; + } + } + + } else { + + MessageBanket* mb = msgs_[src->getIndex()]; + vector neighbors = src->getFactors(); + for (unsigned i = 0; i < neighbors.size(); i++) { + if (neighbors[i] != dest) { + const Message& fromFactor = mb->getMessage (neighbors[i]); + for (unsigned j = 0; j < fromFactor.size(); j++) { + placeholder[j] *= fromFactor[j]; + } + } + } + } +} + diff --git a/packages/CLPBN/clpbn/bp/SPSolver.h b/packages/CLPBN/clpbn/bp/SPSolver.h new file mode 100755 index 000000000..421172166 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/SPSolver.h @@ -0,0 +1,171 @@ +#ifndef BP_SPSOLVER_H +#define BP_SPSOLVER_H + +#include +#include +#include +#include + +#include "Solver.h" +#include "FgVarNode.h" +#include "Factor.h" + +using namespace std; + +class FactorGraph; +class SPSolver; + +struct Link +{ + Link (Factor* s, FgVarNode* d) + { + source = s; + destination = d; + } + string toString (void) const + { + stringstream ss; + ss << source->getLabel() << " --> " ; + ss << destination->getLabel(); + return ss.str(); + } + Factor* source; + FgVarNode* destination; + static SPSolver* klass; +}; + + + +class MessageBanket +{ + public: + MessageBanket (const FgVarNode* var) + { + vector sources = var->getFactors(); + for (unsigned i = 0; i < sources.size(); i++) { + indexMap_.insert (make_pair (sources[i], i)); + currMsgs_.push_back (Message(var->getDomainSize(), 1)); + nextMsgs_.push_back (Message(var->getDomainSize(), -10)); + residuals_.push_back (0.0); + } + } + + void updateMessage (const Factor* source) + { + unsigned idx = getIndex(source); + currMsgs_[idx] = nextMsgs_[idx]; + } + + void setNextMessage (const Factor* source, const Message& msg) + { + unsigned idx = getIndex(source); + nextMsgs_[idx] = msg; + residuals_[idx] = computeResidual (source); + } + + const Message& getMessage (const Factor* source) const + { + return currMsgs_[getIndex(source)]; + } + + double getResidual (const Factor* source) const + { + return residuals_[getIndex(source)]; + } + + void resetResidual (const Factor* source) + { + residuals_[getIndex(source)] = 0.0; + } + + private: + double computeResidual (const Factor* source) + { + double change = 0.0; + unsigned idx = getIndex (source); + const Message& currMessage = currMsgs_[idx]; + const Message& nextMessage = nextMsgs_[idx]; + for (unsigned i = 0; i < currMessage.size(); i++) { + change += abs (currMessage[i] - nextMessage[i]); + } + return change; + } + + unsigned getIndex (const Factor* factor) const + { + assert (factor); + assert (indexMap_.find(factor) != indexMap_.end()); + return indexMap_.find(factor)->second; + } + + typedef map IndexMap; + + IndexMap indexMap_; + vector currMsgs_; + vector nextMsgs_; + vector residuals_; +}; + + + +class SPSolver : public Solver +{ + public: + SPSolver (const FactorGraph&); + ~SPSolver (void); + + void runSolver (void); + ParamSet getPosterioriOf (const Variable* var) const; + + private: + bool converged (void); + void maxResidualSchedule (void); + void updateMessage (const Link&); + void updateMessage (const Factor*, const FgVarNode*); + void calculateNextMessage (const Link&); + void calculateNextMessage (const Factor*, const FgVarNode*); + void calculateVarFactorMessage ( + const FgVarNode*, const Factor*, Message&) const; + double getResidual (const Link&) const; + void resetResidual (const Link&) const; + friend bool compareResidual (const Link&, const Link&); + + const FactorGraph* fg_; + vector msgs_; + Schedule schedule_; + int nIter_; + double accuracy_; + int maxIter_; + vector updateOrder_; +}; + + + +inline double +SPSolver::getResidual (const Link& link) const +{ + MessageBanket* mb = Link::klass->msgs_[link.destination->getIndex()]; + return mb->getResidual (link.source); +} + + + +inline void +SPSolver::resetResidual (const Link& link) const +{ + MessageBanket* mb = Link::klass->msgs_[link.destination->getIndex()]; + mb->resetResidual (link.source); +} + + + +inline bool +compareResidual (const Link& link1, const Link& link2) +{ + MessageBanket* mb1 = Link::klass->msgs_[link1.destination->getIndex()]; + MessageBanket* mb2 = Link::klass->msgs_[link2.destination->getIndex()]; + return mb1->getResidual(link1.source) > mb2->getResidual(link2.source); +} + +#endif + diff --git a/packages/CLPBN/clpbn/bp/Shared.h b/packages/CLPBN/clpbn/bp/Shared.h new file mode 100755 index 000000000..82afd3e51 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/Shared.h @@ -0,0 +1,203 @@ +#ifndef BP_SHARED_H +#define BP_SHARED_H + +#include +#include +#include +#include +#include +#include +#include + +// Macro to disallow the copy constructor and operator= functions +#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&); \ + void operator=(const TypeName&) + +using namespace std; + +class Variable; +class BayesNode; +class FgVarNode; + +typedef double Param; +typedef vector ParamSet; +typedef vector Message; +typedef vector VarSet; +typedef vector NodeSet; +typedef vector FgVarSet; +typedef vector Domain; +typedef vector DomainConf; +typedef pair DomainConstr; +typedef unordered_map IndexMap; + + +//extern unsigned DL; +static const unsigned DL = 0; + +// number of digits to show when printing a parameter +static const unsigned PRECISION = 10; + +// shared by bp and sp solver +enum Schedule +{ + S_SEQ_FIXED, + S_SEQ_RANDOM, + S_PARALLEL, + S_MAX_RESIDUAL +}; + + +struct NetInfo +{ + NetInfo (unsigned c, double t) + { + counting = c; + solvingTime = t; + } + unsigned counting; + double solvingTime; +}; + +typedef map StatisticMap; + + +class Statistics +{ + public: + + static void updateStats (unsigned size, double time) + { + StatisticMap::iterator it = stats_.find(size); + if (it == stats_.end()) { + stats_.insert (make_pair (size, NetInfo (1, 0.0))); + } else { + it->second.counting ++; + it->second.solvingTime += time; + } + } + + static unsigned getCounting (unsigned size) + { + StatisticMap::iterator it = stats_.find(size); + assert (it != stats_.end()); + return it->second.counting; + } + + static void updateIterations (unsigned nIters) + { + totalOfIterations += nIters; + if (nIters > maxIterations) { + maxIterations = nIters; + } + } + + static void writeStats (void) + { + ofstream out ("../../stats.txt"); + if (!out.is_open()) { + cerr << "error: cannot open file to write at " ; + cerr << "Statistics:::updateStats()" << endl; + abort(); + } + unsigned avgIterations = 0; + if (numSolvedLoopyNets > 0) { + avgIterations = totalOfIterations / numSolvedLoopyNets; + } + double totalSolvingTime = 0.0; + for (StatisticMap::iterator it = stats_.begin(); + it != stats_.end(); it++) { + totalSolvingTime += it->second.solvingTime; + } + out << "created networks: " << numCreatedNets << endl; + out << "solver runs on polytrees: " << numSolvedPolyTrees << endl; + out << "solver runs on loopy networks: " << numSolvedLoopyNets << endl; + out << " unconverged: " << numUnconvergedRuns << endl; + out << " max iterations: " << maxIterations << endl; + out << " average iterations: " << avgIterations << endl; + out << "total solving time " << totalSolvingTime << endl; + out << endl; + out << "Network Size\tCounting\tSolving Time\tAverage Time" << endl; + for (StatisticMap::iterator it = stats_.begin(); + it != stats_.end(); it++) { + out << it->first; + out << "\t\t" << it->second.counting; + out << "\t\t" << it->second.solvingTime; + if (it->second.counting > 0) { + out << "\t\t" << it->second.solvingTime / it->second.counting; + } else { + out << "\t\t0.0" ; + } + out << endl; + } + out.close(); + } + + static unsigned numCreatedNets; + static unsigned numSolvedPolyTrees; + static unsigned numSolvedLoopyNets; + static unsigned numUnconvergedRuns; + + private: + static StatisticMap stats_; + static unsigned maxIterations; + static unsigned totalOfIterations; + +}; + + + +class Util +{ + public: + static void normalize (ParamSet& v) + { + double sum = 0.0; + for (unsigned i = 0; i < v.size(); i++) { + sum += v[i]; + } + assert (sum != 0.0); + for (unsigned i = 0; i < v.size(); i++) { + v[i] /= sum; + } + } + + static double getL1dist (const ParamSet& v1, const ParamSet& v2) + { + assert (v1.size() == v2.size()); + double dist = 0.0; + for (unsigned i = 0; i < v1.size(); i++) { + dist += abs (v1[i] - v2[i]); + } + return dist; + } + + static double getMaxNorm (const ParamSet& v1, const ParamSet& v2) + { + assert (v1.size() == v2.size()); + double max = 0.0; + for (unsigned i = 0; i < v1.size(); i++) { + double diff = abs (v1[i] - v2[i]); + if (diff > max) { + max = diff; + } + } + return max; + } + + static bool isInteger (const string& s) + { + stringstream ss1 (s); + stringstream ss2; + int integer; + ss1 >> integer; + ss2 << integer; + return (ss1.str() == ss2.str()); + } +}; + + +//unsigned Statistics::totalOfIterations = 0; + +#endif + diff --git a/packages/CLPBN/clpbn/bp/Solver.h b/packages/CLPBN/clpbn/bp/Solver.h new file mode 100644 index 000000000..483986278 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/Solver.h @@ -0,0 +1,50 @@ +#ifndef BP_SOLVER_H +#define BP_SOLVER_H + +#include + +#include "GraphicalModel.h" +#include "Variable.h" + +using namespace std; + +class Solver +{ + public: + Solver (const GraphicalModel* gm) + { + gm_ = gm; + } + virtual void runSolver (void) = 0; + virtual ParamSet getPosterioriOf (const Variable*) const = 0; + + void printPosterioriOf (const Variable* var) const + { + cout << endl; + cout << setw (20) << left << var->getLabel() << "posteriori" ; + cout << endl; + cout << "------------------------------" ; + cout << endl; + const Domain& domain = var->getDomain(); + ParamSet results = getPosterioriOf (var); + for (int xi = 0; xi < var->getDomainSize(); xi++) { + cout << setw (20) << domain[xi]; + cout << setprecision (PRECISION) << results[xi]; + cout << endl; + } + cout << endl; + } + + void printAllPosterioris (void) const + { + VarSet vars = gm_->getVariables(); + for (unsigned i = 0; i < vars.size(); i++) { + printPosterioriOf (vars[i]); + } + } + + private: + const GraphicalModel* gm_; +}; + +#endif diff --git a/packages/CLPBN/clpbn/bp/Variable.h b/packages/CLPBN/clpbn/bp/Variable.h new file mode 100755 index 000000000..63f3edcbc --- /dev/null +++ b/packages/CLPBN/clpbn/bp/Variable.h @@ -0,0 +1,143 @@ +#ifndef BP_GENERIC_VARIABLE_H +#define BP_GENERIC_VARIABLE_H + +#include + +#include +#include "Shared.h" + +using namespace std; + +class Variable +{ + public: + + Variable (unsigned varId) + { + this->varId_ = varId; + this->dsize_ = 0; + this->evidence_ = -1; + this->label_ = 0; + } + + Variable (unsigned varId, unsigned dsize, int evidence = -1) + { + assert (dsize != 0); + assert (evidence < (int)dsize); + this->varId_ = varId; + this->dsize_ = dsize; + this->evidence_ = evidence; + this->label_ = 0; + } + + Variable (unsigned varId, const Domain& domain, int evidence = -1) + { + assert (!domain.empty()); + assert (evidence < (int)domain.size()); + this->varId_ = varId; + this->dsize_ = domain.size(); + this->domain_ = domain; + this->evidence_ = evidence; + this->label_ = 0; + } + + ~Variable (void) + { + delete label_; + } + + unsigned getVarId (void) const { return varId_; } + unsigned getIndex (void) const { return index_; } + void setIndex (unsigned idx) { index_ = idx; } + int getDomainSize (void) const { return dsize_; } + bool hasEvidence (void) const { return evidence_ != -1; } + int getEvidence (void) const { return evidence_; } + bool hasDomain (void) { return !domain_.empty(); } + bool hasLabel (void) { return label_ != 0; } + + bool isValidStateIndex (int index) + { + return index >= 0 && index < dsize_; + } + + bool isValidState (const string& state) + { + return find (domain_.begin(), domain_.end(), state) != domain_.end(); + } + + Domain getDomain (void) const + { + assert (dsize_ != 0); + if (domain_.size() == 0) { + Domain d; + for (int i = 0; i < dsize_; i++) { + stringstream ss; + ss << "x" << i ; + d.push_back (ss.str()); + } + return d; + } else { + return domain_; + } + } + + void setDomainSize (unsigned dsize) + { + assert (dsize != 0); + dsize_ = dsize; + } + + void setDomain (const Domain& domain) + { + assert (!domain.empty()); + domain_ = domain; + dsize_ = domain.size(); + } + + void setEvidence (int ev) + { + assert (ev < dsize_); + evidence_ = ev; + } + + void setEvidence (const string& ev) + { + assert (isValidState (ev)); + for (unsigned i = 0; i < domain_.size(); i++) { + if (domain_[i] == ev) { + evidence_ = i; + } + } + } + + void setLabel (string label) + { + label_ = new string (label); + } + + string getLabel (void) const + { + if (label_ == 0) { + stringstream ss; + ss << "v" << varId_; + return ss.str(); + } else { + return *label_; + } + } + + protected: + unsigned varId_; + string* label_; + unsigned index_; + int evidence_; + + private: + DISALLOW_COPY_AND_ASSIGN (Variable); + Domain domain_; + int dsize_; + +}; + +#endif // BP_GENERIC_VARIABLE_H + diff --git a/packages/CLPBN/clpbn/bp/bnets/dog-net.xml b/packages/CLPBN/clpbn/bp/bnets/dog-net.xml deleted file mode 100644 index 74f0a0e1e..000000000 --- a/packages/CLPBN/clpbn/bp/bnets/dog-net.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - - - - - - - - - - - - - - - - - - -]> - - - - -Dog-Problem - - - - light-on - true - false - position = (73, 165) - - - - bowel-problem - true - false - position = (190, 69) - - - - dog-out - true - false - position = (155, 165) - - - - hear-bark - true - false - position = (154, 241) - - - - family-out - true - false - position = (112, 69) - - - - - - light-on - family-out - 0.6 0.4 0.05 0.95
-
- - - bowel-problem - 0.01 0.99
-
- - - dog-out - bowel-problem - family-out - 0.99 0.01 0.97 0.03 0.9 0.1 0.3 0.7
-
- - - hear-bark - dog-out - 0.7 0.3 0.01 0.99
-
- - - family-out - 0.15 0.85
-
- - -
-
diff --git a/packages/CLPBN/clpbn/bp/bnets/multiconnected.xml b/packages/CLPBN/clpbn/bp/bnets/multiconnected.xml deleted file mode 100644 index 973679408..000000000 --- a/packages/CLPBN/clpbn/bp/bnets/multiconnected.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - -Multiconnected - - - - H - h1 - h2 - - - - B - b1 - b2 - - - - L - l1 - l2 - - - - F - f1 - f2 - - - - C - c1 - c2 - - - - H - .2 .8
-
- - - B - H - .25 .75 .05 .95
-
- - - L - H - .003 .997 .00005 .99995
-
- - - F - B - L - .75 .25 .1 .9 .5 .5 .05 .95
-
- - - C - L - .6 .4 .02 .98
-
- -
-
- diff --git a/packages/CLPBN/clpbn/bp/bnets/multiconnected.yap b/packages/CLPBN/clpbn/bp/bnets/multiconnected.yap deleted file mode 100644 index 493ac7bf3..000000000 --- a/packages/CLPBN/clpbn/bp/bnets/multiconnected.yap +++ /dev/null @@ -1,59 +0,0 @@ - -:- use_module(library(clpbn)). - -:- set_clpbn_flag(solver, bp). - - -% H -% / \ -% / \ -% B L -% \ / \ -% \ / \ -% F C - - -h(H) :- - h_table(HDist), - { H = h with p([h1, h2], HDist) }. - - -b(B) :- - h(H), - b_table(BDist), - { B = b with p([b1, b2], BDist, [H]) }. - - -l(L) :- - h(H), - l_table(LDist), - { L = l with p([l1, l2], LDist, [H]) }. - - -f(F) :- - b(B), - l(L), - f_table(FDist), - { F = f with p([f1, f2], FDist, [B, L]) }. - - -c(C) :- - l(L), - c_table(CDist), - { C = c with p([c1, c2], CDist, [L]) }. - - -h_table([0.2, 0.8]). - -b_table([0.25, 0.05, - 0.75, 0.95]). - -l_table([0.003, 0.00005, - 0.997, 0.99995]). - -f_table([0.75, 0.1, 0.5, 0.05, - 0.25, 0.9, 0.5, 0.95]). - -c_table([0.6, 0.02, - 0.4, 0.98]). - diff --git a/packages/CLPBN/clpbn/bp/bnets/test.yap b/packages/CLPBN/clpbn/bp/bnets/test.yap deleted file mode 100644 index d617ea5ae..000000000 --- a/packages/CLPBN/clpbn/bp/bnets/test.yap +++ /dev/null @@ -1,36 +0,0 @@ - -:- use_module(library(clpbn)). - -:- set_clpbn_flag(solver, bp). - - -% B F -% \ / -% \ / -% A - - -a(A) :- - b(B), - f(F), - a_table(ADist), - { A = a with p([a1, a2, a3], ADist, [B, F]) }. - - - -b(B) :- - b_table(BDist), - { B = b with p([b1, b2], BDist) }. - -f(F) :- - f_table(FDist), - { F = f with p([f1, f2], FDist) }. - -b_table([0.005, 0.995]). - -f_table([0.03, 0.97]). - -a_table([0.992, 0.99, 0.2, 0.003, - 0.008, 0.01, 0.8, 0.997, - 0.018, 0.21, 0.2, 0.927]). - diff --git a/packages/CLPBN/clpbn/bp/callgrind.h b/packages/CLPBN/clpbn/bp/callgrind.h new file mode 100755 index 000000000..d36b6f4eb --- /dev/null +++ b/packages/CLPBN/clpbn/bp/callgrind.h @@ -0,0 +1,147 @@ + +/* + ---------------------------------------------------------------- + + Notice that the following BSD-style license applies to this one + file (callgrind.h) only. The rest of Valgrind is licensed under the + terms of the GNU General Public License, version 2, unless + otherwise indicated. See the COPYING file in the source + distribution for details. + + ---------------------------------------------------------------- + + This file is part of callgrind, a valgrind tool for cache simulation + and call tree tracing. + + Copyright (C) 2003-2010 Josef Weidendorfer. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ---------------------------------------------------------------- + + Notice that the above BSD-style license applies to this one file + (callgrind.h) only. The entire rest of Valgrind is licensed under + the terms of the GNU General Public License, version 2. See the + COPYING file in the source distribution for details. + + ---------------------------------------------------------------- +*/ + +#ifndef __CALLGRIND_H +#define __CALLGRIND_H + +#include "valgrind.h" + +/* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !! + This enum comprises an ABI exported by Valgrind to programs + which use client requests. DO NOT CHANGE THE ORDER OF THESE + ENTRIES, NOR DELETE ANY -- add new ones at the end. + + The identification ('C','T') for Callgrind has historical + reasons: it was called "Calltree" before. Besides, ('C','G') would + clash with cachegrind. + */ + +typedef + enum { + VG_USERREQ__DUMP_STATS = VG_USERREQ_TOOL_BASE('C','T'), + VG_USERREQ__ZERO_STATS, + VG_USERREQ__TOGGLE_COLLECT, + VG_USERREQ__DUMP_STATS_AT, + VG_USERREQ__START_INSTRUMENTATION, + VG_USERREQ__STOP_INSTRUMENTATION + } Vg_CallgrindClientRequest; + +/* Dump current state of cost centers, and zero them afterwards */ +#define CALLGRIND_DUMP_STATS \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__DUMP_STATS, \ + 0, 0, 0, 0, 0); \ + } + +/* Dump current state of cost centers, and zero them afterwards. + The argument is appended to a string stating the reason which triggered + the dump. This string is written as a description field into the + profile data dump. */ +#define CALLGRIND_DUMP_STATS_AT(pos_str) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__DUMP_STATS_AT, \ + pos_str, 0, 0, 0, 0); \ + } + +/* Zero cost centers */ +#define CALLGRIND_ZERO_STATS \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__ZERO_STATS, \ + 0, 0, 0, 0, 0); \ + } + +/* Toggles collection state. + The collection state specifies whether the happening of events + should be noted or if they are to be ignored. Events are noted + by increment of counters in a cost center */ +#define CALLGRIND_TOGGLE_COLLECT \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__TOGGLE_COLLECT, \ + 0, 0, 0, 0, 0); \ + } + +/* Start full callgrind instrumentation if not already switched on. + When cache simulation is done, it will flush the simulated cache; + this will lead to an artifical cache warmup phase afterwards with + cache misses which would not have happened in reality. */ +#define CALLGRIND_START_INSTRUMENTATION \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__START_INSTRUMENTATION, \ + 0, 0, 0, 0, 0); \ + } + +/* Stop full callgrind instrumentation if not already switched off. + This flushes Valgrinds translation cache, and does no additional + instrumentation afterwards, which effectivly will run at the same + speed as the "none" tool (ie. at minimal slowdown). + Use this to bypass Callgrind aggregation for uninteresting code parts. + To start Callgrind in this mode to ignore the setup phase, use + the option "--instr-atstart=no". */ +#define CALLGRIND_STOP_INSTRUMENTATION \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__STOP_INSTRUMENTATION, \ + 0, 0, 0, 0, 0); \ + } + +#endif /* __CALLGRIND_H */ diff --git a/packages/CLPBN/clpbn/bp/examples/bayes-ball a.xml b/packages/CLPBN/clpbn/bp/examples/bayes-ball a.xml new file mode 100755 index 000000000..286b95f59 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/bayes-ball a.xml @@ -0,0 +1,76 @@ + + + + +Bayes-Ball: The Rational Pastime Network, Figure 4, a) + + + 1 + + + + + 2 + + + + + 3 + + + + + 4 + + + + + 5 + + + + + 6 + + + + + 1 + 1
+
+ + + 2 + 1 + 3 + 1
+
+ + + 3 + 1
+
+ + + 4 + 1 + 5 + 1
+
+ + + 5 + 2 + 6 + 1
+
+ + + 6 + 3 + 1
+
+ +
+
+ diff --git a/packages/CLPBN/clpbn/bp/examples/bayes-ball c.xml b/packages/CLPBN/clpbn/bp/examples/bayes-ball c.xml new file mode 100755 index 000000000..44b291822 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/bayes-ball c.xml @@ -0,0 +1,74 @@ + + + + +Bayes-Ball: The Rational Pastime Network, Figure 4, c) + + + 1 + + + + + 2 + + + + + 3 + + + + + 4 + + + + + 5 + + + + + 6 + + + + + 1 + 1
+
+ + + 2 + 1 + 3 + 1
+
+ + + 3 + 1
+
+ + + 4 + 5 + 1
+
+ + + 5 + 2 + 6 + 1
+
+ + + 6 + 1
+
+ +
+
+ diff --git a/packages/CLPBN/clpbn/bp/examples/burglary-alarm.uai b/packages/CLPBN/clpbn/bp/examples/burglary-alarm.uai new file mode 100755 index 000000000..3f24754e2 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/burglary-alarm.uai @@ -0,0 +1,28 @@ +MARKOV +5 +2 2 2 2 2 +5 +1 0 +1 1 +3 2 0 1 +2 3 2 +2 4 2 + +2 + .001 .009 + +2 + .002 .008 + +8 + .95 .94 .29 .001 + .05 .06 .71 .999 + +4 + .9 .05 + .1 .95 + +4 + .7 .01 + .3 .99 + diff --git a/packages/CLPBN/clpbn/bp/examples/burglary-alarm.xml b/packages/CLPBN/clpbn/bp/examples/burglary-alarm.xml new file mode 100755 index 000000000..36c7a500b --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/burglary-alarm.xml @@ -0,0 +1,81 @@ + + + + + + + +Simple Loop + + + B + b1 + b2 + + + + E + e1 + e2 + + + + A + a1 + a2 + + + + J + j1 + j2 + + + + M + m1 + m2 + + + + B + .001 .009
+
+ + + E + .002 .008
+
+ + + A + B + E + .95 .05 .94 .06 .29 .71 .001 .999
+
+ + + J + A + .9 .1 .05 .95
+
+ + + M + A + .7 .3 .01 .99
+
+ +
+
+ diff --git a/packages/CLPBN/clpbn/bp/examples/burglary-alarm.yap b/packages/CLPBN/clpbn/bp/examples/burglary-alarm.yap new file mode 100755 index 000000000..9fd004712 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/burglary-alarm.yap @@ -0,0 +1,54 @@ + +:- use_module(library(clpbn)). + +:- set_clpbn_flag(solver, vel). + +% +% B E +% \ / +% \ / +% A +% / \ +% / \ +% J M +% + + +b(B) :- + b_table(BDist), + { B = b with p([b1, b2], BDist) }. + +e(E) :- + e_table(EDist), + { E = e with p([e1, e2], EDist) }. + +a(A) :- + b(B), + e(E), + a_table(ADist), + { A = a with p([a1, a2], ADist, [B, E]) }. + +j(J):- + a(A), + j_table(JDist), + { J = j with p([j1, j2], JDist, [A]) }. + +m(M):- + a(A), + m_table(MDist), + { M = m with p([m1, m2], MDist, [A]) }. + + +b_table([0.001, 0.009]). + +e_table([0.002, 0.008]). + +a_table([0.95, 0.94, 0.29, 0.001, + 0.05, 0.06, 0.71, 0.999]). + +j_table([0.9, 0.05, + 0.1, 0.95]). + +m_table([0.7, 0.01, + 0.3, 0.99]). + diff --git a/packages/CLPBN/clpbn/bp/examples/chain.xml b/packages/CLPBN/clpbn/bp/examples/chain.xml new file mode 100755 index 000000000..6b5882e5d --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/chain.xml @@ -0,0 +1,58 @@ + + + + + + +Simple Chain + + + A + a1 + a2 + + + + B + b1 + b2 + + + + C + c1 + c2 + + + + A + 0.3 0.7
+
+ + + B + A + 0.4 0.6 0.2 0.8
+
+ + + C + B + 0.9 0.1 0.25 0.75
+
+ +
+
+ diff --git a/packages/CLPBN/clpbn/bp/examples/convergence.xml b/packages/CLPBN/clpbn/bp/examples/convergence.xml new file mode 100755 index 000000000..8172042ed --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/convergence.xml @@ -0,0 +1,51 @@ + + + + + + +Simple Convergence + + + A + + + + + B + + + + + C + + + + + A + 1
+
+ + + B + 1
+
+ + + C + A + B + 1
+
+ +
+
+ diff --git a/packages/CLPBN/clpbn/bp/examples/divergence.xml b/packages/CLPBN/clpbn/bp/examples/divergence.xml new file mode 100755 index 000000000..69ef00f04 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/divergence.xml @@ -0,0 +1,51 @@ + + + + + + +Simple Divergence + + + A + + + + + B + + + + + C + + + + + A + 1
+
+ + + B + A + 1
+
+ + + C + A + 1
+
+ +
+
+ diff --git a/packages/CLPBN/clpbn/bp/bnets/john-mary-call.xml b/packages/CLPBN/clpbn/bp/examples/john-mary-call.xml old mode 100644 new mode 100755 similarity index 100% rename from packages/CLPBN/clpbn/bp/bnets/john-mary-call.xml rename to packages/CLPBN/clpbn/bp/examples/john-mary-call.xml diff --git a/packages/CLPBN/clpbn/bp/bnets/simple-loop.xml b/packages/CLPBN/clpbn/bp/examples/loop.xml old mode 100644 new mode 100755 similarity index 63% rename from packages/CLPBN/clpbn/bp/bnets/simple-loop.xml rename to packages/CLPBN/clpbn/bp/examples/loop.xml index f3a52a087..2764d73d1 --- a/packages/CLPBN/clpbn/bp/bnets/simple-loop.xml +++ b/packages/CLPBN/clpbn/bp/examples/loop.xml @@ -1,8 +1,20 @@ + + -Simple Loop +Loop A @@ -28,6 +40,12 @@ d2 + + E + e1 + e2 + + A .01 .09
@@ -36,20 +54,26 @@ B A - .03 .97 .6 .4
+ .03 .97 .6 .4
C A - .24 .76 .12 .88
+ E + .24 .76 .12 .88 .2 .4. 5. .6
D B C - .2 .8 .7 .3 .45 .55 .22 .78
+ .2 .8 .7 .3 .45 .55 .22 .78
+
+ + + E + .5 .6
diff --git a/packages/CLPBN/clpbn/bp/examples/loop.yap b/packages/CLPBN/clpbn/bp/examples/loop.yap new file mode 100755 index 000000000..c18784975 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/loop.yap @@ -0,0 +1,53 @@ + +:- use_module(library(clpbn)). + +:- set_clpbn_flag(solver, bp). + +% +% A E +% / \ / +% / \ / +% B C +% \ / +% \ / +% D +% + +a(A) :- + a_table(ADist), + { A = a with p([a1, a2], ADist) }. + +b(B) :- + a(A), + b_table(BDist), + { B = b with p([b1, b2], BDist, [A]) }. + +c(C) :- + a(A), + c_table(CDist), + { C = c with p([c1, c2], CDist, [A]) }. + +d(D) :- + b(B), + c(C), + d_table(DDist), + { D = d with p([d1, d2], DDist, [B, C]) }. + +e(E) :- + e_table(EDist), + { E = e with p([e1, e2], EDist) }. + + +a_table([0.005, 0.995]). + +b_table([0.02, 0.97, + 0.88, 0.03]). + +c_table([0.55, 0.94, + 0.45, 0.06]). + +d_table([0.192, 0.98, 0.33, 0.013, + 0.908, 0.02, 0.77, 0.987]). + +e_table([0.055, 0.945]). + diff --git a/packages/CLPBN/clpbn/bp/examples/neapolitan-A-F-joint.yap b/packages/CLPBN/clpbn/bp/examples/neapolitan-A-F-joint.yap new file mode 100755 index 000000000..4cb95eab4 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/neapolitan-A-F-joint.yap @@ -0,0 +1,55 @@ + +:- use_module(library(clpbn)). + +:- set_clpbn_flag(solver, bp). + +% +% B F +% \ / +% \ / +% A +% + +b(B) :- + b_table(BDist), + { B = b with p([b1, b2], BDist) }. + +f(F) :- + f_table(FDist), + { F = f with p([f1, f2], FDist) }. + +a(A) :- + b(B), + f(F), + a_table(ADist), + { A = a with p([a1, a2], ADist, [B, F]) }. + +d(D) :- + a(A), + f(F), + d_table(DDist), + { D = d with p([d1, d2, d3, d4], DDist, [A, F]) }. + + +b_table([0.005, 0.995]). + +f_table([0.03, 0.97]). + +a_table([0.992, 0.99, 0.2, 0.003, + 0.008, 0.01, 0.8, 0.997]). + +d_table([1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0]). + +%d_table([0.997, 0.001, 0.001, 0.001, +% 0.001, 0.997, 0.001, 0.001, +% 0.001, 0.001, 0.997, 0.001, +% 0.001, 0.001, 0.001, 0.997]). + +%d_table([0.15, 0.1, 0.7, 0.5, +% 0.25, 0.3, 0.2, 0.25, +% 0.3, 0.15, 0.35, 0.2, +% 0.3, 0.4, 0.2, 0.1]). + diff --git a/packages/CLPBN/clpbn/bp/examples/neapolitan.uai b/packages/CLPBN/clpbn/bp/examples/neapolitan.uai new file mode 100755 index 000000000..1339c83c2 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/neapolitan.uai @@ -0,0 +1,17 @@ +MARKOV +3 +2 2 2 +3 +1 0 +1 1 +3 2 0 1 + +2 + 0.005 0.995 + +2 + 0.03 0.97 + +8 + 0.992 0.99 0.2 0.003 + 0.008 0.01 0.8 0.997 diff --git a/packages/CLPBN/clpbn/bp/bnets/neapolitan.xml b/packages/CLPBN/clpbn/bp/examples/neapolitan.xml old mode 100644 new mode 100755 similarity index 60% rename from packages/CLPBN/clpbn/bp/bnets/neapolitan.xml rename to packages/CLPBN/clpbn/bp/examples/neapolitan.xml index b3a2e9612..0b359e274 --- a/packages/CLPBN/clpbn/bp/bnets/neapolitan.xml +++ b/packages/CLPBN/clpbn/bp/examples/neapolitan.xml @@ -1,49 +1,50 @@ - Neapolitan - - Burglar + B b1 b2 - FreightTruck + F f1 f2 - Alarm + A a1 a2 - Burglar + B .005 .995
- FreightTruck + F .03 .97
- Alarm - Burglar - FreightTruck + A + B + F .992 .008 .99 .01 .2 .8 .003 .997
diff --git a/packages/CLPBN/clpbn/bp/bnets/neapolitan.yap b/packages/CLPBN/clpbn/bp/examples/neapolitan.yap old mode 100644 new mode 100755 similarity index 99% rename from packages/CLPBN/clpbn/bp/bnets/neapolitan.yap rename to packages/CLPBN/clpbn/bp/examples/neapolitan.yap index 7a2155931..1d558d634 --- a/packages/CLPBN/clpbn/bp/bnets/neapolitan.yap +++ b/packages/CLPBN/clpbn/bp/examples/neapolitan.yap @@ -3,19 +3,12 @@ :- set_clpbn_flag(solver, bp). - +% % B F % \ / % \ / % A - - -a(A) :- - b(B), - f(F), - a_table(ADist), - { A = a with p([a1, a2], ADist, [B, F]) }. - +% b(B) :- @@ -26,6 +19,13 @@ f(F) :- f_table(FDist), { F = f with p([f1, f2], FDist) }. +a(A) :- + b(B), + f(F), + a_table(ADist), + { A = a with p([a1, a2], ADist, [B, F]) }. + + b_table([0.005, 0.995]). f_table([0.03, 0.97]). diff --git a/packages/CLPBN/clpbn/bp/bnets/more-than-2-parents-and-childs.xml b/packages/CLPBN/clpbn/bp/examples/several-parents-and-childs.xml old mode 100644 new mode 100755 similarity index 94% rename from packages/CLPBN/clpbn/bp/bnets/more-than-2-parents-and-childs.xml rename to packages/CLPBN/clpbn/bp/examples/several-parents-and-childs.xml index 9d1794264..e37c7ac5e --- a/packages/CLPBN/clpbn/bp/bnets/more-than-2-parents-and-childs.xml +++ b/packages/CLPBN/clpbn/bp/examples/several-parents-and-childs.xml @@ -1,8 +1,20 @@ + + -Test +Node with several parents and childs A diff --git a/packages/CLPBN/clpbn/bp/examples/test.uai b/packages/CLPBN/clpbn/bp/examples/test.uai new file mode 100755 index 000000000..f773cd9bf --- /dev/null +++ b/packages/CLPBN/clpbn/bp/examples/test.uai @@ -0,0 +1,36 @@ +MARKOV +5 +4 2 3 2 3 +7 +1 0 +1 1 +1 2 +1 3 +1 4 +2 0 1 +4 1 2 3 4 + +4 + 0.1 0.7 0.43 0.22 + +2 + 0.2 0.6 + +3 + 0.3 0.5 0.2 + +2 + 0.15 0.75 + +3 + 0.25 0.45 0.15 + +8 + 0.210 0.333 0.457 0.4 + 0.811 0.000 0.189 0.89 + +36 + 0.1 0.15 0.2 0.25 0.3 0.45 0.5 0.55 0.65 0.7 0.75 0.9 + 0.11 0.22 0.33 0.44 0.55 0.66 0.77 0.88 0.91 0.93 0.95 0.97 + 0.42 0.22 0.33 0.44 0.15 0.36 0.27 0.28 0.21 0.13 0.25 0.17 + diff --git a/packages/CLPBN/clpbn/bp/valgrind.h b/packages/CLPBN/clpbn/bp/valgrind.h new file mode 100755 index 000000000..0f5b37662 --- /dev/null +++ b/packages/CLPBN/clpbn/bp/valgrind.h @@ -0,0 +1,4536 @@ +/* -*- c -*- + ---------------------------------------------------------------- + + Notice that the following BSD-style license applies to this one + file (valgrind.h) only. The rest of Valgrind is licensed under the + terms of the GNU General Public License, version 2, unless + otherwise indicated. See the COPYING file in the source + distribution for details. + + ---------------------------------------------------------------- + + This file is part of Valgrind, a dynamic binary instrumentation + framework. + + Copyright (C) 2000-2010 Julian Seward. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ---------------------------------------------------------------- + + Notice that the above BSD-style license applies to this one file + (valgrind.h) only. The entire rest of Valgrind is licensed under + the terms of the GNU General Public License, version 2. See the + COPYING file in the source distribution for details. + + ---------------------------------------------------------------- +*/ + + +/* This file is for inclusion into client (your!) code. + + You can use these macros to manipulate and query Valgrind's + execution inside your own programs. + + The resulting executables will still run without Valgrind, just a + little bit more slowly than they otherwise would, but otherwise + unchanged. When not running on valgrind, each client request + consumes very few (eg. 7) instructions, so the resulting performance + loss is negligible unless you plan to execute client requests + millions of times per second. Nevertheless, if that is still a + problem, you can compile with the NVALGRIND symbol defined (gcc + -DNVALGRIND) so that client requests are not even compiled in. */ + +#ifndef __VALGRIND_H +#define __VALGRIND_H + + +/* ------------------------------------------------------------------ */ +/* VERSION NUMBER OF VALGRIND */ +/* ------------------------------------------------------------------ */ + +/* Specify Valgrind's version number, so that user code can + conditionally compile based on our version number. Note that these + were introduced at version 3.6 and so do not exist in version 3.5 + or earlier. The recommended way to use them to check for "version + X.Y or later" is (eg) + +#if defined(__VALGRIND_MAJOR__) && defined(__VALGRIND_MINOR__) \ + && (__VALGRIND_MAJOR__ > 3 \ + || (__VALGRIND_MAJOR__ == 3 && __VALGRIND_MINOR__ >= 6)) +*/ +#define __VALGRIND_MAJOR__ 3 +#define __VALGRIND_MINOR__ 6 + + +#include + +/* Nb: this file might be included in a file compiled with -ansi. So + we can't use C++ style "//" comments nor the "asm" keyword (instead + use "__asm__"). */ + +/* Derive some tags indicating what the target platform is. Note + that in this file we're using the compiler's CPP symbols for + identifying architectures, which are different to the ones we use + within the rest of Valgrind. Note, __powerpc__ is active for both + 32 and 64-bit PPC, whereas __powerpc64__ is only active for the + latter (on Linux, that is). + + Misc note: how to find out what's predefined in gcc by default: + gcc -Wp,-dM somefile.c +*/ +#undef PLAT_ppc64_aix5 +#undef PLAT_ppc32_aix5 +#undef PLAT_x86_darwin +#undef PLAT_amd64_darwin +#undef PLAT_x86_linux +#undef PLAT_amd64_linux +#undef PLAT_ppc32_linux +#undef PLAT_ppc64_linux +#undef PLAT_arm_linux + +#if defined(_AIX) && defined(__64BIT__) +# define PLAT_ppc64_aix5 1 +#elif defined(_AIX) && !defined(__64BIT__) +# define PLAT_ppc32_aix5 1 +#elif defined(__APPLE__) && defined(__i386__) +# define PLAT_x86_darwin 1 +#elif defined(__APPLE__) && defined(__x86_64__) +# define PLAT_amd64_darwin 1 +#elif defined(__linux__) && defined(__i386__) +# define PLAT_x86_linux 1 +#elif defined(__linux__) && defined(__x86_64__) +# define PLAT_amd64_linux 1 +#elif defined(__linux__) && defined(__powerpc__) && !defined(__powerpc64__) +# define PLAT_ppc32_linux 1 +#elif defined(__linux__) && defined(__powerpc__) && defined(__powerpc64__) +# define PLAT_ppc64_linux 1 +#elif defined(__linux__) && defined(__arm__) +# define PLAT_arm_linux 1 +#else +/* If we're not compiling for our target platform, don't generate + any inline asms. */ +# if !defined(NVALGRIND) +# define NVALGRIND 1 +# endif +#endif + + +/* ------------------------------------------------------------------ */ +/* ARCHITECTURE SPECIFICS for SPECIAL INSTRUCTIONS. There is nothing */ +/* in here of use to end-users -- skip to the next section. */ +/* ------------------------------------------------------------------ */ + +#if defined(NVALGRIND) + +/* Define NVALGRIND to completely remove the Valgrind magic sequence + from the compiled code (analogous to NDEBUG's effects on + assert()) */ +#define VALGRIND_DO_CLIENT_REQUEST( \ + _zzq_rlval, _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + { \ + (_zzq_rlval) = (_zzq_default); \ + } + +#else /* ! NVALGRIND */ + +/* The following defines the magic code sequences which the JITter + spots and handles magically. Don't look too closely at them as + they will rot your brain. + + The assembly code sequences for all architectures is in this one + file. This is because this file must be stand-alone, and we don't + want to have multiple files. + + For VALGRIND_DO_CLIENT_REQUEST, we must ensure that the default + value gets put in the return slot, so that everything works when + this is executed not under Valgrind. Args are passed in a memory + block, and so there's no intrinsic limit to the number that could + be passed, but it's currently five. + + The macro args are: + _zzq_rlval result lvalue + _zzq_default default value (result returned when running on real CPU) + _zzq_request request code + _zzq_arg1..5 request params + + The other two macros are used to support function wrapping, and are + a lot simpler. VALGRIND_GET_NR_CONTEXT returns the value of the + guest's NRADDR pseudo-register and whatever other information is + needed to safely run the call original from the wrapper: on + ppc64-linux, the R2 value at the divert point is also needed. This + information is abstracted into a user-visible type, OrigFn. + + VALGRIND_CALL_NOREDIR_* behaves the same as the following on the + guest, but guarantees that the branch instruction will not be + redirected: x86: call *%eax, amd64: call *%rax, ppc32/ppc64: + branch-and-link-to-r11. VALGRIND_CALL_NOREDIR is just text, not a + complete inline asm, since it needs to be combined with more magic + inline asm stuff to be useful. +*/ + +/* ------------------------- x86-{linux,darwin} ---------------- */ + +#if defined(PLAT_x86_linux) || defined(PLAT_x86_darwin) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "roll $3, %%edi ; roll $13, %%edi\n\t" \ + "roll $29, %%edi ; roll $19, %%edi\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST( \ + _zzq_rlval, _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + { volatile unsigned int _zzq_args[6]; \ + volatile unsigned int _zzq_result; \ + _zzq_args[0] = (unsigned int)(_zzq_request); \ + _zzq_args[1] = (unsigned int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int)(_zzq_arg5); \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %EDX = client_request ( %EAX ) */ \ + "xchgl %%ebx,%%ebx" \ + : "=d" (_zzq_result) \ + : "a" (&_zzq_args[0]), "0" (_zzq_default) \ + : "cc", "memory" \ + ); \ + _zzq_rlval = _zzq_result; \ + } + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + volatile unsigned int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %EAX = guest_NRADDR */ \ + "xchgl %%ecx,%%ecx" \ + : "=a" (__addr) \ + : \ + : "cc", "memory" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_CALL_NOREDIR_EAX \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* call-noredir *%EAX */ \ + "xchgl %%edx,%%edx\n\t" +#endif /* PLAT_x86_linux || PLAT_x86_darwin */ + +/* ------------------------ amd64-{linux,darwin} --------------- */ + +#if defined(PLAT_amd64_linux) || defined(PLAT_amd64_darwin) + +typedef + struct { + unsigned long long int nraddr; /* where's the code? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "rolq $3, %%rdi ; rolq $13, %%rdi\n\t" \ + "rolq $61, %%rdi ; rolq $51, %%rdi\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST( \ + _zzq_rlval, _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + { volatile unsigned long long int _zzq_args[6]; \ + volatile unsigned long long int _zzq_result; \ + _zzq_args[0] = (unsigned long long int)(_zzq_request); \ + _zzq_args[1] = (unsigned long long int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned long long int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned long long int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned long long int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned long long int)(_zzq_arg5); \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %RDX = client_request ( %RAX ) */ \ + "xchgq %%rbx,%%rbx" \ + : "=d" (_zzq_result) \ + : "a" (&_zzq_args[0]), "0" (_zzq_default) \ + : "cc", "memory" \ + ); \ + _zzq_rlval = _zzq_result; \ + } + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + volatile unsigned long long int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %RAX = guest_NRADDR */ \ + "xchgq %%rcx,%%rcx" \ + : "=a" (__addr) \ + : \ + : "cc", "memory" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_CALL_NOREDIR_RAX \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* call-noredir *%RAX */ \ + "xchgq %%rdx,%%rdx\n\t" +#endif /* PLAT_amd64_linux || PLAT_amd64_darwin */ + +/* ------------------------ ppc32-linux ------------------------ */ + +#if defined(PLAT_ppc32_linux) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "rlwinm 0,0,3,0,0 ; rlwinm 0,0,13,0,0\n\t" \ + "rlwinm 0,0,29,0,0 ; rlwinm 0,0,19,0,0\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST( \ + _zzq_rlval, _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + { unsigned int _zzq_args[6]; \ + unsigned int _zzq_result; \ + unsigned int* _zzq_ptr; \ + _zzq_args[0] = (unsigned int)(_zzq_request); \ + _zzq_args[1] = (unsigned int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int)(_zzq_arg5); \ + _zzq_ptr = _zzq_args; \ + __asm__ volatile("mr 3,%1\n\t" /*default*/ \ + "mr 4,%2\n\t" /*ptr*/ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = client_request ( %R4 ) */ \ + "or 1,1,1\n\t" \ + "mr %0,3" /*result*/ \ + : "=b" (_zzq_result) \ + : "b" (_zzq_default), "b" (_zzq_ptr) \ + : "cc", "memory", "r3", "r4"); \ + _zzq_rlval = _zzq_result; \ + } + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + unsigned int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR */ \ + "or 2,2,2\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "cc", "memory", "r3" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir *%R11 */ \ + "or 3,3,3\n\t" +#endif /* PLAT_ppc32_linux */ + +/* ------------------------ ppc64-linux ------------------------ */ + +#if defined(PLAT_ppc64_linux) + +typedef + struct { + unsigned long long int nraddr; /* where's the code? */ + unsigned long long int r2; /* what tocptr do we need? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "rotldi 0,0,3 ; rotldi 0,0,13\n\t" \ + "rotldi 0,0,61 ; rotldi 0,0,51\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST( \ + _zzq_rlval, _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + { unsigned long long int _zzq_args[6]; \ + register unsigned long long int _zzq_result __asm__("r3"); \ + register unsigned long long int* _zzq_ptr __asm__("r4"); \ + _zzq_args[0] = (unsigned long long int)(_zzq_request); \ + _zzq_args[1] = (unsigned long long int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned long long int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned long long int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned long long int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned long long int)(_zzq_arg5); \ + _zzq_ptr = _zzq_args; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = client_request ( %R4 ) */ \ + "or 1,1,1" \ + : "=r" (_zzq_result) \ + : "0" (_zzq_default), "r" (_zzq_ptr) \ + : "cc", "memory"); \ + _zzq_rlval = _zzq_result; \ + } + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + register unsigned long long int __addr __asm__("r3"); \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR */ \ + "or 2,2,2" \ + : "=r" (__addr) \ + : \ + : "cc", "memory" \ + ); \ + _zzq_orig->nraddr = __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR_GPR2 */ \ + "or 4,4,4" \ + : "=r" (__addr) \ + : \ + : "cc", "memory" \ + ); \ + _zzq_orig->r2 = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir *%R11 */ \ + "or 3,3,3\n\t" + +#endif /* PLAT_ppc64_linux */ + +/* ------------------------- arm-linux ------------------------- */ + +#if defined(PLAT_arm_linux) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "mov r12, r12, ror #3 ; mov r12, r12, ror #13 \n\t" \ + "mov r12, r12, ror #29 ; mov r12, r12, ror #19 \n\t" + +#define VALGRIND_DO_CLIENT_REQUEST( \ + _zzq_rlval, _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + { volatile unsigned int _zzq_args[6]; \ + volatile unsigned int _zzq_result; \ + _zzq_args[0] = (unsigned int)(_zzq_request); \ + _zzq_args[1] = (unsigned int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int)(_zzq_arg5); \ + __asm__ volatile("mov r3, %1\n\t" /*default*/ \ + "mov r4, %2\n\t" /*ptr*/ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* R3 = client_request ( R4 ) */ \ + "orr r10, r10, r10\n\t" \ + "mov %0, r3" /*result*/ \ + : "=r" (_zzq_result) \ + : "r" (_zzq_default), "r" (&_zzq_args[0]) \ + : "cc","memory", "r3", "r4"); \ + _zzq_rlval = _zzq_result; \ + } + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + unsigned int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* R3 = guest_NRADDR */ \ + "orr r11, r11, r11\n\t" \ + "mov %0, r3" \ + : "=r" (__addr) \ + : \ + : "cc", "memory", "r3" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir *%R4 */ \ + "orr r12, r12, r12\n\t" + +#endif /* PLAT_arm_linux */ + +/* ------------------------ ppc32-aix5 ------------------------- */ + +#if defined(PLAT_ppc32_aix5) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + unsigned int r2; /* what tocptr do we need? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "rlwinm 0,0,3,0,0 ; rlwinm 0,0,13,0,0\n\t" \ + "rlwinm 0,0,29,0,0 ; rlwinm 0,0,19,0,0\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST( \ + _zzq_rlval, _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + { unsigned int _zzq_args[7]; \ + register unsigned int _zzq_result; \ + register unsigned int* _zzq_ptr; \ + _zzq_args[0] = (unsigned int)(_zzq_request); \ + _zzq_args[1] = (unsigned int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int)(_zzq_arg5); \ + _zzq_args[6] = (unsigned int)(_zzq_default); \ + _zzq_ptr = _zzq_args; \ + __asm__ volatile("mr 4,%1\n\t" \ + "lwz 3, 24(4)\n\t" \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = client_request ( %R4 ) */ \ + "or 1,1,1\n\t" \ + "mr %0,3" \ + : "=b" (_zzq_result) \ + : "b" (_zzq_ptr) \ + : "r3", "r4", "cc", "memory"); \ + _zzq_rlval = _zzq_result; \ + } + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + register unsigned int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR */ \ + "or 2,2,2\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "r3", "cc", "memory" \ + ); \ + _zzq_orig->nraddr = __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR_GPR2 */ \ + "or 4,4,4\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "r3", "cc", "memory" \ + ); \ + _zzq_orig->r2 = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir *%R11 */ \ + "or 3,3,3\n\t" + +#endif /* PLAT_ppc32_aix5 */ + +/* ------------------------ ppc64-aix5 ------------------------- */ + +#if defined(PLAT_ppc64_aix5) + +typedef + struct { + unsigned long long int nraddr; /* where's the code? */ + unsigned long long int r2; /* what tocptr do we need? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "rotldi 0,0,3 ; rotldi 0,0,13\n\t" \ + "rotldi 0,0,61 ; rotldi 0,0,51\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST( \ + _zzq_rlval, _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + { unsigned long long int _zzq_args[7]; \ + register unsigned long long int _zzq_result; \ + register unsigned long long int* _zzq_ptr; \ + _zzq_args[0] = (unsigned int long long)(_zzq_request); \ + _zzq_args[1] = (unsigned int long long)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int long long)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int long long)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int long long)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int long long)(_zzq_arg5); \ + _zzq_args[6] = (unsigned int long long)(_zzq_default); \ + _zzq_ptr = _zzq_args; \ + __asm__ volatile("mr 4,%1\n\t" \ + "ld 3, 48(4)\n\t" \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = client_request ( %R4 ) */ \ + "or 1,1,1\n\t" \ + "mr %0,3" \ + : "=b" (_zzq_result) \ + : "b" (_zzq_ptr) \ + : "r3", "r4", "cc", "memory"); \ + _zzq_rlval = _zzq_result; \ + } + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + register unsigned long long int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR */ \ + "or 2,2,2\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "r3", "cc", "memory" \ + ); \ + _zzq_orig->nraddr = __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR_GPR2 */ \ + "or 4,4,4\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "r3", "cc", "memory" \ + ); \ + _zzq_orig->r2 = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir *%R11 */ \ + "or 3,3,3\n\t" + +#endif /* PLAT_ppc64_aix5 */ + +/* Insert assembly code for other platforms here... */ + +#endif /* NVALGRIND */ + + +/* ------------------------------------------------------------------ */ +/* PLATFORM SPECIFICS for FUNCTION WRAPPING. This is all very */ +/* ugly. It's the least-worst tradeoff I can think of. */ +/* ------------------------------------------------------------------ */ + +/* This section defines magic (a.k.a appalling-hack) macros for doing + guaranteed-no-redirection macros, so as to get from function + wrappers to the functions they are wrapping. The whole point is to + construct standard call sequences, but to do the call itself with a + special no-redirect call pseudo-instruction that the JIT + understands and handles specially. This section is long and + repetitious, and I can't see a way to make it shorter. + + The naming scheme is as follows: + + CALL_FN_{W,v}_{v,W,WW,WWW,WWWW,5W,6W,7W,etc} + + 'W' stands for "word" and 'v' for "void". Hence there are + different macros for calling arity 0, 1, 2, 3, 4, etc, functions, + and for each, the possibility of returning a word-typed result, or + no result. +*/ + +/* Use these to write the name of your wrapper. NOTE: duplicates + VG_WRAP_FUNCTION_Z{U,Z} in pub_tool_redir.h. */ + +/* Use an extra level of macroisation so as to ensure the soname/fnname + args are fully macro-expanded before pasting them together. */ +#define VG_CONCAT4(_aa,_bb,_cc,_dd) _aa##_bb##_cc##_dd + +#define I_WRAP_SONAME_FNNAME_ZU(soname,fnname) \ + VG_CONCAT4(_vgwZU_,soname,_,fnname) + +#define I_WRAP_SONAME_FNNAME_ZZ(soname,fnname) \ + VG_CONCAT4(_vgwZZ_,soname,_,fnname) + +/* Use this macro from within a wrapper function to collect the + context (address and possibly other info) of the original function. + Once you have that you can then use it in one of the CALL_FN_ + macros. The type of the argument _lval is OrigFn. */ +#define VALGRIND_GET_ORIG_FN(_lval) VALGRIND_GET_NR_CONTEXT(_lval) + +/* Derivatives of the main macros below, for calling functions + returning void. */ + +#define CALL_FN_v_v(fnptr) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_v(_junk,fnptr); } while (0) + +#define CALL_FN_v_W(fnptr, arg1) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_W(_junk,fnptr,arg1); } while (0) + +#define CALL_FN_v_WW(fnptr, arg1,arg2) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_WW(_junk,fnptr,arg1,arg2); } while (0) + +#define CALL_FN_v_WWW(fnptr, arg1,arg2,arg3) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_WWW(_junk,fnptr,arg1,arg2,arg3); } while (0) + +#define CALL_FN_v_WWWW(fnptr, arg1,arg2,arg3,arg4) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_WWWW(_junk,fnptr,arg1,arg2,arg3,arg4); } while (0) + +#define CALL_FN_v_5W(fnptr, arg1,arg2,arg3,arg4,arg5) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_5W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5); } while (0) + +#define CALL_FN_v_6W(fnptr, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_6W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5,arg6); } while (0) + +#define CALL_FN_v_7W(fnptr, arg1,arg2,arg3,arg4,arg5,arg6,arg7) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_7W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5,arg6,arg7); } while (0) + +/* ------------------------- x86-{linux,darwin} ---------------- */ + +#if defined(PLAT_x86_linux) || defined(PLAT_x86_darwin) + +/* These regs are trashed by the hidden call. No need to mention eax + as gcc can already see that, plus causes gcc to bomb. */ +#define __CALLER_SAVED_REGS /*"eax"*/ "ecx", "edx" + +/* These CALL_FN_ macros assume that on x86-linux, sizeof(unsigned + long) == 4. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + __asm__ volatile( \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $4, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + __asm__ volatile( \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $8, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + __asm__ volatile( \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $12, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + __asm__ volatile( \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $16, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + __asm__ volatile( \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $20, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + __asm__ volatile( \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $24, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + __asm__ volatile( \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $28, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + __asm__ volatile( \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $32, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + __asm__ volatile( \ + "pushl 36(%%eax)\n\t" \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $36, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + __asm__ volatile( \ + "pushl 40(%%eax)\n\t" \ + "pushl 36(%%eax)\n\t" \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $40, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + __asm__ volatile( \ + "pushl 44(%%eax)\n\t" \ + "pushl 40(%%eax)\n\t" \ + "pushl 36(%%eax)\n\t" \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $44, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + _argvec[12] = (unsigned long)(arg12); \ + __asm__ volatile( \ + "pushl 48(%%eax)\n\t" \ + "pushl 44(%%eax)\n\t" \ + "pushl 40(%%eax)\n\t" \ + "pushl 36(%%eax)\n\t" \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + "addl $48, %%esp\n" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_x86_linux || PLAT_x86_darwin */ + +/* ------------------------ amd64-{linux,darwin} --------------- */ + +#if defined(PLAT_amd64_linux) || defined(PLAT_amd64_darwin) + +/* ARGREGS: rdi rsi rdx rcx r8 r9 (the rest on stack in R-to-L order) */ + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS /*"rax",*/ "rcx", "rdx", "rsi", \ + "rdi", "r8", "r9", "r10", "r11" + +/* These CALL_FN_ macros assume that on amd64-linux, sizeof(unsigned + long) == 8. */ + +/* NB 9 Sept 07. There is a nasty kludge here in all these CALL_FN_ + macros. In order not to trash the stack redzone, we need to drop + %rsp by 128 before the hidden call, and restore afterwards. The + nastyness is that it is only by luck that the stack still appears + to be unwindable during the hidden call - since then the behaviour + of any routine using this macro does not match what the CFI data + says. Sigh. + + Why is this important? Imagine that a wrapper has a stack + allocated local, and passes to the hidden call, a pointer to it. + Because gcc does not know about the hidden call, it may allocate + that local in the redzone. Unfortunately the hidden call may then + trash it before it comes to use it. So we must step clear of the + redzone, for the duration of the hidden call, to make it safe. + + Probably the same problem afflicts the other redzone-style ABIs too + (ppc64-linux, ppc32-aix5, ppc64-aix5); but for those, the stack is + self describing (none of this CFI nonsense) so at least messing + with the stack pointer doesn't give a danger of non-unwindable + stack. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + "addq $128,%%rsp\n\t" \ + VALGRIND_CALL_NOREDIR_RAX \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $8, %%rsp\n" \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $16, %%rsp\n" \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "pushq 72(%%rax)\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $24, %%rsp\n" \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "pushq 80(%%rax)\n\t" \ + "pushq 72(%%rax)\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $32, %%rsp\n" \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "pushq 88(%%rax)\n\t" \ + "pushq 80(%%rax)\n\t" \ + "pushq 72(%%rax)\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $40, %%rsp\n" \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + _argvec[12] = (unsigned long)(arg12); \ + __asm__ volatile( \ + "subq $128,%%rsp\n\t" \ + "pushq 96(%%rax)\n\t" \ + "pushq 88(%%rax)\n\t" \ + "pushq 80(%%rax)\n\t" \ + "pushq 72(%%rax)\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + "addq $48, %%rsp\n" \ + "addq $128,%%rsp\n\t" \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_amd64_linux || PLAT_amd64_darwin */ + +/* ------------------------ ppc32-linux ------------------------ */ + +#if defined(PLAT_ppc32_linux) + +/* This is useful for finding out about the on-stack stuff: + + extern int f9 ( int,int,int,int,int,int,int,int,int ); + extern int f10 ( int,int,int,int,int,int,int,int,int,int ); + extern int f11 ( int,int,int,int,int,int,int,int,int,int,int ); + extern int f12 ( int,int,int,int,int,int,int,int,int,int,int,int ); + + int g9 ( void ) { + return f9(11,22,33,44,55,66,77,88,99); + } + int g10 ( void ) { + return f10(11,22,33,44,55,66,77,88,99,110); + } + int g11 ( void ) { + return f11(11,22,33,44,55,66,77,88,99,110,121); + } + int g12 ( void ) { + return f12(11,22,33,44,55,66,77,88,99,110,121,132); + } +*/ + +/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS \ + "lr", "ctr", "xer", \ + "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ + "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ + "r11", "r12", "r13" + +/* These CALL_FN_ macros assume that on ppc32-linux, + sizeof(unsigned long) == 4. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "addi 1,1,-16\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,8(1)\n\t" \ + /* args1-8 */ \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "addi 1,1,16\n\t" \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + _argvec[10] = (unsigned long)arg10; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "addi 1,1,-16\n\t" \ + /* arg10 */ \ + "lwz 3,40(11)\n\t" \ + "stw 3,12(1)\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,8(1)\n\t" \ + /* args1-8 */ \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "addi 1,1,16\n\t" \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + _argvec[10] = (unsigned long)arg10; \ + _argvec[11] = (unsigned long)arg11; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "addi 1,1,-32\n\t" \ + /* arg11 */ \ + "lwz 3,44(11)\n\t" \ + "stw 3,16(1)\n\t" \ + /* arg10 */ \ + "lwz 3,40(11)\n\t" \ + "stw 3,12(1)\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,8(1)\n\t" \ + /* args1-8 */ \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "addi 1,1,32\n\t" \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + _argvec[10] = (unsigned long)arg10; \ + _argvec[11] = (unsigned long)arg11; \ + _argvec[12] = (unsigned long)arg12; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "addi 1,1,-32\n\t" \ + /* arg12 */ \ + "lwz 3,48(11)\n\t" \ + "stw 3,20(1)\n\t" \ + /* arg11 */ \ + "lwz 3,44(11)\n\t" \ + "stw 3,16(1)\n\t" \ + /* arg10 */ \ + "lwz 3,40(11)\n\t" \ + "stw 3,12(1)\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,8(1)\n\t" \ + /* args1-8 */ \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "addi 1,1,32\n\t" \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_ppc32_linux */ + +/* ------------------------ ppc64-linux ------------------------ */ + +#if defined(PLAT_ppc64_linux) + +/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS \ + "lr", "ctr", "xer", \ + "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ + "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ + "r11", "r12", "r13" + +/* These CALL_FN_ macros assume that on ppc64-linux, sizeof(unsigned + long) == 8. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+0]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)" /* restore tocptr */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+1]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)" /* restore tocptr */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+2]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)" /* restore tocptr */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+3]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)" /* restore tocptr */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+4]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)" /* restore tocptr */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+5]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)" /* restore tocptr */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+6]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)" /* restore tocptr */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+7]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)" /* restore tocptr */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+8]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)" /* restore tocptr */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+9]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-128\n\t" /* expand stack frame */ \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + "addi 1,1,128" /* restore frame */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+10]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-128\n\t" /* expand stack frame */ \ + /* arg10 */ \ + "ld 3,80(11)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + "addi 1,1,128" /* restore frame */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+11]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-144\n\t" /* expand stack frame */ \ + /* arg11 */ \ + "ld 3,88(11)\n\t" \ + "std 3,128(1)\n\t" \ + /* arg10 */ \ + "ld 3,80(11)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + "addi 1,1,144" /* restore frame */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+12]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + _argvec[2+12] = (unsigned long)arg12; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-144\n\t" /* expand stack frame */ \ + /* arg12 */ \ + "ld 3,96(11)\n\t" \ + "std 3,136(1)\n\t" \ + /* arg11 */ \ + "ld 3,88(11)\n\t" \ + "std 3,128(1)\n\t" \ + /* arg10 */ \ + "ld 3,80(11)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + "addi 1,1,144" /* restore frame */ \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_ppc64_linux */ + +/* ------------------------- arm-linux ------------------------- */ + +#if defined(PLAT_arm_linux) + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS "r0", "r1", "r2", "r3","r4","r14" + +/* These CALL_FN_ macros assume that on arm-linux, sizeof(unsigned + long) == 4. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "mov %0, r0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + __asm__ volatile( \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "mov %0, r0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + __asm__ volatile( \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "mov %0, r0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + __asm__ volatile( \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "mov %0, r0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + __asm__ volatile( \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + __asm__ volatile( \ + "ldr r0, [%1, #20] \n\t" \ + "push {r0} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "add sp, sp, #4 \n\t" \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + __asm__ volatile( \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "push {r0, r1} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "add sp, sp, #8 \n\t" \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + __asm__ volatile( \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "push {r0, r1, r2} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "add sp, sp, #12 \n\t" \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + __asm__ volatile( \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "push {r0, r1, r2, r3} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "add sp, sp, #16 \n\t" \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + __asm__ volatile( \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "ldr r4, [%1, #36] \n\t" \ + "push {r0, r1, r2, r3, r4} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "add sp, sp, #20 \n\t" \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + __asm__ volatile( \ + "ldr r0, [%1, #40] \n\t" \ + "push {r0} \n\t" \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "ldr r4, [%1, #36] \n\t" \ + "push {r0, r1, r2, r3, r4} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "add sp, sp, #24 \n\t" \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + __asm__ volatile( \ + "ldr r0, [%1, #40] \n\t" \ + "ldr r1, [%1, #44] \n\t" \ + "push {r0, r1} \n\t" \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "ldr r4, [%1, #36] \n\t" \ + "push {r0, r1, r2, r3, r4} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "add sp, sp, #28 \n\t" \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory",__CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + _argvec[12] = (unsigned long)(arg12); \ + __asm__ volatile( \ + "ldr r0, [%1, #40] \n\t" \ + "ldr r1, [%1, #44] \n\t" \ + "ldr r2, [%1, #48] \n\t" \ + "push {r0, r1, r2} \n\t" \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "ldr r4, [%1, #36] \n\t" \ + "push {r0, r1, r2, r3, r4} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + "add sp, sp, #32 \n\t" \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_arm_linux */ + +/* ------------------------ ppc32-aix5 ------------------------- */ + +#if defined(PLAT_ppc32_aix5) + +/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS \ + "lr", "ctr", "xer", \ + "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ + "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ + "r11", "r12", "r13" + +/* Expand the stack frame, copying enough info that unwinding + still works. Trashes r3. */ + +#define VG_EXPAND_FRAME_BY_trashes_r3(_n_fr) \ + "addi 1,1,-" #_n_fr "\n\t" \ + "lwz 3," #_n_fr "(1)\n\t" \ + "stw 3,0(1)\n\t" + +#define VG_CONTRACT_FRAME_BY(_n_fr) \ + "addi 1,1," #_n_fr "\n\t" + +/* These CALL_FN_ macros assume that on ppc32-aix5, sizeof(unsigned + long) == 4. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+0]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+1]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+2]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+3]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+4]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+5]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ + "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+6]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ + "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ + "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+7]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ + "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ + "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ + "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+8]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ + "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ + "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ + "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ + "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+9]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + VG_EXPAND_FRAME_BY_trashes_r3(64) \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,56(1)\n\t" \ + /* args1-8 */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ + "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ + "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ + "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ + "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(64) \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+10]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + VG_EXPAND_FRAME_BY_trashes_r3(64) \ + /* arg10 */ \ + "lwz 3,40(11)\n\t" \ + "stw 3,60(1)\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,56(1)\n\t" \ + /* args1-8 */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ + "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ + "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ + "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ + "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(64) \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+11]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + VG_EXPAND_FRAME_BY_trashes_r3(72) \ + /* arg11 */ \ + "lwz 3,44(11)\n\t" \ + "stw 3,64(1)\n\t" \ + /* arg10 */ \ + "lwz 3,40(11)\n\t" \ + "stw 3,60(1)\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,56(1)\n\t" \ + /* args1-8 */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ + "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ + "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ + "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ + "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(72) \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+12]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + _argvec[2+12] = (unsigned long)arg12; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "stw 2,-8(11)\n\t" /* save tocptr */ \ + "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \ + VG_EXPAND_FRAME_BY_trashes_r3(72) \ + /* arg12 */ \ + "lwz 3,48(11)\n\t" \ + "stw 3,68(1)\n\t" \ + /* arg11 */ \ + "lwz 3,44(11)\n\t" \ + "stw 3,64(1)\n\t" \ + /* arg10 */ \ + "lwz 3,40(11)\n\t" \ + "stw 3,60(1)\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,56(1)\n\t" \ + /* args1-8 */ \ + "lwz 3, 4(11)\n\t" /* arg1->r3 */ \ + "lwz 4, 8(11)\n\t" /* arg2->r4 */ \ + "lwz 5, 12(11)\n\t" /* arg3->r5 */ \ + "lwz 6, 16(11)\n\t" /* arg4->r6 */ \ + "lwz 7, 20(11)\n\t" /* arg5->r7 */ \ + "lwz 8, 24(11)\n\t" /* arg6->r8 */ \ + "lwz 9, 28(11)\n\t" /* arg7->r9 */ \ + "lwz 10, 32(11)\n\t" /* arg8->r10 */ \ + "lwz 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "lwz 2,-8(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(72) \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_ppc32_aix5 */ + +/* ------------------------ ppc64-aix5 ------------------------- */ + +#if defined(PLAT_ppc64_aix5) + +/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS \ + "lr", "ctr", "xer", \ + "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ + "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ + "r11", "r12", "r13" + +/* Expand the stack frame, copying enough info that unwinding + still works. Trashes r3. */ + +#define VG_EXPAND_FRAME_BY_trashes_r3(_n_fr) \ + "addi 1,1,-" #_n_fr "\n\t" \ + "ld 3," #_n_fr "(1)\n\t" \ + "std 3,0(1)\n\t" + +#define VG_CONTRACT_FRAME_BY(_n_fr) \ + "addi 1,1," #_n_fr "\n\t" + +/* These CALL_FN_ macros assume that on ppc64-aix5, sizeof(unsigned + long) == 8. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+0]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+1]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+2]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+3]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+4]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+5]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+6]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+7]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+8]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+9]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + VG_EXPAND_FRAME_BY_trashes_r3(128) \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(128) \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+10]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + VG_EXPAND_FRAME_BY_trashes_r3(128) \ + /* arg10 */ \ + "ld 3,80(11)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(128) \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+11]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + VG_EXPAND_FRAME_BY_trashes_r3(144) \ + /* arg11 */ \ + "ld 3,88(11)\n\t" \ + "std 3,128(1)\n\t" \ + /* arg10 */ \ + "ld 3,80(11)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(144) \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+12]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + _argvec[2+12] = (unsigned long)arg12; \ + __asm__ volatile( \ + "mr 11,%1\n\t" \ + VG_EXPAND_FRAME_BY_trashes_r3(512) \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + VG_EXPAND_FRAME_BY_trashes_r3(144) \ + /* arg12 */ \ + "ld 3,96(11)\n\t" \ + "std 3,136(1)\n\t" \ + /* arg11 */ \ + "ld 3,88(11)\n\t" \ + "std 3,128(1)\n\t" \ + /* arg10 */ \ + "ld 3,80(11)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VG_CONTRACT_FRAME_BY(144) \ + VG_CONTRACT_FRAME_BY(512) \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_ppc64_aix5 */ + + +/* ------------------------------------------------------------------ */ +/* ARCHITECTURE INDEPENDENT MACROS for CLIENT REQUESTS. */ +/* */ +/* ------------------------------------------------------------------ */ + +/* Some request codes. There are many more of these, but most are not + exposed to end-user view. These are the public ones, all of the + form 0x1000 + small_number. + + Core ones are in the range 0x00000000--0x0000ffff. The non-public + ones start at 0x2000. +*/ + +/* These macros are used by tools -- they must be public, but don't + embed them into other programs. */ +#define VG_USERREQ_TOOL_BASE(a,b) \ + ((unsigned int)(((a)&0xff) << 24 | ((b)&0xff) << 16)) +#define VG_IS_TOOL_USERREQ(a, b, v) \ + (VG_USERREQ_TOOL_BASE(a,b) == ((v) & 0xffff0000)) + +/* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !! + This enum comprises an ABI exported by Valgrind to programs + which use client requests. DO NOT CHANGE THE ORDER OF THESE + ENTRIES, NOR DELETE ANY -- add new ones at the end. */ +typedef + enum { VG_USERREQ__RUNNING_ON_VALGRIND = 0x1001, + VG_USERREQ__DISCARD_TRANSLATIONS = 0x1002, + + /* These allow any function to be called from the simulated + CPU but run on the real CPU. Nb: the first arg passed to + the function is always the ThreadId of the running + thread! So CLIENT_CALL0 actually requires a 1 arg + function, etc. */ + VG_USERREQ__CLIENT_CALL0 = 0x1101, + VG_USERREQ__CLIENT_CALL1 = 0x1102, + VG_USERREQ__CLIENT_CALL2 = 0x1103, + VG_USERREQ__CLIENT_CALL3 = 0x1104, + + /* Can be useful in regression testing suites -- eg. can + send Valgrind's output to /dev/null and still count + errors. */ + VG_USERREQ__COUNT_ERRORS = 0x1201, + + /* These are useful and can be interpreted by any tool that + tracks malloc() et al, by using vg_replace_malloc.c. */ + VG_USERREQ__MALLOCLIKE_BLOCK = 0x1301, + VG_USERREQ__FREELIKE_BLOCK = 0x1302, + /* Memory pool support. */ + VG_USERREQ__CREATE_MEMPOOL = 0x1303, + VG_USERREQ__DESTROY_MEMPOOL = 0x1304, + VG_USERREQ__MEMPOOL_ALLOC = 0x1305, + VG_USERREQ__MEMPOOL_FREE = 0x1306, + VG_USERREQ__MEMPOOL_TRIM = 0x1307, + VG_USERREQ__MOVE_MEMPOOL = 0x1308, + VG_USERREQ__MEMPOOL_CHANGE = 0x1309, + VG_USERREQ__MEMPOOL_EXISTS = 0x130a, + + /* Allow printfs to valgrind log. */ + /* The first two pass the va_list argument by value, which + assumes it is the same size as or smaller than a UWord, + which generally isn't the case. Hence are deprecated. + The second two pass the vargs by reference and so are + immune to this problem. */ + /* both :: char* fmt, va_list vargs (DEPRECATED) */ + VG_USERREQ__PRINTF = 0x1401, + VG_USERREQ__PRINTF_BACKTRACE = 0x1402, + /* both :: char* fmt, va_list* vargs */ + VG_USERREQ__PRINTF_VALIST_BY_REF = 0x1403, + VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF = 0x1404, + + /* Stack support. */ + VG_USERREQ__STACK_REGISTER = 0x1501, + VG_USERREQ__STACK_DEREGISTER = 0x1502, + VG_USERREQ__STACK_CHANGE = 0x1503, + + /* Wine support */ + VG_USERREQ__LOAD_PDB_DEBUGINFO = 0x1601 + } Vg_ClientRequest; + +#if !defined(__GNUC__) +# define __extension__ /* */ +#endif + +/* Returns the number of Valgrinds this code is running under. That + is, 0 if running natively, 1 if running under Valgrind, 2 if + running under Valgrind which is running under another Valgrind, + etc. */ +#define RUNNING_ON_VALGRIND __extension__ \ + ({unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0 /* if not */, \ + VG_USERREQ__RUNNING_ON_VALGRIND, \ + 0, 0, 0, 0, 0); \ + _qzz_res; \ + }) + + +/* Discard translation of code in the range [_qzz_addr .. _qzz_addr + + _qzz_len - 1]. Useful if you are debugging a JITter or some such, + since it provides a way to make sure valgrind will retranslate the + invalidated area. Returns no value. */ +#define VALGRIND_DISCARD_TRANSLATIONS(_qzz_addr,_qzz_len) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__DISCARD_TRANSLATIONS, \ + _qzz_addr, _qzz_len, 0, 0, 0); \ + } + + +/* These requests are for getting Valgrind itself to print something. + Possibly with a backtrace. This is a really ugly hack. The return value + is the number of characters printed, excluding the "**** " part at the + start and the backtrace (if present). */ + +#if defined(NVALGRIND) + +# define VALGRIND_PRINTF(...) +# define VALGRIND_PRINTF_BACKTRACE(...) + +#else /* NVALGRIND */ + +/* Modern GCC will optimize the static routine out if unused, + and unused attribute will shut down warnings about it. */ +static int VALGRIND_PRINTF(const char *format, ...) + __attribute__((format(__printf__, 1, 2), __unused__)); +static int +VALGRIND_PRINTF(const char *format, ...) +{ + unsigned long _qzz_res; + va_list vargs; + va_start(vargs, format); + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, + VG_USERREQ__PRINTF_VALIST_BY_REF, + (unsigned long)format, + (unsigned long)&vargs, + 0, 0, 0); + va_end(vargs); + return (int)_qzz_res; +} + +static int VALGRIND_PRINTF_BACKTRACE(const char *format, ...) + __attribute__((format(__printf__, 1, 2), __unused__)); +static int +VALGRIND_PRINTF_BACKTRACE(const char *format, ...) +{ + unsigned long _qzz_res; + va_list vargs; + va_start(vargs, format); + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, + VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF, + (unsigned long)format, + (unsigned long)&vargs, + 0, 0, 0); + va_end(vargs); + return (int)_qzz_res; +} + +#endif /* NVALGRIND */ + + +/* These requests allow control to move from the simulated CPU to the + real CPU, calling an arbitary function. + + Note that the current ThreadId is inserted as the first argument. + So this call: + + VALGRIND_NON_SIMD_CALL2(f, arg1, arg2) + + requires f to have this signature: + + Word f(Word tid, Word arg1, Word arg2) + + where "Word" is a word-sized type. + + Note that these client requests are not entirely reliable. For example, + if you call a function with them that subsequently calls printf(), + there's a high chance Valgrind will crash. Generally, your prospects of + these working are made higher if the called function does not refer to + any global variables, and does not refer to any libc or other functions + (printf et al). Any kind of entanglement with libc or dynamic linking is + likely to have a bad outcome, for tricky reasons which we've grappled + with a lot in the past. +*/ +#define VALGRIND_NON_SIMD_CALL0(_qyy_fn) \ + __extension__ \ + ({unsigned long _qyy_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ + VG_USERREQ__CLIENT_CALL0, \ + _qyy_fn, \ + 0, 0, 0, 0); \ + _qyy_res; \ + }) + +#define VALGRIND_NON_SIMD_CALL1(_qyy_fn, _qyy_arg1) \ + __extension__ \ + ({unsigned long _qyy_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ + VG_USERREQ__CLIENT_CALL1, \ + _qyy_fn, \ + _qyy_arg1, 0, 0, 0); \ + _qyy_res; \ + }) + +#define VALGRIND_NON_SIMD_CALL2(_qyy_fn, _qyy_arg1, _qyy_arg2) \ + __extension__ \ + ({unsigned long _qyy_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ + VG_USERREQ__CLIENT_CALL2, \ + _qyy_fn, \ + _qyy_arg1, _qyy_arg2, 0, 0); \ + _qyy_res; \ + }) + +#define VALGRIND_NON_SIMD_CALL3(_qyy_fn, _qyy_arg1, _qyy_arg2, _qyy_arg3) \ + __extension__ \ + ({unsigned long _qyy_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ + VG_USERREQ__CLIENT_CALL3, \ + _qyy_fn, \ + _qyy_arg1, _qyy_arg2, \ + _qyy_arg3, 0); \ + _qyy_res; \ + }) + + +/* Counts the number of errors that have been recorded by a tool. Nb: + the tool must record the errors with VG_(maybe_record_error)() or + VG_(unique_error)() for them to be counted. */ +#define VALGRIND_COUNT_ERRORS \ + __extension__ \ + ({unsigned int _qyy_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \ + VG_USERREQ__COUNT_ERRORS, \ + 0, 0, 0, 0, 0); \ + _qyy_res; \ + }) + +/* Several Valgrind tools (Memcheck, Massif, Helgrind, DRD) rely on knowing + when heap blocks are allocated in order to give accurate results. This + happens automatically for the standard allocator functions such as + malloc(), calloc(), realloc(), memalign(), new, new[], free(), delete, + delete[], etc. + + But if your program uses a custom allocator, this doesn't automatically + happen, and Valgrind will not do as well. For example, if you allocate + superblocks with mmap() and then allocates chunks of the superblocks, all + Valgrind's observations will be at the mmap() level and it won't know that + the chunks should be considered separate entities. In Memcheck's case, + that means you probably won't get heap block overrun detection (because + there won't be redzones marked as unaddressable) and you definitely won't + get any leak detection. + + The following client requests allow a custom allocator to be annotated so + that it can be handled accurately by Valgrind. + + VALGRIND_MALLOCLIKE_BLOCK marks a region of memory as having been allocated + by a malloc()-like function. For Memcheck (an illustrative case), this + does two things: + + - It records that the block has been allocated. This means any addresses + within the block mentioned in error messages will be + identified as belonging to the block. It also means that if the block + isn't freed it will be detected by the leak checker. + + - It marks the block as being addressable and undefined (if 'is_zeroed' is + not set), or addressable and defined (if 'is_zeroed' is set). This + controls how accesses to the block by the program are handled. + + 'addr' is the start of the usable block (ie. after any + redzone), 'sizeB' is its size. 'rzB' is the redzone size if the allocator + can apply redzones -- these are blocks of padding at the start and end of + each block. Adding redzones is recommended as it makes it much more likely + Valgrind will spot block overruns. `is_zeroed' indicates if the memory is + zeroed (or filled with another predictable value), as is the case for + calloc(). + + VALGRIND_MALLOCLIKE_BLOCK should be put immediately after the point where a + heap block -- that will be used by the client program -- is allocated. + It's best to put it at the outermost level of the allocator if possible; + for example, if you have a function my_alloc() which calls + internal_alloc(), and the client request is put inside internal_alloc(), + stack traces relating to the heap block will contain entries for both + my_alloc() and internal_alloc(), which is probably not what you want. + + For Memcheck users: if you use VALGRIND_MALLOCLIKE_BLOCK to carve out + custom blocks from within a heap block, B, that has been allocated with + malloc/calloc/new/etc, then block B will be *ignored* during leak-checking + -- the custom blocks will take precedence. + + VALGRIND_FREELIKE_BLOCK is the partner to VALGRIND_MALLOCLIKE_BLOCK. For + Memcheck, it does two things: + + - It records that the block has been deallocated. This assumes that the + block was annotated as having been allocated via + VALGRIND_MALLOCLIKE_BLOCK. Otherwise, an error will be issued. + + - It marks the block as being unaddressable. + + VALGRIND_FREELIKE_BLOCK should be put immediately after the point where a + heap block is deallocated. + + In many cases, these two client requests will not be enough to get your + allocator working well with Memcheck. More specifically, if your allocator + writes to freed blocks in any way then a VALGRIND_MAKE_MEM_UNDEFINED call + will be necessary to mark the memory as addressable just before the zeroing + occurs, otherwise you'll get a lot of invalid write errors. For example, + you'll need to do this if your allocator recycles freed blocks, but it + zeroes them before handing them back out (via VALGRIND_MALLOCLIKE_BLOCK). + Alternatively, if your allocator reuses freed blocks for allocator-internal + data structures, VALGRIND_MAKE_MEM_UNDEFINED calls will also be necessary. + + Really, what's happening is a blurring of the lines between the client + program and the allocator... after VALGRIND_FREELIKE_BLOCK is called, the + memory should be considered unaddressable to the client program, but the + allocator knows more than the rest of the client program and so may be able + to safely access it. Extra client requests are necessary for Valgrind to + understand the distinction between the allocator and the rest of the + program. + + Note: there is currently no VALGRIND_REALLOCLIKE_BLOCK client request; it + has to be emulated with MALLOCLIKE/FREELIKE and memory copying. + + Ignored if addr == 0. +*/ +#define VALGRIND_MALLOCLIKE_BLOCK(addr, sizeB, rzB, is_zeroed) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__MALLOCLIKE_BLOCK, \ + addr, sizeB, rzB, is_zeroed, 0); \ + } + +/* See the comment for VALGRIND_MALLOCLIKE_BLOCK for details. + Ignored if addr == 0. +*/ +#define VALGRIND_FREELIKE_BLOCK(addr, rzB) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__FREELIKE_BLOCK, \ + addr, rzB, 0, 0, 0); \ + } + +/* Create a memory pool. */ +#define VALGRIND_CREATE_MEMPOOL(pool, rzB, is_zeroed) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__CREATE_MEMPOOL, \ + pool, rzB, is_zeroed, 0, 0); \ + } + +/* Destroy a memory pool. */ +#define VALGRIND_DESTROY_MEMPOOL(pool) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__DESTROY_MEMPOOL, \ + pool, 0, 0, 0, 0); \ + } + +/* Associate a piece of memory with a memory pool. */ +#define VALGRIND_MEMPOOL_ALLOC(pool, addr, size) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__MEMPOOL_ALLOC, \ + pool, addr, size, 0, 0); \ + } + +/* Disassociate a piece of memory from a memory pool. */ +#define VALGRIND_MEMPOOL_FREE(pool, addr) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__MEMPOOL_FREE, \ + pool, addr, 0, 0, 0); \ + } + +/* Disassociate any pieces outside a particular range. */ +#define VALGRIND_MEMPOOL_TRIM(pool, addr, size) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__MEMPOOL_TRIM, \ + pool, addr, size, 0, 0); \ + } + +/* Resize and/or move a piece associated with a memory pool. */ +#define VALGRIND_MOVE_MEMPOOL(poolA, poolB) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__MOVE_MEMPOOL, \ + poolA, poolB, 0, 0, 0); \ + } + +/* Resize and/or move a piece associated with a memory pool. */ +#define VALGRIND_MEMPOOL_CHANGE(pool, addrA, addrB, size) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__MEMPOOL_CHANGE, \ + pool, addrA, addrB, size, 0); \ + } + +/* Return 1 if a mempool exists, else 0. */ +#define VALGRIND_MEMPOOL_EXISTS(pool) \ + __extension__ \ + ({unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__MEMPOOL_EXISTS, \ + pool, 0, 0, 0, 0); \ + _qzz_res; \ + }) + +/* Mark a piece of memory as being a stack. Returns a stack id. */ +#define VALGRIND_STACK_REGISTER(start, end) \ + __extension__ \ + ({unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__STACK_REGISTER, \ + start, end, 0, 0, 0); \ + _qzz_res; \ + }) + +/* Unmark the piece of memory associated with a stack id as being a + stack. */ +#define VALGRIND_STACK_DEREGISTER(id) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__STACK_DEREGISTER, \ + id, 0, 0, 0, 0); \ + } + +/* Change the start and end address of the stack id. */ +#define VALGRIND_STACK_CHANGE(id, start, end) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__STACK_CHANGE, \ + id, start, end, 0, 0); \ + } + +/* Load PDB debug info for Wine PE image_map. */ +#define VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta) \ + {unsigned int _qzz_res; \ + VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \ + VG_USERREQ__LOAD_PDB_DEBUGINFO, \ + fd, ptr, total_size, delta, 0); \ + } + + +#undef PLAT_x86_linux +#undef PLAT_amd64_linux +#undef PLAT_ppc32_linux +#undef PLAT_ppc64_linux +#undef PLAT_arm_linux +#undef PLAT_ppc32_aix5 +#undef PLAT_ppc64_aix5 + +#endif /* __VALGRIND_H */ diff --git a/packages/CLPBN/clpbn/connected.yap b/packages/CLPBN/clpbn/connected.yap index 7b0e90860..276184683 100644 --- a/packages/CLPBN/clpbn/connected.yap +++ b/packages/CLPBN/clpbn/connected.yap @@ -1,172 +1,144 @@ :- module(clpbn_connected, - [clpbn_subgraphs/2, - influences/4, + [influences/3, init_influences/3, - influences/5]). + influences/4]). :- use_module(library(dgraphs), [dgraph_new/1, dgraph_add_edges/3, dgraph_add_vertex/3, dgraph_neighbors/3, - dgraph_edge/3]). + dgraph_edge/3, + dgraph_transpose/2]). :- use_module(library(rbtrees), [rb_new/1, + rb_lookup/3, rb_insert/4, - rb_lookup/3]). + rb_visit/2]). -:- attribute component/1. - -% search for connected components, that is, where we know that A influences B or B influences A. -clpbn_subgraphs(Vs, Gs) :- - mark_components(Vs, Components), - keysort(Components, Ordered), - same_key(Ordered, Gs). - -% ignore variables with evidence, -% the others mark the MB. -mark_components([], []). -mark_components([V|Vs], Components) :- - clpbn:get_atts(V, [evidence(_),dist(_,Parents)]), !, - merge_parents(Parents, _), - mark_components(Vs, Components). -mark_components([V|Vs], [Mark-V|Components]) :- - mark_var(V, Mark), - mark_components(Vs, Components). - -mark_var(V, Mark) :- - get_atts(V, [component(Mark)]), !, - clpbn:get_atts(V, [dist(_,Parents)]), !, - merge_parents(Parents, Mark). -mark_var(V, Mark) :- - clpbn:get_atts(V, [dist(_,Parents)]), !, - put_atts(V,[component(Mark)]), - merge_parents(Parents, Mark). - -merge_parents([], _). -merge_parents([V|Parents], Mark) :- - clpbn:get_atts(V,[evidence(_)]), !, - merge_parents(Parents, Mark). -merge_parents([V|Parents], Mark) :- - get_atts(V,[component(Mark)]), !, - merge_parents(Parents, Mark). -merge_parents([V|Parents], Mark) :- - put_atts(V,[component(Mark)]), - merge_parents(Parents, Mark). - - -same_key([],[]). -same_key([K-El|More],[[El|Els]|Gs]) :- - same_keys(More, K, Els, Rest), - same_key(Rest,Gs). - -same_keys([], _, [], []). -same_keys([K1-El|More], K, [El|Els], Rest) :- - K == K1, !, - same_keys(More, K, Els, Rest). -same_keys(Rest, _, [], Rest). - -influences_more([], _, _, Is, Is, Evs, Evs, V2, V2). -influences_more([V|LV], G, RG, Is0, Is, Evs0, Evs, GV0, GV2) :- - rb_lookup(V, _, GV0), !, - influences_more(LV, G, RG, Is0, Is, Evs0, Evs, GV0, GV2). -influences_more([V|LV], G, RG, Is0, Is, Evs0, Evs, GV0, GV3) :- - rb_insert(GV0, V, _, GV1), - follow_dgraph(V, G, RG, [V|Is0], Is1, [V|Evs0], Evs1, GV1, GV2), - influences_more(LV, G, RG, Is1, Is, Evs1, Evs, GV2, GV3). - -% search for the set of variables that influence V -influences(Vs, LV, Is, Evs) :- +influences(Vs, QVars, LV) :- init_influences(Vs, G, RG), - influences(LV, Is, Evs, G, RG). + influences(QVars, G, RG, LV). init_influences(Vs, G, RG) :- dgraph_new(G0), - dgraph_new(RG0), - to_dgraph(Vs, G0, G, RG0, RG). + to_dgraph(Vs, G0, G), + dgraph_transpose(G, RG). -influences([], [], [], _, _). -influences([V|LV], Is, Evs, G, RG) :- - rb_new(V0), - rb_insert(V0, V, _, V1), - follow_dgraph(V, G, RG, [V], Is1, [V], Evs1, V1, V2), - influences_more(LV, G, RG, Is1, Is, Evs1, Evs, V2, _). +to_dgraph([], G, G). +to_dgraph([V|Vs], G0, G) :- + clpbn:get_atts(V, [dist(_,Parents)]), !, + dgraph_add_vertex(G0, V, G00), + build_edges(Parents, V, Edges), + dgraph_add_edges(G00, Edges, G1), + to_dgraph(Vs, G1, G). -to_dgraph([], G, G, RG, RG). -to_dgraph([V|Vs], G0, G, RG0, RG) :- - clpbn:get_atts(V, [evidence(_),dist(_,Parents)]), !, - build_edges(Parents, V, Edges, REdges), - dgraph_add_edges(G0,[V-e|Edges],G1), - dgraph_add_edges(RG0,REdges,RG1), - to_dgraph(Vs, G1, G, RG1, RG). -to_dgraph([V|Vs], G0, G, RG0, RG) :- - clpbn:get_atts(V, [dist(_,Parents)]), - build_edges(Parents, V, Edges, REdges), - dgraph_add_vertex(G0,V,G1), - dgraph_add_edges(G1, Edges, G2), - dgraph_add_vertex(RG0,V,RG1), - dgraph_add_edges(RG1, REdges, RG2), - to_dgraph(Vs, G2, G, RG2, RG). +build_edges([], _, []). +build_edges([P|Parents], V, [P-V|Edges]) :- + build_edges(Parents, V, Edges). +% search for the set of variables that influence V +influences(Vs, G, RG, Vars) :- + rb_new(Visited0), + influences(Vs, G, RG, Visited0, Visited), + all_top(Visited, Vars), +length(Vars,Leng), writeln(done:Leng). -build_edges([], _, [], []). -build_edges([P|Parents], V, [P-V|Edges], [V-P|REdges]) :- - build_edges(Parents, V, Edges, REdges). +influences([], _, _, Visited, Visited). +influences([V|LV], G, RG, Vs, NVs) :- + rb_lookup(V, T.B, Vs), T == t, B == b, !, + influences(LV, G, RG, Vs, NVs). +influences([V|LV], G, RG, Vs0, Vs3) :- + rb_insert(Vs0, V, t.b, Vs1), + process_new_variable(V, G, RG, Vs1, Vs2), + influences(LV, G, RG, Vs2, Vs3). -follow_dgraph(V, G, RG, Is0, IsF, Evs0, EvsF, Visited0, Visited) :- +process_new_variable(V, _G, _RG, _Vs0, _Vs1) :- + clpbn:get_atts(V,[evidence(Ev)]), !, + throw(error(bound_to_evidence(V/Ev))). +process_new_variable(V, G, RG, Vs0, Vs2) :- + dgraph_neighbors(V, G, Children), + throw_all_below(Children, G, RG, Vs0, Vs1), dgraph_neighbors(V, RG, Parents), - add_parents(Parents, G, RG, Is0, IsI, Evs0, EvsI, Visited0, Visited1), - dgraph_neighbors(V, G, Kids), - add_kids(Kids, G, RG, IsI, IsF, EvsI, EvsF, Visited1, Visited). + throw_all_above(Parents, G, RG, Vs1, Vs2). -add_parents([], _, _, Is, Is, Evs, Evs, Visited, Visited). -% been here already, can safely ignore. -add_parents([V|Vs], G, RG, Is0, IsF, Evs0, EvsF, Visited0, VisitedF) :- - rb_lookup(V, _, Visited0), !, - add_parents(Vs, G, RG, Is0, IsF, Evs0, EvsF, Visited0, VisitedF). -% evidence node, -% just say that we visited it -add_parents([V|Vs], G, RG, Is0, IsF, Evs0, EvsF, Visited0, VisitedF) :- - dgraph_edge(V,e,G), !, % has evidence - rb_insert(Visited0, V, _, VisitedI), - add_parents(Vs, G, RG, Is0, IsF, [V|Evs0], EvsF, VisitedI, VisitedF). -% non-evidence node, -% we will need to find its parents. -add_parents([V|Vs], G, RG, Is0, IsF, Evs0, EvsF, Visited0, VisitedF) :- - rb_insert(Visited0, V, _, VisitedI), - follow_dgraph(V, G, RG, [V|Is0], IsI, [V|Evs0], EvsI, VisitedI, VisitedII), - add_parents(Vs, G, RG, IsI, IsF, EvsI, EvsF, VisitedII, VisitedF). - -add_kids([], _, _, Is, Is, Evs, Evs, Visited, Visited). -add_kids([V|Vs], G, RG, Is0, IsF, Evs0, EvsF, Visited0, VisitedF) :- - dgraph_edge(V,e,G), % has evidence - % we will go there even if it was visited - ( rb_insert(Visited0, V, _, Visited1) -> - true - ; - % we've been there, but were we there as a father or as a kid? - not_in(Evs0, V), - Visited1 = Visited0 - ), - !, - dgraph_neighbors(V, RG, Parents), - add_parents(Parents, G, RG, Is0, Is1, [V|Evs0], EvsI, Visited1, VisitedI), - (Is1 = Is0 -> - % ignore whatever we did with this node, - % it didn't lead anywhere (all parents have evidence). - add_kids(Vs, G, RG, Is0, IsF, [V|Evs0], EvsF, Visited1, VisitedF) - ; - % insert parents - add_kids(Vs, G, RG, Is1, IsF, EvsI, EvsF, VisitedI, VisitedF) - ). -add_kids([_|Vs], G, RG, Is0, IsF, Evs0, EvsF, Visited0, VisitedF) :- - add_kids(Vs, G, RG, Is0, IsF, Evs0, EvsF, Visited0, VisitedF). +throw_all_below([], _, _, Vs, Vs). +throw_all_below(Child.Children, G, RG, Vs0, Vs2) :- +% clpbn:get_atts(Child,[key(K)]), rb_visit(Vs0, Pairs), writeln(down:Child:K:Pairs), + throw_below(Child, G, RG, Vs0, Vs1), + throw_all_below(Children, G, RG, Vs1, Vs2). + +% visited +throw_below(Child, G, RG, Vs0, Vs1) :- + rb_lookup(Child, _.B, Vs0), !, + ( + B == b -> + Vs0 = Vs1 % been there before + ; + B = b, % mark it + handle_ball_from_above(Child, G, RG, Vs0, Vs1) + ). +throw_below(Child, G, RG, Vs0, Vs2) :- + rb_insert(Vs0, Child, _.b, Vs1), + handle_ball_from_above(Child, G, RG, Vs1, Vs2). + +% share this with parents, if we have evidence +handle_ball_from_above(V, G, RG, Vs0, Vs1) :- + clpbn:get_atts(V,[evidence(_)]), !, + dgraph_neighbors(V, RG, Parents), + throw_all_above(Parents, G, RG, Vs0, Vs1). +% propagate to kids, if we do not +handle_ball_from_above(V, G, RG, Vs0, Vs1) :- + dgraph_neighbors(V, G, Children), + throw_all_below(Children, G, RG, Vs0, Vs1). +throw_all_above([], _, _, Vs, Vs). +throw_all_above(Parent.Parentren, G, RG, Vs0, Vs2) :- +% clpbn:get_atts(Parent,[key(K)]), rb_visit(Vs0, Pairs), writeln(up:Parent:K:Pairs), + throw_above(Parent, G, RG, Vs0, Vs1), + throw_all_above(Parentren, G, RG, Vs1, Vs2). -not_in([V1|_], V) :- V1 == V, !, fail. -not_in([_|Evs0], V) :- - not_in(Evs0, V). +% visited +throw_above(Parent, G, RG, Vs0, Vs1) :- + rb_lookup(Parent, T._, Vs0), !, + ( + T == t -> + Vs1 = Vs0 % been there before + ; + T = t, % mark it + handle_ball_from_below(Parent, G, RG, Vs0, Vs1) + ). +throw_above(Parent, G, RG, Vs0, Vs2) :- + rb_insert(Vs0, Parent, t._, Vs1), + handle_ball_from_below(Parent, G, RG, Vs1, Vs2). +% share this with parents, if we have evidence +handle_ball_from_below(V, _, _, Vs, Vs) :- + clpbn:get_atts(V,[evidence(_)]), !. +% propagate to kids, if we do not +handle_ball_from_below(V, G, RG, Vs0, Vs1) :- + dgraph_neighbors(V, RG, Parents), + propagate_ball_from_below(Parents, V, G, RG, Vs0, Vs1). + +propagate_ball_from_below([], V, G, RG, Vs0, Vs1) :- !, + dgraph_neighbors(V, G, Children), + throw_all_below(Children, G, RG, Vs0, Vs1). +propagate_ball_from_below(Parents, _V, G, RG, Vs0, Vs1) :- + throw_all_above(Parents, G, RG, Vs0, Vs1). + +all_top(T, Vs) :- + rb_visit(T, Pairs), + get_tops(Pairs, Vs). + +get_tops([], []). +get_tops([V-(T._)|Pairs], V.Vs) :- + T == t, !, + get_tops(Pairs, Vs). +get_tops([V-_|Pairs], V.Vs) :- + clpbn:get_atts(V,[evidence(_)]), !, + get_tops(Pairs, Vs). +get_tops(_.Pairs, Vs) :- + get_tops(Pairs, Vs). diff --git a/packages/CLPBN/clpbn/gibbs.yap b/packages/CLPBN/clpbn/gibbs.yap index 5e6323bf5..2a499b302 100644 --- a/packages/CLPBN/clpbn/gibbs.yap +++ b/packages/CLPBN/clpbn/gibbs.yap @@ -51,7 +51,7 @@ :- use_module(library('clpbn/connected'), [ - influences/4 + influences/3 ]). :- dynamic gibbs_params/3. @@ -73,7 +73,7 @@ init_gibbs_solver(GoalVs, Vs0, _, Vs) :- clean_up, term_variables(GoalVs, LVs), check_for_hidden_vars(Vs0, Vs0, Vs1), - influences(Vs1, LVs, _, Vs2), + influences(Vs1, LVs, Vs2), sort(Vs2,Vs). run_gibbs_solver(LVs, LPs, Vs) :- diff --git a/packages/CLPBN/clpbn/graphviz.yap b/packages/CLPBN/clpbn/graphviz.yap index 6d81cf3da..825fae3a1 100644 --- a/packages/CLPBN/clpbn/graphviz.yap +++ b/packages/CLPBN/clpbn/graphviz.yap @@ -22,7 +22,7 @@ output_var(Stream, V) :- Parents = [_|_], !, format(Stream, ' ',[]), output_parents(Stream, Parents), - format(' -> ',[]), + format(Stream,' -> ',[]), output_key(Stream,Key), nl(Stream). output_var(_, _). diff --git a/packages/CLPBN/clpbn/jt.yap b/packages/CLPBN/clpbn/jt.yap index bf5aef811..6828a002b 100644 --- a/packages/CLPBN/clpbn/jt.yap +++ b/packages/CLPBN/clpbn/jt.yap @@ -80,7 +80,7 @@ :- use_module(library('clpbn/connected'), [ init_influences/3, - influences/5 + influences/4 ]). @@ -98,7 +98,7 @@ init_jt_solver(LLVs, Vs0, _, State) :- init_jt_solver_for_questions([], _, _, []). init_jt_solver_for_questions([LLVs|MoreLLVs], G, RG, [state(JTree, Evidence)|State]) :- - influences(LLVs, _, NVs0, G, RG), + influences(LLVs, G, RG, NVs0), sort(NVs0, NVs), get_graph(NVs, BayesNet, CPTs, Evidence), build_jt(BayesNet, CPTs, JTree), diff --git a/packages/CLPBN/clpbn/table.yap b/packages/CLPBN/clpbn/table.yap index 0acd09478..9c07503bc 100644 --- a/packages/CLPBN/clpbn/table.yap +++ b/packages/CLPBN/clpbn/table.yap @@ -96,7 +96,7 @@ clpbn_table(F/N,M) :- Key =.. L1, atom_concat(F, '___tabled', NF), L2 = [_|Args], - S1 =.. [NF|Args], + _S1 =.. [NF|Args], L0 = [_|OArgs], S2 =.. [NF|OArgs], asserta(clpbn_table(S, M, S2)), diff --git a/packages/CLPBN/clpbn/vel.yap b/packages/CLPBN/clpbn/ve.yap similarity index 89% rename from packages/CLPBN/clpbn/vel.yap rename to packages/CLPBN/clpbn/ve.yap index 40940e272..41ed2b19f 100644 --- a/packages/CLPBN/clpbn/vel.yap +++ b/packages/CLPBN/clpbn/ve.yap @@ -14,10 +14,10 @@ *********************************/ -:- module(clpbn_vel, [vel/3, - check_if_vel_done/1, - init_vel_solver/4, - run_vel_solver/3]). +:- module(clpbn_ve, [ve/3, + check_if_ve_done/1, + init_ve_solver/4, + run_ve_solver/3]). :- attribute size/1, all_diffs/1. @@ -44,7 +44,7 @@ :- use_module(library('clpbn/connected'), [ init_influences/3, - influences/5 + influences/4 ]). :- use_module(library('clpbn/matrix_cpt_utils'), @@ -64,40 +64,41 @@ [check_for_agg_vars/2]). -check_if_vel_done(Var) :- +check_if_ve_done(Var) :- get_atts(Var, [size(_)]), !. % % implementation of the well known variable elimination algorithm % -vel([[]],_,_) :- !. -vel([LVs],Vs0,AllDiffs) :- - init_vel_solver([LVs], Vs0, AllDiffs, State), +ve([[]],_,_) :- !. +ve([LVs],Vs0,AllDiffs) :- + init_ve_solver([LVs], Vs0, AllDiffs, State), % variable elimination proper - run_vel_solver([LVs], [LPs], State), + run_ve_solver([LVs], [LPs], State), % bind Probs back to variables so that they can be output. clpbn_bind_vals([LVs],[LPs],AllDiffs). -init_vel_solver(Qs, Vs0, _, LVis) :- +init_ve_solver(Qs, Vs0, _, LVis) :- check_for_agg_vars(Vs0, Vs1), % LVi will have a list of CLPBN variables % Tables0 will have the full data on each variable init_influences(Vs1, G, RG), - init_vel_solver_for_questions(Qs, G, RG, _, LVis). + init_ve_solver_for_questions(Qs, G, RG, _, LVis). -init_vel_solver_for_questions([], _, _, [], []). -init_vel_solver_for_questions([Vs|MVs], G, RG, [NVs|MNVs0], [NVs|LVis]) :- - influences(Vs, _, NVs0, G, RG), +init_ve_solver_for_questions([], _, _, [], []). +init_ve_solver_for_questions([Vs|MVs], G, RG, [NVs|MNVs0], [NVs|LVis]) :- + influences(Vs, G, RG, NVs0), sort(NVs0, NVs), %clpbn_gviz:clpbn2gviz(user_error, test, NVs, Vs), - init_vel_solver_for_questions(MVs, G, RG, MNVs0, LVis). + init_ve_solver_for_questions(MVs, G, RG, MNVs0, LVis). % use a findall to recover space without needing for GC -run_vel_solver(LVs, LPs, LNVs) :- - findall(Ps, solve_vel(LVs, LNVs, Ps), LPs). +run_ve_solver(LVs, LPs, LNVs) :- + findall(Ps, solve_ve(LVs, LNVs, Ps), LPs). -solve_vel([LVs|_], [NVs0|_], Ps) :- -% length(NVs0, L), (L > 64 -> clpbn_gviz:clpbn2gviz(user_error,sort,NVs0,LVs) ; true ), +solve_ve([LVs|_], [NVs0|_], Ps) :- +% length(NVs0, L), (L > 415 -> clpbn_gviz:clpbn2gviz(user_error,sort,NVs0,LVs) ; true ), +% length(NVs0, L), writeln(+LVs:L), find_all_clpbn_vars(NVs0, NVs0, LV0, LVi, Tables0), sort(LV0, LV), % construct the graph @@ -108,8 +109,8 @@ solve_vel([LVs|_], [NVs0|_], Ps) :- % move from potentials back to probabilities normalise_CPT(Dist,MPs), list_from_CPT(MPs, Ps). -solve_vel([_|MoreLVs], [_|MoreLVis], Ps) :- - solve_vel(MoreLVs, MoreLVis, Ps). +solve_ve([_|MoreLVs], [_|MoreLVis], Ps) :- + solve_ve(MoreLVs, MoreLVis, Ps). exps([],[]). exps([L|LD],[O|LDE]) :- @@ -133,7 +134,7 @@ find_all_clpbn_vars([V|Vs], NVs0, [Var|LV], ProcessedVars, [table(I,Table,Parent % variables with evidence should not be processed. (var(Ev) -> Var = var(V,I,Sz,Vals,Parents,Ev,_,_), - vel_get_dist_size(V,Sz), + ve_get_dist_size(V,Sz), ProcessedVars = [Var|ProcessedVars0] ; ProcessedVars = ProcessedVars0 @@ -191,7 +192,7 @@ compute_size([tab(_,Vs,_)|Tabs],Vs0,K) :- multiply_sizes([],K,K). multiply_sizes([V|Vs],K0,K) :- - vel_get_dist_size(V, Sz), + ve_get_dist_size(V, Sz), KI is K0*Sz, multiply_sizes(Vs,KI,K). @@ -280,9 +281,9 @@ update_tables([tab(Tab0,Vs,Sz)|Tabs],[tab(Tab0,Vs,Sz)|NTabs],Table,V) :- update_tables([_|Tabs],NTabs,Table,V) :- update_tables(Tabs,NTabs,Table,V). -vel_get_dist_size(V,Sz) :- +ve_get_dist_size(V,Sz) :- get_atts(V, [size(Sz)]), !. -vel_get_dist_size(V,Sz) :- +ve_get_dist_size(V,Sz) :- clpbn:get_atts(V,dist(Id,_)), !, get_dist_domain_size(Id,Sz), put_atts(V, [size(Sz)]). diff --git a/packages/CLPBN/examples/sprinkler.yap b/packages/CLPBN/examples/sprinkler.yap index e8cc62742..f0be31fee 100644 --- a/packages/CLPBN/examples/sprinkler.yap +++ b/packages/CLPBN/examples/sprinkler.yap @@ -1,4 +1,6 @@ +:- style_check(all). + :- ensure_loaded(library(clpbn)). wet_grass(W) :- diff --git a/packages/CLPBN/learning/em.yap b/packages/CLPBN/learning/em.yap index 7e3f64c31..a09eac3f0 100644 --- a/packages/CLPBN/learning/em.yap +++ b/packages/CLPBN/learning/em.yap @@ -11,6 +11,7 @@ [clpbn_init_graph/1, clpbn_init_solver/5, clpbn_run_solver/4, + clpbn_finalize_solver/1, clpbn_flag/2]). :- use_module(library('clpbn/dists'), @@ -21,9 +22,6 @@ randomise_all_dists/0, uniformise_all_dists/0]). -:- use_module(library('clpbn/connected'), - [clpbn_subgraphs/2]). - :- use_module(library('clpbn/learning/learn_utils'), [run_all/1, clpbn_vars/2, @@ -53,6 +51,7 @@ em(Items, MaxError, MaxIts, Tables, Likelihood) :- catch(init_em(Items, State),Error,handle_em(Error)), em_loop(0, 0.0, State, MaxError, MaxIts, Likelihood, Tables), + clpbn_finalize_solver(State), assert(em_found(Tables, Likelihood)), fail. % get rid of new random variables the easy way :) @@ -90,7 +89,7 @@ init_em(Items, state( AllDists, AllDistInstances, MargVars, SolverVars)) :- em_loop(Its, Likelihood0, State, MaxError, MaxIts, LikelihoodF, FTables) :- estimate(State, LPs), maximise(State, Tables, LPs, Likelihood), - writeln(Likelihood:Its:Likelihood0:Tables), +% writeln(Likelihood:Its:Likelihood0:Tables), ( ( abs((Likelihood - Likelihood0)/Likelihood) < MaxError @@ -205,7 +204,7 @@ compute_parameters([Id-Samples|Dists], [Id-NewTable|Tables], MDistTable, Lik0, empty_dist(Id, Table0), add_samples(Samples, Table0, MDistTable), soften_sample(Table0, SoftenedTable), - matrix:matrix_sum(Table0,TotM), +% matrix:matrix_sum(Table0,TotM), normalise_counts(SoftenedTable, NewTable), compute_likelihood(Table0, NewTable, DeltaLik), dist_new_table(Id, NewTable), diff --git a/packages/CLPBN/learning/example/school_params.yap b/packages/CLPBN/learning/example/school_params.yap index f97119b77..6f96a9d38 100644 --- a/packages/CLPBN/learning/example/school_params.yap +++ b/packages/CLPBN/learning/example/school_params.yap @@ -4,13 +4,14 @@ :- [pos:train]. -:- ['~/Yap/work/packages/CLPBN/clpbn/examples/School/school_32']. +:- ['../../examples/School/school_32']. -:- ['~/Yap/work/packages/CLPBN/learning/em']. +:- use_module(library(clpbn/learning/em)). %:- clpbn:set_clpbn_flag(em_solver,gibbs). -:- clpbn:set_clpbn_flag(em_solver,jt). -%:- clpbn:set_clpbn_flag(em_solver,vel). +%:- clpbn:set_clpbn_flag(em_solver,jt). +:- clpbn:set_clpbn_flag(em_solver,ve). +%:- clpbn:set_clpbn_flag(em_solver,bp). timed_main :- statistics(runtime, _), @@ -24,10 +25,23 @@ main :- em(L,0.01,10,CPTs,Lik), writeln(Lik:CPTs). +debug_school :- + graph(L), + em(L,0.01,10,CPTs,Lik), + writeln(Lik:CPTs). + +run_queries([]). +run_queries(Q.L) :- + call(Q), + run_queries(L). + +graph([professor_ability(p0,_G131367),professor_ability(p1,h),professor_ability(p2,_G131377),professor_ability(p3,_G131382),professor_ability(p4,_G131387),professor_ability(p5,_G131392),professor_ability(p6,_G131397),professor_ability(p7,l),professor_ability(p8,m),professor_ability(p9,h),professor_ability(p10,m),professor_ability(p11,_G131422),professor_ability(p12,_G131427),professor_ability(p13,_G131432),professor_ability(p14,_G131437),professor_ability(p15,_G131442),professor_ability(p16,_G131447),professor_ability(p17,m),professor_ability(p18,l),professor_ability(p19,h),professor_ability(p20,h),professor_ability(p21,_G131472),professor_ability(p22,m),professor_ability(p23,m),professor_ability(p24,l),professor_ability(p25,m),professor_ability(p26,_G131497),professor_ability(p27,h),professor_ability(p28,h),professor_ability(p29,_G131512),professor_ability(p30,_G131517),professor_ability(p31,_G131522),professor_popularity(p0,h),professor_popularity(p1,h),professor_popularity(p2,_G131537),professor_popularity(p3,h),professor_popularity(p4,h),professor_popularity(p5,h),professor_popularity(p6,l),professor_popularity(p7,l),professor_popularity(p8,_G131567),professor_popularity(p9,_G131572),professor_popularity(p10,l),professor_popularity(p11,_G131582),professor_popularity(p12,h),professor_popularity(p13,l),professor_popularity(p14,_G131597),professor_popularity(p15,h),professor_popularity(p16,m),professor_popularity(p17,_G131612),professor_popularity(p18,_G131617),professor_popularity(p19,_G131622),professor_popularity(p20,_G131627),professor_popularity(p21,h),professor_popularity(p22,_G131637),professor_popularity(p23,_G131642),professor_popularity(p24,l),professor_popularity(p25,_G131652),professor_popularity(p26,_G131657),professor_popularity(p27,h),professor_popularity(p28,h),professor_popularity(p29,_G131672),professor_popularity(p30,m),professor_popularity(p31,_G131682),registration_grade(r0,a),registration_grade(r1,_G131692),registration_grade(r2,_G131697),registration_grade(r3,c),registration_grade(r4,c),registration_grade(r5,c),registration_grade(r6,_G131717),registration_grade(r7,a),registration_grade(r8,b),registration_grade(r9,_G131732),registration_grade(r10,_G131737),registration_grade(r11,a),registration_grade(r12,_G131747),registration_grade(r13,a),registration_grade(r14,_G131757),registration_grade(r15,b),registration_grade(r16,a),registration_grade(r17,b),registration_grade(r18,_G131777),registration_grade(r19,_G131782),registration_grade(r20,c),registration_grade(r21,_G131792),registration_grade(r22,_G131797),registration_grade(r23,_G131802),registration_grade(r24,b),registration_grade(r25,a),registration_grade(r26,_G131817),registration_grade(r27,_G131822),registration_grade(r28,c),registration_grade(r29,b),registration_grade(r30,c),registration_grade(r31,b),registration_grade(r32,_G131847),registration_grade(r33,a),registration_grade(r34,c),registration_grade(r35,c),registration_grade(r36,a),registration_grade(r37,a),registration_grade(r38,c),registration_grade(r39,a),registration_grade(r40,_G131887),registration_grade(r41,_G131892),registration_grade(r42,_G131897),registration_grade(r43,a),registration_grade(r44,a),registration_grade(r45,a),registration_grade(r46,a),registration_grade(r47,_G131922),registration_grade(r48,_G131927),registration_grade(r49,b),registration_grade(r50,b),registration_grade(r51,b),registration_grade(r52,_G131947),registration_grade(r53,a),registration_grade(r54,_G131957),registration_grade(r55,a),registration_grade(r56,c),registration_grade(r57,_G131972),registration_grade(r58,_G131977),registration_grade(r59,_G131982),registration_grade(r60,_G131987),registration_grade(r61,a),registration_grade(r62,_G131997),registration_grade(r63,b),registration_grade(r64,b),registration_grade(r65,b),registration_grade(r66,_G132017),registration_grade(r67,b),registration_grade(r68,a),registration_grade(r69,_G132032),registration_grade(r70,_G132037),registration_grade(r71,_G132042),registration_grade(r72,_G132047),registration_grade(r73,_G132052),registration_grade(r74,a),registration_grade(r75,_G132062),registration_grade(r76,_G132067),registration_grade(r77,_G132072),registration_grade(r78,b),registration_grade(r79,_G132082),registration_grade(r80,_G132087),registration_grade(r81,_G132092),registration_grade(r82,_G132097),registration_grade(r83,_G132102),registration_grade(r84,_G132107),registration_grade(r85,b),registration_grade(r86,_G132117),registration_grade(r87,b),registration_grade(r88,_G132127),registration_grade(r89,_G132132),registration_grade(r90,_G132137),registration_grade(r91,a),registration_grade(r92,_G132147),registration_grade(r93,_G132152),registration_grade(r94,_G132157),registration_grade(r95,_G132162),registration_grade(r96,_G132167),registration_grade(r97,a),registration_grade(r98,b),registration_grade(r99,b),registration_grade(r100,a),registration_grade(r101,a),registration_grade(r102,a),registration_grade(r103,_G132202),registration_grade(r104,_G132207),registration_grade(r105,c),registration_grade(r106,b),registration_grade(r107,b),registration_grade(r108,_G132227),registration_grade(r109,_G132232),registration_grade(r110,a),registration_grade(r111,_G132242),registration_grade(r112,_G132247),registration_grade(r113,_G132252),registration_grade(r114,_G132257),registration_grade(r115,d),registration_grade(r116,b),registration_grade(r117,_G132272),registration_grade(r118,_G132277),registration_grade(r119,b),registration_grade(r120,b),registration_grade(r121,_G132292),registration_grade(r122,_G132297),registration_grade(r123,a),registration_grade(r124,a),registration_grade(r125,_G132312),registration_grade(r126,_G132317),registration_grade(r127,b),registration_grade(r128,a),registration_grade(r129,c),registration_grade(r130,a),registration_grade(r131,a),registration_grade(r132,b),registration_grade(r133,_G132352),registration_grade(r134,_G132357),registration_grade(r135,_G132362),registration_grade(r136,_G132367),registration_grade(r137,b),registration_grade(r138,a),registration_grade(r139,_G132382),registration_grade(r140,_G132387),registration_grade(r141,b),registration_grade(r142,_G132397),registration_grade(r143,b),registration_grade(r144,c),registration_grade(r145,b),registration_grade(r146,_G132417),registration_grade(r147,_G132422),registration_grade(r148,_G132427),registration_grade(r149,a),registration_grade(r150,_G132437),registration_grade(r151,a),registration_grade(r152,_G132447),registration_grade(r153,_G132452),registration_grade(r154,a),registration_grade(r155,c),registration_grade(r156,b),registration_grade(r157,b),registration_grade(r158,c),registration_grade(r159,b),registration_grade(r160,a),registration_grade(r161,_G132492),registration_grade(r162,_G132497),registration_grade(r163,_G132502),registration_grade(r164,b),registration_grade(r165,b),registration_grade(r166,_G132517),registration_grade(r167,a),registration_grade(r168,a),registration_grade(r169,_G132532),registration_grade(r170,_G132537),registration_grade(r171,a),registration_grade(r172,c),registration_grade(r173,b),registration_grade(r174,_G132557),registration_grade(r175,_G132562),registration_grade(r176,b),registration_grade(r177,c),registration_grade(r178,b),registration_grade(r179,d),registration_grade(r180,c),registration_grade(r181,a),registration_grade(r182,b),registration_grade(r183,a),registration_grade(r184,_G132607),registration_grade(r185,_G132612),registration_grade(r186,c),registration_grade(r187,a),registration_grade(r188,a),registration_grade(r189,_G132632),registration_grade(r190,_G132637),registration_grade(r191,_G132642),registration_grade(r192,b),registration_grade(r193,c),registration_grade(r194,b),registration_grade(r195,_G132662),registration_grade(r196,_G132667),registration_grade(r197,_G132672),registration_grade(r198,_G132677),registration_grade(r199,b),registration_grade(r200,_G132687),registration_grade(r201,c),registration_grade(r202,a),registration_grade(r203,_G132702),registration_grade(r204,_G132707),registration_grade(r205,_G132712),registration_grade(r206,a),registration_grade(r207,a),registration_grade(r208,_G132727),registration_grade(r209,b),registration_grade(r210,a),registration_grade(r211,d),registration_grade(r212,_G132747),registration_grade(r213,_G132752),registration_grade(r214,_G132757),registration_grade(r215,a),registration_grade(r216,_G132767),registration_grade(r217,_G132772),registration_grade(r218,_G132777),registration_grade(r219,_G132782),registration_grade(r220,_G132787),registration_grade(r221,b),registration_grade(r222,c),registration_grade(r223,_G132802),registration_grade(r224,_G132807),registration_grade(r225,b),registration_grade(r226,d),registration_grade(r227,b),registration_grade(r228,c),registration_grade(r229,b),registration_grade(r230,a),registration_grade(r231,_G132842),registration_grade(r232,_G132847),registration_grade(r233,b),registration_grade(r234,_G132857),registration_grade(r235,c),registration_grade(r236,b),registration_grade(r237,_G132872),registration_grade(r238,d),registration_grade(r239,b),registration_grade(r240,b),registration_grade(r241,_G132892),registration_grade(r242,b),registration_grade(r243,_G132902),registration_grade(r244,b),registration_grade(r245,a),registration_grade(r246,b),registration_grade(r247,_G132922),registration_grade(r248,b),registration_grade(r249,_G132932),registration_grade(r250,a),registration_grade(r251,_G132942),registration_grade(r252,b),registration_grade(r253,_G132952),registration_grade(r254,_G132957),registration_grade(r255,_G132962),registration_grade(r256,_G132967),registration_grade(r257,b),registration_grade(r258,_G132977),registration_grade(r259,a),registration_grade(r260,b),registration_grade(r261,a),registration_grade(r262,_G132997),registration_grade(r263,_G133002),registration_grade(r264,_G133007),registration_grade(r265,a),registration_grade(r266,_G133017),registration_grade(r267,_G133022),registration_grade(r268,c),registration_grade(r269,a),registration_grade(r270,_G133037),registration_grade(r271,_G133042),registration_grade(r272,_G133047),registration_grade(r273,b),registration_grade(r274,c),registration_grade(r275,a),registration_grade(r276,a),registration_grade(r277,_G133072),registration_grade(r278,_G133077),registration_grade(r279,_G133082),registration_grade(r280,_G133087),registration_grade(r281,b),registration_grade(r282,d),registration_grade(r283,_G133102),registration_grade(r284,b),registration_grade(r285,_G133112),registration_grade(r286,_G133117),registration_grade(r287,_G133122),registration_grade(r288,_G133127),registration_grade(r289,_G133132),registration_grade(r290,b),registration_grade(r291,c),registration_grade(r292,_G133147),registration_grade(r293,_G133152),registration_grade(r294,_G133157),registration_grade(r295,a),registration_grade(r296,b),registration_grade(r297,_G133172),registration_grade(r298,a),registration_grade(r299,a),registration_grade(r300,_G133187),registration_grade(r301,b),registration_grade(r302,b),registration_grade(r303,_G133202),registration_grade(r304,a),registration_grade(r305,_G133212),registration_grade(r306,_G133217),registration_grade(r307,_G133222),registration_grade(r308,c),registration_grade(r309,_G133232),registration_grade(r310,a),registration_grade(r311,a),registration_grade(r312,a),registration_grade(r313,_G133252),registration_grade(r314,_G133257),registration_grade(r315,c),registration_grade(r316,_G133267),registration_grade(r317,_G133272),registration_grade(r318,c),registration_grade(r319,c),registration_grade(r320,b),registration_grade(r321,b),registration_grade(r322,_G133297),registration_grade(r323,c),registration_grade(r324,b),registration_grade(r325,b),registration_grade(r326,_G133317),registration_grade(r327,c),registration_grade(r328,b),registration_grade(r329,_G133332),registration_grade(r330,_G133337),registration_grade(r331,_G133342),registration_grade(r332,_G133347),registration_grade(r333,_G133352),registration_grade(r334,_G133357),registration_grade(r335,d),registration_grade(r336,b),registration_grade(r337,b),registration_grade(r338,b),registration_grade(r339,_G133382),registration_grade(r340,_G133387),registration_grade(r341,_G133392),registration_grade(r342,_G133397),registration_grade(r343,a),registration_grade(r344,c),registration_grade(r345,_G133412),registration_grade(r346,b),registration_grade(r347,_G133422),registration_grade(r348,a),registration_grade(r349,a),registration_grade(r350,b),registration_grade(r351,b),registration_grade(r352,_G133447),registration_grade(r353,_G133452),registration_grade(r354,_G133457),registration_grade(r355,_G133462),registration_grade(r356,b),registration_grade(r357,b),registration_grade(r358,_G133477),registration_grade(r359,a),registration_grade(r360,_G133487),registration_grade(r361,_G133492),registration_grade(r362,c),registration_grade(r363,_G133502),registration_grade(r364,b),registration_grade(r365,_G133512),registration_grade(r366,b),registration_grade(r367,_G133522),registration_grade(r368,a),registration_grade(r369,c),registration_grade(r370,b),registration_grade(r371,_G133542),registration_grade(r372,_G133547),registration_grade(r373,_G133552),registration_grade(r374,b),registration_grade(r375,b),registration_grade(r376,a),registration_grade(r377,a),registration_grade(r378,a),registration_grade(r379,_G133582),registration_grade(r380,_G133587),registration_grade(r381,c),registration_grade(r382,_G133597),registration_grade(r383,_G133602),registration_grade(r384,b),registration_grade(r385,_G133612),registration_grade(r386,d),registration_grade(r387,_G133622),registration_grade(r388,_G133627),registration_grade(r389,a),registration_grade(r390,_G133637),registration_grade(r391,_G133642),registration_grade(r392,_G133647),registration_grade(r393,b),registration_grade(r394,c),registration_grade(r395,b),registration_grade(r396,_G133667),registration_grade(r397,a),registration_grade(r398,_G133677),registration_grade(r399,_G133682),registration_grade(r400,_G133687),registration_grade(r401,c),registration_grade(r402,_G133697),registration_grade(r403,_G133702),registration_grade(r404,a),registration_grade(r405,_G133712),registration_grade(r406,_G133717),registration_grade(r407,_G133722),registration_grade(r408,a),registration_grade(r409,a),registration_grade(r410,b),registration_grade(r411,b),registration_grade(r412,_G133747),registration_grade(r413,a),registration_grade(r414,_G133757),registration_grade(r415,_G133762),registration_grade(r416,_G133767),registration_grade(r417,_G133772),registration_grade(r418,a),registration_grade(r419,a),registration_grade(r420,a),registration_grade(r421,c),registration_grade(r422,b),registration_grade(r423,_G133802),registration_grade(r424,a),registration_grade(r425,b),registration_grade(r426,c),registration_grade(r427,c),registration_grade(r428,_G133827),registration_grade(r429,c),registration_grade(r430,_G133837),registration_grade(r431,_G133842),registration_grade(r432,c),registration_grade(r433,_G133852),registration_grade(r434,a),registration_grade(r435,_G133862),registration_grade(r436,_G133867),registration_grade(r437,c),registration_grade(r438,b),registration_grade(r439,_G133882),registration_grade(r440,c),registration_grade(r441,a),registration_grade(r442,c),registration_grade(r443,_G133902),registration_grade(r444,_G133907),registration_grade(r445,_G133912),registration_grade(r446,_G133917),registration_grade(r447,d),registration_grade(r448,_G133927),registration_grade(r449,b),registration_grade(r450,_G133937),registration_grade(r451,_G133942),registration_grade(r452,b),registration_grade(r453,_G133952),registration_grade(r454,_G133957),registration_grade(r455,_G133962),registration_grade(r456,c),registration_grade(r457,_G133972),registration_grade(r458,_G133977),registration_grade(r459,_G133982),registration_grade(r460,_G133987),registration_grade(r461,_G133992),registration_grade(r462,a),registration_grade(r463,d),registration_grade(r464,a),registration_grade(r465,_G134012),registration_grade(r466,_G134017),registration_grade(r467,b),registration_grade(r468,_G134027),registration_grade(r469,_G134032),registration_grade(r470,_G134037),registration_grade(r471,_G134042),registration_grade(r472,a),registration_grade(r473,c),registration_grade(r474,b),registration_grade(r475,_G134062),registration_grade(r476,_G134067),registration_grade(r477,b),registration_grade(r478,a),registration_grade(r479,b),registration_grade(r480,a),registration_grade(r481,_G134092),registration_grade(r482,b),registration_grade(r483,a),registration_grade(r484,_G134107),registration_grade(r485,_G134112),registration_grade(r486,_G134117),registration_grade(r487,_G134122),registration_grade(r488,a),registration_grade(r489,_G134132),registration_grade(r490,_G134137),registration_grade(r491,c),registration_grade(r492,b),registration_grade(r493,a),registration_grade(r494,_G134157),registration_grade(r495,_G134162),registration_grade(r496,_G134167),registration_grade(r497,c),registration_grade(r498,_G134177),registration_grade(r499,c),registration_grade(r500,b),registration_grade(r501,_G134192),registration_grade(r502,a),registration_grade(r503,_G134202),registration_grade(r504,_G134207),registration_grade(r505,_G134212),registration_grade(r506,c),registration_grade(r507,a),registration_grade(r508,_G134227),registration_grade(r509,_G134232),registration_grade(r510,_G134237),registration_grade(r511,_G134242),registration_grade(r512,b),registration_grade(r513,_G134252),registration_grade(r514,_G134257),registration_grade(r515,c),registration_grade(r516,_G134267),registration_grade(r517,_G134272),registration_grade(r518,_G134277),registration_grade(r519,a),registration_grade(r520,b),registration_grade(r521,a),registration_grade(r522,b),registration_grade(r523,_G134302),registration_grade(r524,b),registration_grade(r525,c),registration_grade(r526,c),registration_grade(r527,c),registration_grade(r528,a),registration_grade(r529,_G134332),registration_grade(r530,a),registration_grade(r531,_G134342),registration_grade(r532,a),registration_grade(r533,_G134352),registration_grade(r534,b),registration_grade(r535,c),registration_grade(r536,a),registration_grade(r537,_G134372),registration_grade(r538,_G134377),registration_grade(r539,_G134382),registration_grade(r540,_G134387),registration_grade(r541,c),registration_grade(r542,a),registration_grade(r543,a),registration_grade(r544,b),registration_grade(r545,a),registration_grade(r546,b),registration_grade(r547,_G134422),registration_grade(r548,c),registration_grade(r549,_G134432),registration_grade(r550,a),registration_grade(r551,_G134442),registration_grade(r552,c),registration_grade(r553,_G134452),registration_grade(r554,b),registration_grade(r555,_G134462),registration_grade(r556,_G134467),registration_grade(r557,_G134472),registration_grade(r558,_G134477),registration_grade(r559,b),registration_grade(r560,_G134487),registration_grade(r561,a),registration_grade(r562,_G134497),registration_grade(r563,_G134502),registration_grade(r564,_G134507),registration_grade(r565,d),registration_grade(r566,c),registration_grade(r567,a),registration_grade(r568,a),registration_grade(r569,_G134532),registration_grade(r570,_G134537),registration_grade(r571,_G134542),registration_grade(r572,b),registration_grade(r573,a),registration_grade(r574,_G134557),registration_grade(r575,a),registration_grade(r576,_G134567),registration_grade(r577,_G134572),registration_grade(r578,b),registration_grade(r579,a),registration_grade(r580,_G134587),registration_grade(r581,_G134592),registration_grade(r582,_G134597),registration_grade(r583,_G134602),registration_grade(r584,a),registration_grade(r585,c),registration_grade(r586,b),registration_grade(r587,_G134622),registration_grade(r588,_G134627),registration_grade(r589,c),registration_grade(r590,_G134637),registration_grade(r591,c),registration_grade(r592,b),registration_grade(r593,_G134652),registration_grade(r594,c),registration_grade(r595,b),registration_grade(r596,_G134667),registration_grade(r597,_G134672),registration_grade(r598,a),registration_grade(r599,_G134682),registration_grade(r600,a),registration_grade(r601,b),registration_grade(r602,_G134697),registration_grade(r603,d),registration_grade(r604,_G134707),registration_grade(r605,a),registration_grade(r606,_G134717),registration_grade(r607,_G134722),registration_grade(r608,a),registration_grade(r609,b),registration_grade(r610,_G134737),registration_grade(r611,_G134742),registration_grade(r612,c),registration_grade(r613,_G134752),registration_grade(r614,_G134757),registration_grade(r615,b),registration_grade(r616,_G134767),registration_grade(r617,a),registration_grade(r618,_G134777),registration_grade(r619,_G134782),registration_grade(r620,a),registration_grade(r621,_G134792),registration_grade(r622,b),registration_grade(r623,_G134802),registration_grade(r624,a),registration_grade(r625,_G134812),registration_grade(r626,a),registration_grade(r627,_G134822),registration_grade(r628,a),registration_grade(r629,_G134832),registration_grade(r630,_G134837),registration_grade(r631,_G134842),registration_grade(r632,a),registration_grade(r633,_G134852),registration_grade(r634,b),registration_grade(r635,_G134862),registration_grade(r636,d),registration_grade(r637,c),registration_grade(r638,a),registration_grade(r639,b),registration_grade(r640,_G134887),registration_grade(r641,_G134892),registration_grade(r642,c),registration_grade(r643,_G134902),registration_grade(r644,_G134907),registration_grade(r645,_G134912),registration_grade(r646,_G134917),registration_grade(r647,b),registration_grade(r648,a),registration_grade(r649,_G134932),registration_grade(r650,c),registration_grade(r651,b),registration_grade(r652,b),registration_grade(r653,_G134952),registration_grade(r654,b),registration_grade(r655,a),registration_grade(r656,_G134967),registration_grade(r657,a),registration_grade(r658,a),registration_grade(r659,a),registration_grade(r660,a),registration_grade(r661,c),registration_grade(r662,_G134997),registration_grade(r663,a),registration_grade(r664,_G135007),registration_grade(r665,a),registration_grade(r666,b),registration_grade(r667,_G135022),registration_grade(r668,d),registration_grade(r669,b),registration_grade(r670,a),registration_grade(r671,_G135042),registration_grade(r672,c),registration_grade(r673,a),registration_grade(r674,_G135057),registration_grade(r675,_G135062),registration_grade(r676,a),registration_grade(r677,a),registration_grade(r678,a),registration_grade(r679,a),registration_grade(r680,_G135087),registration_grade(r681,_G135092),registration_grade(r682,_G135097),registration_grade(r683,b),registration_grade(r684,_G135107),registration_grade(r685,_G135112),registration_grade(r686,b),registration_grade(r687,a),registration_grade(r688,c),registration_grade(r689,_G135132),registration_grade(r690,a),registration_grade(r691,_G135142),registration_grade(r692,_G135147),registration_grade(r693,b),registration_grade(r694,_G135157),registration_grade(r695,_G135162),registration_grade(r696,a),registration_grade(r697,_G135172),registration_grade(r698,_G135177),registration_grade(r699,_G135182),registration_grade(r700,a),registration_grade(r701,_G135192),registration_grade(r702,a),registration_grade(r703,_G135202),registration_grade(r704,c),registration_grade(r705,b),registration_grade(r706,_G135217),registration_grade(r707,a),registration_grade(r708,b),registration_grade(r709,_G135232),registration_grade(r710,_G135237),registration_grade(r711,b),registration_grade(r712,_G135247),registration_grade(r713,a),registration_grade(r714,_G135257),registration_grade(r715,a),registration_grade(r716,a),registration_grade(r717,a),registration_grade(r718,a),registration_grade(r719,_G135282),registration_grade(r720,_G135287),registration_grade(r721,_G135292),registration_grade(r722,_G135297),registration_grade(r723,_G135302),registration_grade(r724,_G135307),registration_grade(r725,c),registration_grade(r726,a),registration_grade(r727,_G135322),registration_grade(r728,b),registration_grade(r729,_G135332),registration_grade(r730,_G135337),registration_grade(r731,_G135342),registration_grade(r732,a),registration_grade(r733,a),registration_grade(r734,b),registration_grade(r735,_G135362),registration_grade(r736,a),registration_grade(r737,_G135372),registration_grade(r738,_G135377),registration_grade(r739,a),registration_grade(r740,_G135387),registration_grade(r741,_G135392),registration_grade(r742,_G135397),registration_grade(r743,_G135402),registration_grade(r744,a),registration_grade(r745,b),registration_grade(r746,_G135417),registration_grade(r747,_G135422),registration_grade(r748,b),registration_grade(r749,c),registration_grade(r750,_G135437),registration_grade(r751,c),registration_grade(r752,_G135447),registration_grade(r753,c),registration_grade(r754,_G135457),registration_grade(r755,c),registration_grade(r756,_G135467),registration_grade(r757,_G135472),registration_grade(r758,b),registration_grade(r759,_G135482),registration_grade(r760,_G135487),registration_grade(r761,a),registration_grade(r762,_G135497),registration_grade(r763,a),registration_grade(r764,a),registration_grade(r765,a),registration_grade(r766,_G135517),registration_grade(r767,c),registration_grade(r768,_G135527),registration_grade(r769,_G135532),registration_grade(r770,b),registration_grade(r771,_G135542),registration_grade(r772,a),registration_grade(r773,b),registration_grade(r774,b),registration_grade(r775,a),registration_grade(r776,_G135567),registration_grade(r777,c),registration_grade(r778,c),registration_grade(r779,b),registration_grade(r780,a),registration_grade(r781,_G135592),registration_grade(r782,a),registration_grade(r783,_G135602),registration_grade(r784,_G135607),registration_grade(r785,_G135612),registration_grade(r786,c),registration_grade(r787,a),registration_grade(r788,_G135627),registration_grade(r789,_G135632),registration_grade(r790,b),registration_grade(r791,b),registration_grade(r792,_G135647),registration_grade(r793,_G135652),registration_grade(r794,_G135657),registration_grade(r795,_G135662),registration_grade(r796,_G135667),registration_grade(r797,a),registration_grade(r798,_G135677),registration_grade(r799,_G135682),registration_grade(r800,_G135687),registration_grade(r801,b),registration_grade(r802,_G135697),registration_grade(r803,b),registration_grade(r804,_G135707),registration_grade(r805,_G135712),registration_grade(r806,_G135717),registration_grade(r807,a),registration_grade(r808,_G135727),registration_grade(r809,_G135732),registration_grade(r810,_G135737),registration_grade(r811,d),registration_grade(r812,c),registration_grade(r813,_G135752),registration_grade(r814,c),registration_grade(r815,_G135762),registration_grade(r816,_G135767),registration_grade(r817,a),registration_grade(r818,_G135777),registration_grade(r819,b),registration_grade(r820,d),registration_grade(r821,b),registration_grade(r822,_G135797),registration_grade(r823,a),registration_grade(r824,_G135807),registration_grade(r825,b),registration_grade(r826,b),registration_grade(r827,_G135822),registration_grade(r828,_G135827),registration_grade(r829,b),registration_grade(r830,_G135837),registration_grade(r831,_G135842),registration_grade(r832,b),registration_grade(r833,b),registration_grade(r834,_G135857),registration_grade(r835,a),registration_grade(r836,a),registration_grade(r837,c),registration_grade(r838,_G135877),registration_grade(r839,b),registration_grade(r840,b),registration_grade(r841,a),registration_grade(r842,a),registration_grade(r843,b),registration_grade(r844,_G135907),registration_grade(r845,c),registration_grade(r846,b),registration_grade(r847,b),registration_grade(r848,_G135927),registration_grade(r849,_G135932),registration_grade(r850,_G135937),registration_grade(r851,_G135942),registration_grade(r852,_G135947),registration_grade(r853,_G135952),registration_grade(r854,_G135957),registration_grade(r855,_G135962),registration_grade(r856,_G135967),student_intelligence(s0,l),student_intelligence(s1,_G135977),student_intelligence(s2,_G135982),student_intelligence(s3,h),student_intelligence(s4,h),student_intelligence(s5,h),student_intelligence(s6,m),student_intelligence(s7,h),student_intelligence(s8,h),student_intelligence(s9,_G136017),student_intelligence(s10,m),student_intelligence(s11,_G136027),student_intelligence(s12,h),student_intelligence(s13,h),student_intelligence(s14,_G136042),student_intelligence(s15,_G136047),student_intelligence(s16,_G136052),student_intelligence(s17,m),student_intelligence(s18,m),student_intelligence(s19,_G136067),student_intelligence(s20,m),student_intelligence(s21,_G136077),student_intelligence(s22,h),student_intelligence(s23,_G136087),student_intelligence(s24,_G136092),student_intelligence(s25,h),student_intelligence(s26,_G136102),student_intelligence(s27,m),student_intelligence(s28,m),student_intelligence(s29,_G136117),student_intelligence(s30,h),student_intelligence(s31,m),student_intelligence(s32,m),student_intelligence(s33,_G136137),student_intelligence(s34,l),student_intelligence(s35,m),student_intelligence(s36,l),student_intelligence(s37,_G136157),student_intelligence(s38,_G136162),student_intelligence(s39,h),student_intelligence(s40,h),student_intelligence(s41,m),student_intelligence(s42,_G136182),student_intelligence(s43,_G136187),student_intelligence(s44,_G136192),student_intelligence(s45,_G136197),student_intelligence(s46,l),student_intelligence(s47,h),student_intelligence(s48,_G136212),student_intelligence(s49,_G136217),student_intelligence(s50,_G136222),student_intelligence(s51,_G136227),student_intelligence(s52,_G136232),student_intelligence(s53,m),student_intelligence(s54,_G136242),student_intelligence(s55,h),student_intelligence(s56,l),student_intelligence(s57,_G136257),student_intelligence(s58,h),student_intelligence(s59,_G136267),student_intelligence(s60,m),student_intelligence(s61,h),student_intelligence(s62,_G136282),student_intelligence(s63,_G136287),student_intelligence(s64,l),student_intelligence(s65,_G136297),student_intelligence(s66,h),student_intelligence(s67,m),student_intelligence(s68,_G136312),student_intelligence(s69,_G136317),student_intelligence(s70,_G136322),student_intelligence(s71,m),student_intelligence(s72,_G136332),student_intelligence(s73,_G136337),student_intelligence(s74,_G136342),student_intelligence(s75,h),student_intelligence(s76,h),student_intelligence(s77,h),student_intelligence(s78,_G136362),student_intelligence(s79,m),student_intelligence(s80,_G136372),student_intelligence(s81,_G136377),student_intelligence(s82,_G136382),student_intelligence(s83,_G136387),student_intelligence(s84,_G136392),student_intelligence(s85,_G136397),student_intelligence(s86,_G136402),student_intelligence(s87,h),student_intelligence(s88,h),student_intelligence(s89,_G136417),student_intelligence(s90,h),student_intelligence(s91,_G136427),student_intelligence(s92,h),student_intelligence(s93,_G136437),student_intelligence(s94,_G136442),student_intelligence(s95,_G136447),student_intelligence(s96,_G136452),student_intelligence(s97,_G136457),student_intelligence(s98,_G136462),student_intelligence(s99,l),student_intelligence(s100,h),student_intelligence(s101,_G136477),student_intelligence(s102,m),student_intelligence(s103,h),student_intelligence(s104,l),student_intelligence(s105,m),student_intelligence(s106,_G136502),student_intelligence(s107,l),student_intelligence(s108,m),student_intelligence(s109,_G136517),student_intelligence(s110,m),student_intelligence(s111,h),student_intelligence(s112,m),student_intelligence(s113,h),student_intelligence(s114,_G136542),student_intelligence(s115,h),student_intelligence(s116,_G136552),student_intelligence(s117,m),student_intelligence(s118,_G136562),student_intelligence(s119,h),student_intelligence(s120,h),student_intelligence(s121,_G136577),student_intelligence(s122,m),student_intelligence(s123,_G136587),student_intelligence(s124,h),student_intelligence(s125,_G136597),student_intelligence(s126,m),student_intelligence(s127,m),student_intelligence(s128,_G136612),student_intelligence(s129,h),student_intelligence(s130,_G136622),student_intelligence(s131,h),student_intelligence(s132,_G136632),student_intelligence(s133,_G136637),student_intelligence(s134,h),student_intelligence(s135,_G136647),student_intelligence(s136,m),student_intelligence(s137,m),student_intelligence(s138,l),student_intelligence(s139,h),student_intelligence(s140,_G136672),student_intelligence(s141,_G136677),student_intelligence(s142,_G136682),student_intelligence(s143,_G136687),student_intelligence(s144,h),student_intelligence(s145,h),student_intelligence(s146,m),student_intelligence(s147,m),student_intelligence(s148,_G136712),student_intelligence(s149,_G136717),student_intelligence(s150,l),student_intelligence(s151,h),student_intelligence(s152,h),student_intelligence(s153,_G136737),student_intelligence(s154,_G136742),student_intelligence(s155,_G136747),student_intelligence(s156,m),student_intelligence(s157,m),student_intelligence(s158,h),student_intelligence(s159,_G136767),student_intelligence(s160,_G136772),student_intelligence(s161,_G136777),student_intelligence(s162,h),student_intelligence(s163,m),student_intelligence(s164,_G136792),student_intelligence(s165,m),student_intelligence(s166,m),student_intelligence(s167,_G136807),student_intelligence(s168,_G136812),student_intelligence(s169,_G136817),student_intelligence(s170,_G136822),student_intelligence(s171,m),student_intelligence(s172,_G136832),student_intelligence(s173,h),student_intelligence(s174,h),student_intelligence(s175,_G136847),student_intelligence(s176,_G136852),student_intelligence(s177,m),student_intelligence(s178,_G136862),student_intelligence(s179,m),student_intelligence(s180,m),student_intelligence(s181,h),student_intelligence(s182,m),student_intelligence(s183,h),student_intelligence(s184,_G136892),student_intelligence(s185,m),student_intelligence(s186,m),student_intelligence(s187,m),student_intelligence(s188,_G136912),student_intelligence(s189,m),student_intelligence(s190,h),student_intelligence(s191,l),student_intelligence(s192,_G136932),student_intelligence(s193,m),student_intelligence(s194,m),student_intelligence(s195,_G136947),student_intelligence(s196,h),student_intelligence(s197,_G136957),student_intelligence(s198,h),student_intelligence(s199,m),student_intelligence(s200,h),student_intelligence(s201,_G136977),student_intelligence(s202,h),student_intelligence(s203,m),student_intelligence(s204,h),student_intelligence(s205,_G136997),student_intelligence(s206,_G137002),student_intelligence(s207,h),student_intelligence(s208,_G137012),student_intelligence(s209,h),student_intelligence(s210,_G137022),student_intelligence(s211,_G137027),student_intelligence(s212,m),student_intelligence(s213,h),student_intelligence(s214,h),student_intelligence(s215,_G137047),student_intelligence(s216,h),student_intelligence(s217,_G137057),student_intelligence(s218,h),student_intelligence(s219,_G137067),student_intelligence(s220,_G137072),student_intelligence(s221,h),student_intelligence(s222,_G137082),student_intelligence(s223,_G137087),student_intelligence(s224,l),student_intelligence(s225,l),student_intelligence(s226,m),student_intelligence(s227,_G137107),student_intelligence(s228,h),student_intelligence(s229,_G137117),student_intelligence(s230,_G137122),student_intelligence(s231,_G137127),student_intelligence(s232,m),student_intelligence(s233,_G137137),student_intelligence(s234,_G137142),student_intelligence(s235,_G137147),student_intelligence(s236,_G137152),student_intelligence(s237,h),student_intelligence(s238,h),student_intelligence(s239,h),student_intelligence(s240,_G137172),student_intelligence(s241,_G137177),student_intelligence(s242,l),student_intelligence(s243,_G137187),student_intelligence(s244,_G137192),student_intelligence(s245,l),student_intelligence(s246,_G137202),student_intelligence(s247,h),student_intelligence(s248,m),student_intelligence(s249,_G137217),student_intelligence(s250,m),student_intelligence(s251,_G137227),student_intelligence(s252,_G137232),student_intelligence(s253,m),student_intelligence(s254,_G137242),student_intelligence(s255,m),course_difficulty(c0,_G137252),course_difficulty(c1,m),course_difficulty(c2,_G137262),course_difficulty(c3,_G137267),course_difficulty(c4,_G137272),course_difficulty(c5,l),course_difficulty(c6,m),course_difficulty(c7,h),course_difficulty(c8,h),course_difficulty(c9,_G137297),course_difficulty(c10,m),course_difficulty(c11,_G137307),course_difficulty(c12,m),course_difficulty(c13,_G137317),course_difficulty(c14,m),course_difficulty(c15,_G137327),course_difficulty(c16,l),course_difficulty(c17,h),course_difficulty(c18,_G137342),course_difficulty(c19,l),course_difficulty(c20,_G137352),course_difficulty(c21,_G137357),course_difficulty(c22,_G137362),course_difficulty(c23,_G137367),course_difficulty(c24,_G137372),course_difficulty(c25,m),course_difficulty(c26,_G137382),course_difficulty(c27,_G137387),course_difficulty(c28,m),course_difficulty(c29,_G137397),course_difficulty(c30,_G137402),course_difficulty(c31,m),course_difficulty(c32,l),course_difficulty(c33,m),course_difficulty(c34,_G137422),course_difficulty(c35,_G137427),course_difficulty(c36,h),course_difficulty(c37,m),course_difficulty(c38,m),course_difficulty(c39,_G137447),course_difficulty(c40,h),course_difficulty(c41,_G137457),course_difficulty(c42,_G137462),course_difficulty(c43,m),course_difficulty(c44,m),course_difficulty(c45,_G137477),course_difficulty(c46,m),course_difficulty(c47,_G137487),course_difficulty(c48,m),course_difficulty(c49,l),course_difficulty(c50,_G137502),course_difficulty(c51,h),course_difficulty(c52,_G137512),course_difficulty(c53,_G137517),course_difficulty(c54,_G137522),course_difficulty(c55,h),course_difficulty(c56,_G137532),course_difficulty(c57,_G137537),course_difficulty(c58,_G137542),course_difficulty(c59,m),course_difficulty(c60,_G137552),course_difficulty(c61,m),course_difficulty(c62,l),course_difficulty(c63,_G137567),registration_satisfaction(r0,_G137572),registration_satisfaction(r1,l),registration_satisfaction(r2,_G137582),registration_satisfaction(r3,_G137587),registration_satisfaction(r4,h),registration_satisfaction(r5,h),registration_satisfaction(r6,_G137602),registration_satisfaction(r7,h),registration_satisfaction(r8,_G137612),registration_satisfaction(r9,h),registration_satisfaction(r10,_G137622),registration_satisfaction(r11,_G137627),registration_satisfaction(r12,_G137632),registration_satisfaction(r13,h),registration_satisfaction(r14,m),registration_satisfaction(r15,h),registration_satisfaction(r16,h),registration_satisfaction(r17,l),registration_satisfaction(r18,l),registration_satisfaction(r19,_G137667),registration_satisfaction(r20,_G137672),registration_satisfaction(r21,_G137677),registration_satisfaction(r22,h),registration_satisfaction(r23,_G137687),registration_satisfaction(r24,_G137692),registration_satisfaction(r25,_G137697),registration_satisfaction(r26,_G137702),registration_satisfaction(r27,_G137707),registration_satisfaction(r28,h),registration_satisfaction(r29,_G137717),registration_satisfaction(r30,l),registration_satisfaction(r31,_G137727),registration_satisfaction(r32,_G137732),registration_satisfaction(r33,h),registration_satisfaction(r34,_G137742),registration_satisfaction(r35,h),registration_satisfaction(r36,m),registration_satisfaction(r37,h),registration_satisfaction(r38,_G137762),registration_satisfaction(r39,h),registration_satisfaction(r40,_G137772),registration_satisfaction(r41,_G137777),registration_satisfaction(r42,_G137782),registration_satisfaction(r43,h),registration_satisfaction(r44,_G137792),registration_satisfaction(r45,h),registration_satisfaction(r46,m),registration_satisfaction(r47,_G137807),registration_satisfaction(r48,_G137812),registration_satisfaction(r49,h),registration_satisfaction(r50,_G137822),registration_satisfaction(r51,_G137827),registration_satisfaction(r52,h),registration_satisfaction(r53,_G137837),registration_satisfaction(r54,h),registration_satisfaction(r55,h),registration_satisfaction(r56,_G137852),registration_satisfaction(r57,h),registration_satisfaction(r58,_G137862),registration_satisfaction(r59,_G137867),registration_satisfaction(r60,h),registration_satisfaction(r61,h),registration_satisfaction(r62,h),registration_satisfaction(r63,h),registration_satisfaction(r64,h),registration_satisfaction(r65,h),registration_satisfaction(r66,h),registration_satisfaction(r67,_G137907),registration_satisfaction(r68,h),registration_satisfaction(r69,m),registration_satisfaction(r70,_G137922),registration_satisfaction(r71,_G137927),registration_satisfaction(r72,_G137932),registration_satisfaction(r73,h),registration_satisfaction(r74,h),registration_satisfaction(r75,h),registration_satisfaction(r76,_G137952),registration_satisfaction(r77,_G137957),registration_satisfaction(r78,m),registration_satisfaction(r79,h),registration_satisfaction(r80,h),registration_satisfaction(r81,h),registration_satisfaction(r82,l),registration_satisfaction(r83,_G137987),registration_satisfaction(r84,m),registration_satisfaction(r85,h),registration_satisfaction(r86,_G138002),registration_satisfaction(r87,_G138007),registration_satisfaction(r88,h),registration_satisfaction(r89,_G138017),registration_satisfaction(r90,_G138022),registration_satisfaction(r91,h),registration_satisfaction(r92,_G138032),registration_satisfaction(r93,_G138037),registration_satisfaction(r94,l),registration_satisfaction(r95,_G138047),registration_satisfaction(r96,h),registration_satisfaction(r97,_G138057),registration_satisfaction(r98,h),registration_satisfaction(r99,h),registration_satisfaction(r100,_G138072),registration_satisfaction(r101,_G138077),registration_satisfaction(r102,h),registration_satisfaction(r103,h),registration_satisfaction(r104,h),registration_satisfaction(r105,_G138097),registration_satisfaction(r106,_G138102),registration_satisfaction(r107,l),registration_satisfaction(r108,l),registration_satisfaction(r109,h),registration_satisfaction(r110,_G138122),registration_satisfaction(r111,h),registration_satisfaction(r112,_G138132),registration_satisfaction(r113,_G138137),registration_satisfaction(r114,m),registration_satisfaction(r115,_G138147),registration_satisfaction(r116,h),registration_satisfaction(r117,_G138157),registration_satisfaction(r118,h),registration_satisfaction(r119,h),registration_satisfaction(r120,l),registration_satisfaction(r121,_G138177),registration_satisfaction(r122,_G138182),registration_satisfaction(r123,l),registration_satisfaction(r124,_G138192),registration_satisfaction(r125,m),registration_satisfaction(r126,h),registration_satisfaction(r127,h),registration_satisfaction(r128,h),registration_satisfaction(r129,h),registration_satisfaction(r130,h),registration_satisfaction(r131,_G138227),registration_satisfaction(r132,m),registration_satisfaction(r133,_G138237),registration_satisfaction(r134,m),registration_satisfaction(r135,_G138247),registration_satisfaction(r136,h),registration_satisfaction(r137,h),registration_satisfaction(r138,h),registration_satisfaction(r139,_G138267),registration_satisfaction(r140,h),registration_satisfaction(r141,_G138277),registration_satisfaction(r142,h),registration_satisfaction(r143,h),registration_satisfaction(r144,h),registration_satisfaction(r145,l),registration_satisfaction(r146,_G138302),registration_satisfaction(r147,l),registration_satisfaction(r148,m),registration_satisfaction(r149,h),registration_satisfaction(r150,_G138322),registration_satisfaction(r151,_G138327),registration_satisfaction(r152,h),registration_satisfaction(r153,_G138337),registration_satisfaction(r154,_G138342),registration_satisfaction(r155,m),registration_satisfaction(r156,h),registration_satisfaction(r157,_G138357),registration_satisfaction(r158,l),registration_satisfaction(r159,m),registration_satisfaction(r160,h),registration_satisfaction(r161,_G138377),registration_satisfaction(r162,m),registration_satisfaction(r163,_G138387),registration_satisfaction(r164,m),registration_satisfaction(r165,m),registration_satisfaction(r166,l),registration_satisfaction(r167,_G138407),registration_satisfaction(r168,h),registration_satisfaction(r169,h),registration_satisfaction(r170,_G138422),registration_satisfaction(r171,_G138427),registration_satisfaction(r172,h),registration_satisfaction(r173,_G138437),registration_satisfaction(r174,_G138442),registration_satisfaction(r175,_G138447),registration_satisfaction(r176,h),registration_satisfaction(r177,h),registration_satisfaction(r178,h),registration_satisfaction(r179,l),registration_satisfaction(r180,_G138472),registration_satisfaction(r181,_G138477),registration_satisfaction(r182,_G138482),registration_satisfaction(r183,_G138487),registration_satisfaction(r184,_G138492),registration_satisfaction(r185,_G138497),registration_satisfaction(r186,_G138502),registration_satisfaction(r187,h),registration_satisfaction(r188,m),registration_satisfaction(r189,_G138517),registration_satisfaction(r190,h),registration_satisfaction(r191,h),registration_satisfaction(r192,m),registration_satisfaction(r193,h),registration_satisfaction(r194,_G138542),registration_satisfaction(r195,_G138547),registration_satisfaction(r196,_G138552),registration_satisfaction(r197,h),registration_satisfaction(r198,h),registration_satisfaction(r199,h),registration_satisfaction(r200,_G138572),registration_satisfaction(r201,h),registration_satisfaction(r202,_G138582),registration_satisfaction(r203,_G138587),registration_satisfaction(r204,_G138592),registration_satisfaction(r205,_G138597),registration_satisfaction(r206,h),registration_satisfaction(r207,h),registration_satisfaction(r208,h),registration_satisfaction(r209,h),registration_satisfaction(r210,_G138622),registration_satisfaction(r211,_G138627),registration_satisfaction(r212,h),registration_satisfaction(r213,_G138637),registration_satisfaction(r214,_G138642),registration_satisfaction(r215,h),registration_satisfaction(r216,h),registration_satisfaction(r217,h),registration_satisfaction(r218,m),registration_satisfaction(r219,h),registration_satisfaction(r220,h),registration_satisfaction(r221,_G138677),registration_satisfaction(r222,_G138682),registration_satisfaction(r223,h),registration_satisfaction(r224,h),registration_satisfaction(r225,_G138697),registration_satisfaction(r226,_G138702),registration_satisfaction(r227,h),registration_satisfaction(r228,_G138712),registration_satisfaction(r229,l),registration_satisfaction(r230,h),registration_satisfaction(r231,_G138727),registration_satisfaction(r232,h),registration_satisfaction(r233,m),registration_satisfaction(r234,_G138742),registration_satisfaction(r235,h),registration_satisfaction(r236,_G138752),registration_satisfaction(r237,_G138757),registration_satisfaction(r238,m),registration_satisfaction(r239,m),registration_satisfaction(r240,h),registration_satisfaction(r241,h),registration_satisfaction(r242,m),registration_satisfaction(r243,_G138787),registration_satisfaction(r244,_G138792),registration_satisfaction(r245,_G138797),registration_satisfaction(r246,h),registration_satisfaction(r247,_G138807),registration_satisfaction(r248,_G138812),registration_satisfaction(r249,h),registration_satisfaction(r250,h),registration_satisfaction(r251,h),registration_satisfaction(r252,h),registration_satisfaction(r253,h),registration_satisfaction(r254,h),registration_satisfaction(r255,h),registration_satisfaction(r256,_G138852),registration_satisfaction(r257,m),registration_satisfaction(r258,h),registration_satisfaction(r259,_G138867),registration_satisfaction(r260,_G138872),registration_satisfaction(r261,_G138877),registration_satisfaction(r262,h),registration_satisfaction(r263,m),registration_satisfaction(r264,_G138892),registration_satisfaction(r265,_G138897),registration_satisfaction(r266,l),registration_satisfaction(r267,_G138907),registration_satisfaction(r268,_G138912),registration_satisfaction(r269,_G138917),registration_satisfaction(r270,l),registration_satisfaction(r271,h),registration_satisfaction(r272,_G138932),registration_satisfaction(r273,h),registration_satisfaction(r274,h),registration_satisfaction(r275,_G138947),registration_satisfaction(r276,_G138952),registration_satisfaction(r277,h),registration_satisfaction(r278,h),registration_satisfaction(r279,_G138967),registration_satisfaction(r280,_G138972),registration_satisfaction(r281,_G138977),registration_satisfaction(r282,_G138982),registration_satisfaction(r283,_G138987),registration_satisfaction(r284,_G138992),registration_satisfaction(r285,m),registration_satisfaction(r286,h),registration_satisfaction(r287,_G139007),registration_satisfaction(r288,_G139012),registration_satisfaction(r289,l),registration_satisfaction(r290,m),registration_satisfaction(r291,h),registration_satisfaction(r292,m),registration_satisfaction(r293,_G139037),registration_satisfaction(r294,h),registration_satisfaction(r295,_G139047),registration_satisfaction(r296,_G139052),registration_satisfaction(r297,_G139057),registration_satisfaction(r298,_G139062),registration_satisfaction(r299,_G139067),registration_satisfaction(r300,l),registration_satisfaction(r301,_G139077),registration_satisfaction(r302,_G139082),registration_satisfaction(r303,h),registration_satisfaction(r304,h),registration_satisfaction(r305,_G139097),registration_satisfaction(r306,_G139102),registration_satisfaction(r307,_G139107),registration_satisfaction(r308,l),registration_satisfaction(r309,m),registration_satisfaction(r310,_G139122),registration_satisfaction(r311,_G139127),registration_satisfaction(r312,h),registration_satisfaction(r313,_G139137),registration_satisfaction(r314,h),registration_satisfaction(r315,h),registration_satisfaction(r316,l),registration_satisfaction(r317,l),registration_satisfaction(r318,_G139162),registration_satisfaction(r319,_G139167),registration_satisfaction(r320,_G139172),registration_satisfaction(r321,l),registration_satisfaction(r322,h),registration_satisfaction(r323,_G139187),registration_satisfaction(r324,h),registration_satisfaction(r325,h),registration_satisfaction(r326,_G139202),registration_satisfaction(r327,m),registration_satisfaction(r328,h),registration_satisfaction(r329,h),registration_satisfaction(r330,_G139222),registration_satisfaction(r331,h),registration_satisfaction(r332,l),registration_satisfaction(r333,_G139237),registration_satisfaction(r334,_G139242),registration_satisfaction(r335,h),registration_satisfaction(r336,_G139252),registration_satisfaction(r337,h),registration_satisfaction(r338,h),registration_satisfaction(r339,_G139267),registration_satisfaction(r340,_G139272),registration_satisfaction(r341,l),registration_satisfaction(r342,h),registration_satisfaction(r343,_G139287),registration_satisfaction(r344,_G139292),registration_satisfaction(r345,m),registration_satisfaction(r346,h),registration_satisfaction(r347,m),registration_satisfaction(r348,_G139312),registration_satisfaction(r349,h),registration_satisfaction(r350,m),registration_satisfaction(r351,_G139327),registration_satisfaction(r352,l),registration_satisfaction(r353,h),registration_satisfaction(r354,h),registration_satisfaction(r355,_G139347),registration_satisfaction(r356,_G139352),registration_satisfaction(r357,m),registration_satisfaction(r358,_G139362),registration_satisfaction(r359,_G139367),registration_satisfaction(r360,_G139372),registration_satisfaction(r361,m),registration_satisfaction(r362,_G139382),registration_satisfaction(r363,_G139387),registration_satisfaction(r364,_G139392),registration_satisfaction(r365,_G139397),registration_satisfaction(r366,h),registration_satisfaction(r367,h),registration_satisfaction(r368,h),registration_satisfaction(r369,h),registration_satisfaction(r370,_G139422),registration_satisfaction(r371,_G139427),registration_satisfaction(r372,h),registration_satisfaction(r373,h),registration_satisfaction(r374,_G139442),registration_satisfaction(r375,h),registration_satisfaction(r376,_G139452),registration_satisfaction(r377,_G139457),registration_satisfaction(r378,_G139462),registration_satisfaction(r379,h),registration_satisfaction(r380,_G139472),registration_satisfaction(r381,_G139477),registration_satisfaction(r382,h),registration_satisfaction(r383,h),registration_satisfaction(r384,_G139492),registration_satisfaction(r385,m),registration_satisfaction(r386,_G139502),registration_satisfaction(r387,h),registration_satisfaction(r388,_G139512),registration_satisfaction(r389,_G139517),registration_satisfaction(r390,_G139522),registration_satisfaction(r391,l),registration_satisfaction(r392,_G139532),registration_satisfaction(r393,_G139537),registration_satisfaction(r394,h),registration_satisfaction(r395,_G139547),registration_satisfaction(r396,h),registration_satisfaction(r397,h),registration_satisfaction(r398,l),registration_satisfaction(r399,h),registration_satisfaction(r400,_G139572),registration_satisfaction(r401,l),registration_satisfaction(r402,h),registration_satisfaction(r403,h),registration_satisfaction(r404,h),registration_satisfaction(r405,h),registration_satisfaction(r406,_G139602),registration_satisfaction(r407,_G139607),registration_satisfaction(r408,_G139612),registration_satisfaction(r409,h),registration_satisfaction(r410,h),registration_satisfaction(r411,_G139627),registration_satisfaction(r412,_G139632),registration_satisfaction(r413,l),registration_satisfaction(r414,h),registration_satisfaction(r415,m),registration_satisfaction(r416,_G139652),registration_satisfaction(r417,h),registration_satisfaction(r418,_G139662),registration_satisfaction(r419,_G139667),registration_satisfaction(r420,_G139672),registration_satisfaction(r421,_G139677),registration_satisfaction(r422,_G139682),registration_satisfaction(r423,_G139687),registration_satisfaction(r424,h),registration_satisfaction(r425,h),registration_satisfaction(r426,_G139702),registration_satisfaction(r427,_G139707),registration_satisfaction(r428,_G139712),registration_satisfaction(r429,_G139717),registration_satisfaction(r430,l),registration_satisfaction(r431,m),registration_satisfaction(r432,_G139732),registration_satisfaction(r433,_G139737),registration_satisfaction(r434,h),registration_satisfaction(r435,m),registration_satisfaction(r436,_G139752),registration_satisfaction(r437,h),registration_satisfaction(r438,l),registration_satisfaction(r439,_G139767),registration_satisfaction(r440,h),registration_satisfaction(r441,h),registration_satisfaction(r442,_G139782),registration_satisfaction(r443,_G139787),registration_satisfaction(r444,_G139792),registration_satisfaction(r445,_G139797),registration_satisfaction(r446,h),registration_satisfaction(r447,m),registration_satisfaction(r448,l),registration_satisfaction(r449,_G139817),registration_satisfaction(r450,h),registration_satisfaction(r451,_G139827),registration_satisfaction(r452,_G139832),registration_satisfaction(r453,_G139837),registration_satisfaction(r454,_G139842),registration_satisfaction(r455,_G139847),registration_satisfaction(r456,h),registration_satisfaction(r457,h),registration_satisfaction(r458,_G139862),registration_satisfaction(r459,_G139867),registration_satisfaction(r460,l),registration_satisfaction(r461,h),registration_satisfaction(r462,h),registration_satisfaction(r463,_G139887),registration_satisfaction(r464,_G139892),registration_satisfaction(r465,_G139897),registration_satisfaction(r466,l),registration_satisfaction(r467,_G139907),registration_satisfaction(r468,_G139912),registration_satisfaction(r469,h),registration_satisfaction(r470,h),registration_satisfaction(r471,_G139927),registration_satisfaction(r472,_G139932),registration_satisfaction(r473,_G139937),registration_satisfaction(r474,_G139942),registration_satisfaction(r475,h),registration_satisfaction(r476,_G139952),registration_satisfaction(r477,_G139957),registration_satisfaction(r478,_G139962),registration_satisfaction(r479,_G139967),registration_satisfaction(r480,_G139972),registration_satisfaction(r481,_G139977),registration_satisfaction(r482,_G139982),registration_satisfaction(r483,h),registration_satisfaction(r484,_G139992),registration_satisfaction(r485,h),registration_satisfaction(r486,h),registration_satisfaction(r487,_G140007),registration_satisfaction(r488,_G140012),registration_satisfaction(r489,m),registration_satisfaction(r490,_G140022),registration_satisfaction(r491,_G140027),registration_satisfaction(r492,h),registration_satisfaction(r493,_G140037),registration_satisfaction(r494,_G140042),registration_satisfaction(r495,h),registration_satisfaction(r496,h),registration_satisfaction(r497,_G140057),registration_satisfaction(r498,_G140062),registration_satisfaction(r499,h),registration_satisfaction(r500,m),registration_satisfaction(r501,h),registration_satisfaction(r502,_G140082),registration_satisfaction(r503,_G140087),registration_satisfaction(r504,m),registration_satisfaction(r505,_G140097),registration_satisfaction(r506,_G140102),registration_satisfaction(r507,_G140107),registration_satisfaction(r508,_G140112),registration_satisfaction(r509,_G140117),registration_satisfaction(r510,_G140122),registration_satisfaction(r511,l),registration_satisfaction(r512,h),registration_satisfaction(r513,h),registration_satisfaction(r514,_G140142),registration_satisfaction(r515,_G140147),registration_satisfaction(r516,_G140152),registration_satisfaction(r517,m),registration_satisfaction(r518,_G140162),registration_satisfaction(r519,h),registration_satisfaction(r520,_G140172),registration_satisfaction(r521,h),registration_satisfaction(r522,h),registration_satisfaction(r523,h),registration_satisfaction(r524,h),registration_satisfaction(r525,_G140197),registration_satisfaction(r526,h),registration_satisfaction(r527,_G140207),registration_satisfaction(r528,_G140212),registration_satisfaction(r529,h),registration_satisfaction(r530,_G140222),registration_satisfaction(r531,_G140227),registration_satisfaction(r532,_G140232),registration_satisfaction(r533,_G140237),registration_satisfaction(r534,l),registration_satisfaction(r535,_G140247),registration_satisfaction(r536,h),registration_satisfaction(r537,h),registration_satisfaction(r538,_G140262),registration_satisfaction(r539,_G140267),registration_satisfaction(r540,_G140272),registration_satisfaction(r541,_G140277),registration_satisfaction(r542,h),registration_satisfaction(r543,h),registration_satisfaction(r544,_G140292),registration_satisfaction(r545,h),registration_satisfaction(r546,_G140302),registration_satisfaction(r547,_G140307),registration_satisfaction(r548,h),registration_satisfaction(r549,_G140317),registration_satisfaction(r550,_G140322),registration_satisfaction(r551,h),registration_satisfaction(r552,m),registration_satisfaction(r553,m),registration_satisfaction(r554,l),registration_satisfaction(r555,m),registration_satisfaction(r556,_G140352),registration_satisfaction(r557,_G140357),registration_satisfaction(r558,_G140362),registration_satisfaction(r559,_G140367),registration_satisfaction(r560,_G140372),registration_satisfaction(r561,_G140377),registration_satisfaction(r562,h),registration_satisfaction(r563,_G140387),registration_satisfaction(r564,h),registration_satisfaction(r565,_G140397),registration_satisfaction(r566,l),registration_satisfaction(r567,_G140407),registration_satisfaction(r568,h),registration_satisfaction(r569,h),registration_satisfaction(r570,h),registration_satisfaction(r571,_G140427),registration_satisfaction(r572,_G140432),registration_satisfaction(r573,_G140437),registration_satisfaction(r574,_G140442),registration_satisfaction(r575,_G140447),registration_satisfaction(r576,_G140452),registration_satisfaction(r577,_G140457),registration_satisfaction(r578,l),registration_satisfaction(r579,h),registration_satisfaction(r580,m),registration_satisfaction(r581,h),registration_satisfaction(r582,h),registration_satisfaction(r583,h),registration_satisfaction(r584,h),registration_satisfaction(r585,h),registration_satisfaction(r586,_G140502),registration_satisfaction(r587,_G140507),registration_satisfaction(r588,_G140512),registration_satisfaction(r589,l),registration_satisfaction(r590,h),registration_satisfaction(r591,_G140527),registration_satisfaction(r592,_G140532),registration_satisfaction(r593,_G140537),registration_satisfaction(r594,l),registration_satisfaction(r595,m),registration_satisfaction(r596,h),registration_satisfaction(r597,_G140557),registration_satisfaction(r598,_G140562),registration_satisfaction(r599,h),registration_satisfaction(r600,_G140572),registration_satisfaction(r601,m),registration_satisfaction(r602,h),registration_satisfaction(r603,_G140587),registration_satisfaction(r604,_G140592),registration_satisfaction(r605,h),registration_satisfaction(r606,h),registration_satisfaction(r607,l),registration_satisfaction(r608,_G140612),registration_satisfaction(r609,h),registration_satisfaction(r610,_G140622),registration_satisfaction(r611,h),registration_satisfaction(r612,l),registration_satisfaction(r613,_G140637),registration_satisfaction(r614,_G140642),registration_satisfaction(r615,_G140647),registration_satisfaction(r616,h),registration_satisfaction(r617,h),registration_satisfaction(r618,h),registration_satisfaction(r619,h),registration_satisfaction(r620,_G140672),registration_satisfaction(r621,_G140677),registration_satisfaction(r622,h),registration_satisfaction(r623,_G140687),registration_satisfaction(r624,_G140692),registration_satisfaction(r625,l),registration_satisfaction(r626,_G140702),registration_satisfaction(r627,h),registration_satisfaction(r628,h),registration_satisfaction(r629,h),registration_satisfaction(r630,h),registration_satisfaction(r631,h),registration_satisfaction(r632,h),registration_satisfaction(r633,_G140737),registration_satisfaction(r634,_G140742),registration_satisfaction(r635,_G140747),registration_satisfaction(r636,_G140752),registration_satisfaction(r637,_G140757),registration_satisfaction(r638,h),registration_satisfaction(r639,_G140767),registration_satisfaction(r640,h),registration_satisfaction(r641,h),registration_satisfaction(r642,_G140782),registration_satisfaction(r643,_G140787),registration_satisfaction(r644,h),registration_satisfaction(r645,_G140797),registration_satisfaction(r646,h),registration_satisfaction(r647,h),registration_satisfaction(r648,_G140812),registration_satisfaction(r649,_G140817),registration_satisfaction(r650,_G140822),registration_satisfaction(r651,_G140827),registration_satisfaction(r652,_G140832),registration_satisfaction(r653,_G140837),registration_satisfaction(r654,h),registration_satisfaction(r655,h),registration_satisfaction(r656,m),registration_satisfaction(r657,_G140857),registration_satisfaction(r658,h),registration_satisfaction(r659,h),registration_satisfaction(r660,h),registration_satisfaction(r661,_G140877),registration_satisfaction(r662,_G140882),registration_satisfaction(r663,h),registration_satisfaction(r664,_G140892),registration_satisfaction(r665,h),registration_satisfaction(r666,l),registration_satisfaction(r667,h),registration_satisfaction(r668,l),registration_satisfaction(r669,_G140917),registration_satisfaction(r670,h),registration_satisfaction(r671,_G140927),registration_satisfaction(r672,_G140932),registration_satisfaction(r673,_G140937),registration_satisfaction(r674,h),registration_satisfaction(r675,l),registration_satisfaction(r676,_G140952),registration_satisfaction(r677,_G140957),registration_satisfaction(r678,h),registration_satisfaction(r679,h),registration_satisfaction(r680,m),registration_satisfaction(r681,_G140977),registration_satisfaction(r682,_G140982),registration_satisfaction(r683,h),registration_satisfaction(r684,_G140992),registration_satisfaction(r685,h),registration_satisfaction(r686,h),registration_satisfaction(r687,_G141007),registration_satisfaction(r688,_G141012),registration_satisfaction(r689,_G141017),registration_satisfaction(r690,h),registration_satisfaction(r691,h),registration_satisfaction(r692,h),registration_satisfaction(r693,_G141037),registration_satisfaction(r694,h),registration_satisfaction(r695,_G141047),registration_satisfaction(r696,_G141052),registration_satisfaction(r697,_G141057),registration_satisfaction(r698,h),registration_satisfaction(r699,h),registration_satisfaction(r700,_G141072),registration_satisfaction(r701,h),registration_satisfaction(r702,_G141082),registration_satisfaction(r703,_G141087),registration_satisfaction(r704,l),registration_satisfaction(r705,_G141097),registration_satisfaction(r706,_G141102),registration_satisfaction(r707,_G141107),registration_satisfaction(r708,_G141112),registration_satisfaction(r709,m),registration_satisfaction(r710,l),registration_satisfaction(r711,h),registration_satisfaction(r712,h),registration_satisfaction(r713,h),registration_satisfaction(r714,m),registration_satisfaction(r715,_G141147),registration_satisfaction(r716,h),registration_satisfaction(r717,h),registration_satisfaction(r718,l),registration_satisfaction(r719,l),registration_satisfaction(r720,_G141172),registration_satisfaction(r721,h),registration_satisfaction(r722,h),registration_satisfaction(r723,h),registration_satisfaction(r724,h),registration_satisfaction(r725,_G141197),registration_satisfaction(r726,h),registration_satisfaction(r727,_G141207),registration_satisfaction(r728,_G141212),registration_satisfaction(r729,_G141217),registration_satisfaction(r730,h),registration_satisfaction(r731,h),registration_satisfaction(r732,_G141232),registration_satisfaction(r733,_G141237),registration_satisfaction(r734,h),registration_satisfaction(r735,h),registration_satisfaction(r736,_G141252),registration_satisfaction(r737,h),registration_satisfaction(r738,_G141262),registration_satisfaction(r739,h),registration_satisfaction(r740,h),registration_satisfaction(r741,h),registration_satisfaction(r742,h),registration_satisfaction(r743,_G141287),registration_satisfaction(r744,_G141292),registration_satisfaction(r745,m),registration_satisfaction(r746,h),registration_satisfaction(r747,_G141307),registration_satisfaction(r748,_G141312),registration_satisfaction(r749,_G141317),registration_satisfaction(r750,_G141322),registration_satisfaction(r751,_G141327),registration_satisfaction(r752,m),registration_satisfaction(r753,m),registration_satisfaction(r754,_G141342),registration_satisfaction(r755,l),registration_satisfaction(r756,_G141352),registration_satisfaction(r757,h),registration_satisfaction(r758,h),registration_satisfaction(r759,l),registration_satisfaction(r760,_G141372),registration_satisfaction(r761,h),registration_satisfaction(r762,_G141382),registration_satisfaction(r763,_G141387),registration_satisfaction(r764,_G141392),registration_satisfaction(r765,h),registration_satisfaction(r766,_G141402),registration_satisfaction(r767,_G141407),registration_satisfaction(r768,_G141412),registration_satisfaction(r769,_G141417),registration_satisfaction(r770,m),registration_satisfaction(r771,_G141427),registration_satisfaction(r772,_G141432),registration_satisfaction(r773,m),registration_satisfaction(r774,h),registration_satisfaction(r775,h),registration_satisfaction(r776,_G141452),registration_satisfaction(r777,_G141457),registration_satisfaction(r778,h),registration_satisfaction(r779,_G141467),registration_satisfaction(r780,h),registration_satisfaction(r781,m),registration_satisfaction(r782,m),registration_satisfaction(r783,m),registration_satisfaction(r784,l),registration_satisfaction(r785,l),registration_satisfaction(r786,h),registration_satisfaction(r787,h),registration_satisfaction(r788,_G141512),registration_satisfaction(r789,_G141517),registration_satisfaction(r790,_G141522),registration_satisfaction(r791,h),registration_satisfaction(r792,_G141532),registration_satisfaction(r793,_G141537),registration_satisfaction(r794,_G141542),registration_satisfaction(r795,_G141547),registration_satisfaction(r796,h),registration_satisfaction(r797,h),registration_satisfaction(r798,m),registration_satisfaction(r799,_G141567),registration_satisfaction(r800,m),registration_satisfaction(r801,h),registration_satisfaction(r802,h),registration_satisfaction(r803,h),registration_satisfaction(r804,_G141592),registration_satisfaction(r805,_G141597),registration_satisfaction(r806,_G141602),registration_satisfaction(r807,_G141607),registration_satisfaction(r808,_G141612),registration_satisfaction(r809,_G141617),registration_satisfaction(r810,h),registration_satisfaction(r811,_G141627),registration_satisfaction(r812,h),registration_satisfaction(r813,m),registration_satisfaction(r814,l),registration_satisfaction(r815,_G141647),registration_satisfaction(r816,_G141652),registration_satisfaction(r817,_G141657),registration_satisfaction(r818,_G141662),registration_satisfaction(r819,h),registration_satisfaction(r820,h),registration_satisfaction(r821,_G141677),registration_satisfaction(r822,m),registration_satisfaction(r823,_G141687),registration_satisfaction(r824,m),registration_satisfaction(r825,l),registration_satisfaction(r826,l),registration_satisfaction(r827,l),registration_satisfaction(r828,_G141712),registration_satisfaction(r829,_G141717),registration_satisfaction(r830,h),registration_satisfaction(r831,_G141727),registration_satisfaction(r832,m),registration_satisfaction(r833,_G141737),registration_satisfaction(r834,_G141742),registration_satisfaction(r835,_G141747),registration_satisfaction(r836,h),registration_satisfaction(r837,h),registration_satisfaction(r838,l),registration_satisfaction(r839,_G141767),registration_satisfaction(r840,m),registration_satisfaction(r841,_G141777),registration_satisfaction(r842,_G141782),registration_satisfaction(r843,h),registration_satisfaction(r844,_G141792),registration_satisfaction(r845,_G141797),registration_satisfaction(r846,_G141802),registration_satisfaction(r847,_G141807),registration_satisfaction(r848,l),registration_satisfaction(r849,_G141817),registration_satisfaction(r850,_G141822),registration_satisfaction(r851,h),registration_satisfaction(r852,h),registration_satisfaction(r853,h),registration_satisfaction(r854,m),registration_satisfaction(r855,_G141847),registration_satisfaction(r856,_G141852)]). + + % % change to 0.0, 0.1, 0.2 to make things simpler/harder % -missing(0.50). +missing(0.5). % miss 30% of the examples. goal(professor_ability(P,V)) :- diff --git a/packages/CLPBN/learning/learn_utils.yap b/packages/CLPBN/learning/learn_utils.yap index 9d0523dd9..713f19da4 100644 --- a/packages/CLPBN/learning/learn_utils.yap +++ b/packages/CLPBN/learning/learn_utils.yap @@ -38,7 +38,7 @@ run_all(M:Gs) :- run_all([],_). run_all([G|Gs],M) :- % (G = _:ge(ybr136w,t8,23,-1) -> nb_getval(clpbn_tables, Tab), writeln(Tab) ; true ), - ( call(M:G) -> true ; writeln(bad:M:G), start_low_level_trace, M:G ; halt ), + ( call(M:G) -> true ; throw(bad_call(M:G)) ), run_all(Gs,M). clpbn_vars(Vs,BVars) :- diff --git a/packages/PLStream/pl-file.c b/packages/PLStream/pl-file.c index 6063f64ee..bc67f2652 100755 --- a/packages/PLStream/pl-file.c +++ b/packages/PLStream/pl-file.c @@ -4740,7 +4740,7 @@ struct PL_local_data *Yap_InitThreadIO(int wid) #if THREADS if (wid) { /* copy from other worker */ - memcpy(p, Yap_WLocal[worker_id]->Yap_ld_, sizeof(struct PL_local_data)); + memcpy(p, Yap_local[worker_id]->PL_local_data_p_, sizeof(struct PL_local_data)); } #endif return p; diff --git a/packages/PLStream/pl-global.h b/packages/PLStream/pl-global.h index e1fa1b173..6338c68dc 100644 --- a/packages/PLStream/pl-global.h +++ b/packages/PLStream/pl-global.h @@ -255,7 +255,7 @@ extern PL_local_data_t lds; // THIS HAS TO BE ABSTRACTED -#define GLOBAL_LD (PL_local_data_p) +#define GLOBAL_LD (LOCAL_PL_local_data_p) #if !defined(O_PLMT) && !defined(YAPOR) #define LOCAL_LD (GLOBAL_LD) diff --git a/packages/PLStream/pl-incl.h b/packages/PLStream/pl-incl.h index a2ceba132..80e3d5a82 100755 --- a/packages/PLStream/pl-incl.h +++ b/packages/PLStream/pl-incl.h @@ -43,6 +43,7 @@ do_startCritical(void) { } static inline int do_endCritical(void) { + CACHE_REGS YAPLeaveCriticalSection(); return 1; } diff --git a/packages/PLStream/pl-yap.c b/packages/PLStream/pl-yap.c index 60dfa6bdc..34550abc0 100755 --- a/packages/PLStream/pl-yap.c +++ b/packages/PLStream/pl-yap.c @@ -1,6 +1,8 @@ /* YAP support for some low-level SWI stuff */ +#define PL_KERNEL 1 + #include #include "Yap.h" #include "Yatom.h" @@ -1098,7 +1100,7 @@ pl_readline(term_t flag) static Term StreamPosition(IOSTREAM *st) -{ +{ GET_LD Term t[4]; if (!st) st = Suser_input; diff --git a/packages/chr b/packages/chr index bf6525f85..b2eb894ce 160000 --- a/packages/chr +++ b/packages/chr @@ -1 +1 @@ -Subproject commit bf6525f85cfcf3c08fff8cf91fb189fe71dc34fd +Subproject commit b2eb894ce3e41925070215f800d6df3a356dc29d diff --git a/packages/meld/Makefile.in b/packages/meld/Makefile.in index b083bb8d4..64756d21d 100644 --- a/packages/meld/Makefile.in +++ b/packages/meld/Makefile.in @@ -24,6 +24,8 @@ INSTALL_PROGRAM=@INSTALL_PROGRAM@ srcdir=@srcdir@ YAP_EXTRAS=@YAP_EXTRAS@ +EXDIR=$(srcdir)/examples + MELD_PROGRAMS= \ $(srcdir)/meldtd.yap \ $(srcdir)/meldc.yap \ @@ -31,11 +33,12 @@ MELD_PROGRAMS= \ $(srcdir)/meldp.yap MELD_EXAMPLES= \ - $(srcdir)/maxtemp.meld \ - $(srcdir)/graph0.meld \ - $(srcdir)/graph1.meld \ - $(srcdir)/graph2.meld \ - $(srcdir)/graph3.meld + $(EXDIR)/temperature/maxtemp.meld \ + $(EXDIR)/temperature/graph0.meld \ + $(EXDIR)/temperature/graph1.meld \ + $(EXDIR)/temperature/graph2.meld \ + $(EXDIR)/temperature/graph3.meld \ + $(EXDIR)/pagerank/pagerank.meld \ PROGRAMS= \ $(srcdir)/meld.yap \ diff --git a/packages/meld/README b/packages/meld/README index cdc63d6cf..809766ef8 100644 --- a/packages/meld/README +++ b/packages/meld/README @@ -17,8 +17,8 @@ Supported: - basic semantics - aggregates - updates + - delete Unsupported: - - delete - distributed execution :) diff --git a/packages/meld/examples/pagerank/README b/packages/meld/examples/pagerank/README new file mode 100644 index 000000000..cd7b743d9 --- /dev/null +++ b/packages/meld/examples/pagerank/README @@ -0,0 +1,13 @@ +Pagerank Algorithm in Meld + Example of Iteration and Arithmetic Builtins + +Use as follows: + +bash> yap + +:- use_module(library(meld)). + +:- mcompile(pagerank). + +:- simulate(g10). + diff --git a/packages/meld/examples/pagerank/g10.meld b/packages/meld/examples/pagerank/g10.meld new file mode 100644 index 000000000..276101fc1 --- /dev/null +++ b/packages/meld/examples/pagerank/g10.meld @@ -0,0 +1,30 @@ +edge(0, 9). +edge(0, 6). +edge(1, 6). +edge(2, 9). +edge(2, 3). +edge(2, 6). +edge(2, 8). +edge(3, 4). +edge(4, 2). +edge(4, 1). +edge(5, 4). +edge(5, 3). +edge(5, 8). +edge(5, 9). +edge(5, 2). +edge(6, 2). +edge(6, 8). +edge(6, 7). +edge(6, 3). +edge(6, 1). +edge(7, 6). +edge(7, 2). +edge(7, 4). +edge(7, 9). +edge(7, 5). +edge(8, 4). +edge(8, 9). +edge(8, 0). +edge(8, 3). +edge(9, 7). diff --git a/packages/meld/examples/pagerank/g100.meld b/packages/meld/examples/pagerank/g100.meld new file mode 100644 index 000000000..00e424031 --- /dev/null +++ b/packages/meld/examples/pagerank/g100.meld @@ -0,0 +1,3030 @@ +edge(0, 15). +edge(0, 52). +edge(0, 39). +edge(0, 82). +edge(0, 54). +edge(0, 8). +edge(0, 11). +edge(0, 67). +edge(0, 68). +edge(0, 48). +edge(0, 9). +edge(0, 58). +edge(0, 63). +edge(0, 36). +edge(0, 49). +edge(0, 18). +edge(0, 1). +edge(0, 50). +edge(0, 37). +edge(0, 23). +edge(0, 91). +edge(0, 96). +edge(0, 81). +edge(0, 44). +edge(0, 19). +edge(0, 92). +edge(0, 90). +edge(0, 47). +edge(0, 43). +edge(0, 95). +edge(0, 33). +edge(0, 86). +edge(0, 69). +edge(0, 65). +edge(0, 97). +edge(0, 12). +edge(0, 45). +edge(0, 29). +edge(0, 64). +edge(0, 75). +edge(0, 56). +edge(0, 66). +edge(0, 80). +edge(0, 79). +edge(0, 13). +edge(0, 53). +edge(0, 94). +edge(0, 85). +edge(0, 42). +edge(0, 27). +edge(0, 61). +edge(0, 72). +edge(0, 70). +edge(0, 4). +edge(0, 77). +edge(0, 31). +edge(1, 63). +edge(1, 52). +edge(1, 28). +edge(1, 18). +edge(1, 30). +edge(1, 23). +edge(1, 92). +edge(1, 94). +edge(1, 60). +edge(1, 2). +edge(1, 95). +edge(1, 14). +edge(1, 86). +edge(1, 87). +edge(1, 37). +edge(1, 90). +edge(1, 43). +edge(1, 45). +edge(1, 73). +edge(1, 62). +edge(1, 67). +edge(2, 12). +edge(2, 70). +edge(2, 76). +edge(2, 46). +edge(2, 11). +edge(2, 28). +edge(2, 60). +edge(2, 6). +edge(2, 73). +edge(2, 3). +edge(2, 74). +edge(2, 16). +edge(2, 56). +edge(2, 35). +edge(2, 57). +edge(2, 84). +edge(2, 81). +edge(2, 25). +edge(2, 86). +edge(2, 36). +edge(2, 20). +edge(2, 37). +edge(2, 5). +edge(2, 55). +edge(2, 53). +edge(2, 44). +edge(2, 61). +edge(2, 23). +edge(2, 7). +edge(2, 87). +edge(2, 24). +edge(2, 93). +edge(2, 90). +edge(2, 4). +edge(2, 49). +edge(2, 67). +edge(2, 42). +edge(2, 78). +edge(2, 68). +edge(2, 26). +edge(2, 92). +edge(2, 89). +edge(2, 97). +edge(2, 19). +edge(3, 32). +edge(3, 69). +edge(3, 93). +edge(3, 43). +edge(3, 45). +edge(3, 81). +edge(3, 91). +edge(3, 10). +edge(3, 74). +edge(3, 24). +edge(3, 94). +edge(4, 51). +edge(4, 11). +edge(4, 87). +edge(4, 97). +edge(5, 67). +edge(5, 66). +edge(5, 3). +edge(5, 61). +edge(5, 7). +edge(5, 97). +edge(5, 54). +edge(5, 71). +edge(5, 1). +edge(5, 89). +edge(5, 58). +edge(5, 32). +edge(5, 56). +edge(5, 88). +edge(5, 86). +edge(5, 91). +edge(5, 16). +edge(5, 64). +edge(5, 39). +edge(5, 28). +edge(5, 42). +edge(5, 92). +edge(5, 34). +edge(5, 51). +edge(5, 21). +edge(5, 37). +edge(6, 79). +edge(6, 80). +edge(6, 46). +edge(6, 45). +edge(6, 91). +edge(6, 58). +edge(6, 62). +edge(6, 27). +edge(6, 73). +edge(6, 54). +edge(6, 55). +edge(6, 83). +edge(6, 24). +edge(6, 78). +edge(6, 63). +edge(6, 72). +edge(6, 21). +edge(6, 75). +edge(6, 71). +edge(6, 2). +edge(6, 10). +edge(6, 85). +edge(6, 26). +edge(6, 16). +edge(6, 69). +edge(6, 47). +edge(6, 86). +edge(6, 1). +edge(6, 33). +edge(6, 68). +edge(6, 7). +edge(6, 31). +edge(6, 17). +edge(6, 38). +edge(6, 12). +edge(6, 30). +edge(6, 8). +edge(6, 28). +edge(6, 22). +edge(6, 61). +edge(6, 56). +edge(6, 76). +edge(6, 53). +edge(6, 42). +edge(6, 57). +edge(6, 13). +edge(6, 14). +edge(6, 52). +edge(6, 19). +edge(6, 4). +edge(7, 49). +edge(7, 6). +edge(7, 11). +edge(7, 16). +edge(7, 88). +edge(7, 52). +edge(7, 10). +edge(7, 39). +edge(7, 35). +edge(7, 46). +edge(7, 29). +edge(7, 65). +edge(7, 78). +edge(7, 41). +edge(7, 24). +edge(7, 34). +edge(7, 1). +edge(7, 59). +edge(7, 79). +edge(7, 95). +edge(7, 69). +edge(7, 91). +edge(7, 40). +edge(7, 15). +edge(7, 63). +edge(7, 9). +edge(7, 64). +edge(7, 22). +edge(7, 58). +edge(7, 31). +edge(7, 18). +edge(7, 92). +edge(7, 30). +edge(7, 36). +edge(7, 83). +edge(7, 21). +edge(7, 3). +edge(7, 90). +edge(7, 47). +edge(7, 5). +edge(7, 37). +edge(7, 53). +edge(7, 48). +edge(7, 14). +edge(7, 54). +edge(7, 28). +edge(7, 38). +edge(7, 2). +edge(8, 55). +edge(8, 12). +edge(8, 33). +edge(8, 34). +edge(8, 27). +edge(8, 14). +edge(8, 53). +edge(8, 61). +edge(8, 42). +edge(8, 72). +edge(8, 35). +edge(8, 87). +edge(8, 63). +edge(8, 46). +edge(8, 89). +edge(8, 58). +edge(8, 41). +edge(8, 79). +edge(8, 47). +edge(8, 90). +edge(8, 19). +edge(8, 85). +edge(9, 80). +edge(9, 62). +edge(9, 23). +edge(9, 44). +edge(9, 88). +edge(9, 51). +edge(9, 56). +edge(9, 70). +edge(9, 27). +edge(9, 5). +edge(9, 64). +edge(9, 61). +edge(9, 21). +edge(9, 32). +edge(9, 79). +edge(9, 71). +edge(9, 84). +edge(9, 89). +edge(9, 40). +edge(9, 34). +edge(9, 87). +edge(9, 55). +edge(9, 83). +edge(9, 57). +edge(9, 60). +edge(9, 3). +edge(9, 10). +edge(9, 94). +edge(9, 59). +edge(9, 4). +edge(9, 18). +edge(9, 6). +edge(9, 47). +edge(9, 69). +edge(9, 50). +edge(9, 96). +edge(10, 14). +edge(10, 90). +edge(10, 1). +edge(10, 29). +edge(10, 33). +edge(10, 57). +edge(10, 71). +edge(10, 68). +edge(10, 85). +edge(10, 37). +edge(10, 63). +edge(10, 99). +edge(10, 32). +edge(10, 28). +edge(10, 79). +edge(10, 94). +edge(10, 27). +edge(10, 11). +edge(10, 91). +edge(10, 9). +edge(10, 77). +edge(10, 21). +edge(10, 20). +edge(10, 53). +edge(10, 84). +edge(10, 22). +edge(10, 86). +edge(10, 36). +edge(10, 15). +edge(10, 74). +edge(10, 75). +edge(10, 72). +edge(11, 79). +edge(11, 82). +edge(11, 75). +edge(11, 17). +edge(11, 47). +edge(11, 42). +edge(11, 12). +edge(11, 44). +edge(11, 38). +edge(11, 58). +edge(11, 3). +edge(11, 31). +edge(11, 63). +edge(11, 49). +edge(11, 46). +edge(11, 97). +edge(11, 43). +edge(11, 21). +edge(11, 15). +edge(11, 59). +edge(11, 89). +edge(11, 16). +edge(11, 53). +edge(11, 77). +edge(11, 39). +edge(11, 6). +edge(11, 20). +edge(11, 96). +edge(11, 88). +edge(11, 2). +edge(11, 10). +edge(11, 41). +edge(11, 65). +edge(11, 25). +edge(11, 35). +edge(11, 32). +edge(11, 55). +edge(11, 34). +edge(11, 4). +edge(12, 18). +edge(12, 33). +edge(12, 81). +edge(12, 94). +edge(12, 77). +edge(12, 84). +edge(12, 58). +edge(12, 45). +edge(12, 13). +edge(12, 68). +edge(12, 30). +edge(12, 4). +edge(12, 29). +edge(12, 37). +edge(12, 79). +edge(12, 25). +edge(12, 69). +edge(12, 55). +edge(12, 87). +edge(12, 1). +edge(12, 66). +edge(12, 62). +edge(12, 5). +edge(12, 3). +edge(12, 82). +edge(12, 65). +edge(12, 74). +edge(12, 71). +edge(12, 60). +edge(12, 24). +edge(12, 17). +edge(12, 20). +edge(12, 64). +edge(12, 34). +edge(13, 19). +edge(13, 23). +edge(13, 67). +edge(13, 61). +edge(13, 46). +edge(13, 15). +edge(13, 54). +edge(13, 88). +edge(13, 29). +edge(13, 77). +edge(13, 43). +edge(13, 33). +edge(13, 57). +edge(13, 63). +edge(13, 59). +edge(13, 49). +edge(13, 2). +edge(14, 98). +edge(14, 88). +edge(14, 29). +edge(14, 74). +edge(14, 9). +edge(14, 13). +edge(14, 56). +edge(14, 5). +edge(14, 23). +edge(14, 91). +edge(14, 12). +edge(14, 64). +edge(14, 44). +edge(14, 36). +edge(14, 18). +edge(14, 83). +edge(14, 30). +edge(14, 22). +edge(14, 79). +edge(14, 21). +edge(14, 8). +edge(14, 51). +edge(14, 61). +edge(14, 40). +edge(14, 57). +edge(14, 24). +edge(14, 48). +edge(14, 46). +edge(14, 62). +edge(14, 28). +edge(14, 10). +edge(14, 97). +edge(14, 42). +edge(14, 67). +edge(14, 35). +edge(14, 32). +edge(14, 31). +edge(15, 65). +edge(15, 46). +edge(15, 42). +edge(15, 11). +edge(15, 14). +edge(15, 29). +edge(15, 50). +edge(15, 21). +edge(15, 57). +edge(15, 32). +edge(15, 38). +edge(15, 92). +edge(15, 81). +edge(15, 76). +edge(15, 58). +edge(15, 36). +edge(15, 33). +edge(15, 7). +edge(15, 82). +edge(15, 4). +edge(15, 56). +edge(15, 95). +edge(15, 67). +edge(15, 75). +edge(15, 22). +edge(15, 31). +edge(15, 88). +edge(15, 16). +edge(15, 52). +edge(15, 41). +edge(15, 13). +edge(15, 47). +edge(16, 35). +edge(16, 25). +edge(16, 32). +edge(16, 47). +edge(16, 85). +edge(16, 96). +edge(16, 42). +edge(16, 62). +edge(16, 56). +edge(16, 34). +edge(16, 67). +edge(16, 30). +edge(16, 24). +edge(16, 92). +edge(16, 54). +edge(16, 89). +edge(16, 31). +edge(16, 99). +edge(16, 1). +edge(16, 5). +edge(16, 6). +edge(16, 61). +edge(16, 66). +edge(16, 70). +edge(16, 38). +edge(16, 27). +edge(16, 19). +edge(16, 51). +edge(16, 11). +edge(16, 73). +edge(16, 8). +edge(16, 53). +edge(16, 45). +edge(16, 17). +edge(16, 98). +edge(16, 39). +edge(16, 83). +edge(16, 80). +edge(16, 60). +edge(16, 43). +edge(16, 72). +edge(16, 9). +edge(16, 65). +edge(16, 86). +edge(16, 84). +edge(16, 95). +edge(16, 18). +edge(16, 75). +edge(16, 3). +edge(17, 38). +edge(17, 8). +edge(17, 56). +edge(17, 32). +edge(17, 33). +edge(17, 1). +edge(17, 57). +edge(17, 52). +edge(17, 40). +edge(17, 31). +edge(17, 22). +edge(17, 26). +edge(17, 10). +edge(17, 43). +edge(17, 81). +edge(17, 87). +edge(17, 7). +edge(17, 62). +edge(17, 97). +edge(17, 67). +edge(17, 58). +edge(17, 23). +edge(17, 69). +edge(17, 13). +edge(17, 20). +edge(17, 18). +edge(17, 80). +edge(17, 2). +edge(17, 5). +edge(17, 35). +edge(17, 85). +edge(17, 46). +edge(17, 83). +edge(17, 72). +edge(17, 50). +edge(17, 98). +edge(17, 93). +edge(17, 77). +edge(17, 54). +edge(17, 12). +edge(17, 36). +edge(17, 63). +edge(17, 9). +edge(17, 30). +edge(17, 51). +edge(17, 76). +edge(17, 24). +edge(17, 49). +edge(17, 14). +edge(18, 50). +edge(18, 75). +edge(18, 29). +edge(18, 61). +edge(18, 98). +edge(18, 38). +edge(18, 49). +edge(18, 62). +edge(18, 58). +edge(18, 66). +edge(18, 90). +edge(18, 76). +edge(18, 57). +edge(18, 43). +edge(18, 41). +edge(18, 3). +edge(18, 84). +edge(18, 65). +edge(18, 96). +edge(18, 2). +edge(18, 95). +edge(18, 6). +edge(18, 9). +edge(18, 46). +edge(18, 81). +edge(18, 37). +edge(18, 97). +edge(18, 26). +edge(18, 55). +edge(18, 14). +edge(18, 30). +edge(18, 21). +edge(18, 28). +edge(18, 63). +edge(18, 80). +edge(18, 5). +edge(18, 7). +edge(18, 44). +edge(18, 82). +edge(18, 93). +edge(19, 51). +edge(19, 37). +edge(19, 90). +edge(19, 42). +edge(19, 79). +edge(19, 31). +edge(19, 93). +edge(19, 62). +edge(19, 7). +edge(19, 53). +edge(19, 54). +edge(19, 34). +edge(19, 57). +edge(19, 10). +edge(19, 46). +edge(19, 17). +edge(19, 78). +edge(19, 67). +edge(19, 56). +edge(19, 81). +edge(19, 63). +edge(19, 48). +edge(19, 74). +edge(19, 61). +edge(19, 28). +edge(19, 33). +edge(19, 43). +edge(19, 94). +edge(19, 3). +edge(19, 14). +edge(19, 40). +edge(19, 77). +edge(19, 41). +edge(19, 35). +edge(19, 66). +edge(20, 39). +edge(20, 41). +edge(20, 77). +edge(20, 58). +edge(20, 75). +edge(20, 85). +edge(20, 83). +edge(20, 54). +edge(20, 37). +edge(20, 19). +edge(20, 27). +edge(20, 5). +edge(20, 32). +edge(20, 50). +edge(20, 46). +edge(20, 91). +edge(20, 22). +edge(20, 17). +edge(20, 86). +edge(20, 94). +edge(20, 2). +edge(20, 25). +edge(20, 52). +edge(20, 24). +edge(20, 72). +edge(20, 45). +edge(21, 43). +edge(21, 86). +edge(21, 23). +edge(21, 89). +edge(21, 4). +edge(21, 53). +edge(21, 46). +edge(21, 57). +edge(21, 69). +edge(22, 81). +edge(22, 8). +edge(22, 92). +edge(22, 55). +edge(22, 64). +edge(22, 33). +edge(22, 66). +edge(22, 46). +edge(22, 97). +edge(22, 62). +edge(22, 99). +edge(22, 96). +edge(22, 13). +edge(22, 36). +edge(22, 31). +edge(22, 85). +edge(22, 21). +edge(22, 37). +edge(22, 34). +edge(22, 1). +edge(22, 61). +edge(22, 73). +edge(22, 94). +edge(22, 28). +edge(22, 90). +edge(22, 50). +edge(22, 98). +edge(22, 53). +edge(22, 24). +edge(22, 89). +edge(22, 38). +edge(22, 70). +edge(22, 93). +edge(22, 45). +edge(22, 95). +edge(22, 2). +edge(22, 23). +edge(23, 4). +edge(23, 25). +edge(23, 22). +edge(23, 80). +edge(23, 26). +edge(23, 75). +edge(23, 63). +edge(23, 65). +edge(23, 69). +edge(23, 57). +edge(23, 35). +edge(23, 68). +edge(23, 73). +edge(23, 9). +edge(23, 58). +edge(23, 49). +edge(23, 36). +edge(23, 67). +edge(23, 72). +edge(23, 1). +edge(23, 90). +edge(23, 47). +edge(23, 19). +edge(23, 6). +edge(23, 31). +edge(23, 46). +edge(23, 62). +edge(24, 61). +edge(24, 67). +edge(24, 30). +edge(24, 39). +edge(24, 68). +edge(24, 98). +edge(24, 25). +edge(24, 82). +edge(24, 62). +edge(24, 73). +edge(24, 4). +edge(24, 6). +edge(24, 94). +edge(24, 55). +edge(24, 85). +edge(24, 95). +edge(24, 91). +edge(24, 47). +edge(24, 75). +edge(24, 86). +edge(24, 38). +edge(24, 60). +edge(24, 74). +edge(24, 51). +edge(24, 29). +edge(24, 26). +edge(24, 49). +edge(24, 12). +edge(24, 15). +edge(24, 58). +edge(24, 71). +edge(24, 72). +edge(24, 69). +edge(24, 97). +edge(24, 18). +edge(24, 54). +edge(25, 88). +edge(25, 27). +edge(25, 72). +edge(25, 47). +edge(26, 79). +edge(26, 35). +edge(26, 41). +edge(26, 68). +edge(26, 90). +edge(26, 46). +edge(26, 54). +edge(26, 28). +edge(26, 86). +edge(26, 85). +edge(26, 2). +edge(26, 8). +edge(26, 94). +edge(26, 58). +edge(26, 74). +edge(26, 87). +edge(26, 67). +edge(26, 93). +edge(26, 12). +edge(26, 16). +edge(26, 89). +edge(26, 48). +edge(27, 70). +edge(28, 41). +edge(28, 66). +edge(28, 25). +edge(28, 84). +edge(28, 35). +edge(28, 82). +edge(28, 64). +edge(28, 88). +edge(28, 45). +edge(28, 30). +edge(28, 3). +edge(28, 75). +edge(28, 46). +edge(28, 73). +edge(28, 33). +edge(28, 18). +edge(28, 98). +edge(28, 39). +edge(29, 46). +edge(29, 30). +edge(29, 93). +edge(29, 24). +edge(29, 74). +edge(29, 35). +edge(30, 37). +edge(30, 77). +edge(30, 88). +edge(30, 60). +edge(30, 25). +edge(30, 57). +edge(30, 80). +edge(30, 92). +edge(30, 98). +edge(30, 7). +edge(30, 44). +edge(30, 32). +edge(30, 17). +edge(30, 90). +edge(30, 49). +edge(30, 1). +edge(30, 96). +edge(30, 46). +edge(30, 72). +edge(30, 70). +edge(30, 95). +edge(30, 67). +edge(30, 16). +edge(30, 73). +edge(30, 12). +edge(30, 8). +edge(30, 58). +edge(30, 64). +edge(30, 82). +edge(30, 75). +edge(30, 3). +edge(30, 29). +edge(30, 28). +edge(30, 59). +edge(30, 22). +edge(30, 89). +edge(30, 6). +edge(30, 47). +edge(30, 78). +edge(30, 9). +edge(30, 54). +edge(31, 54). +edge(31, 65). +edge(31, 61). +edge(31, 34). +edge(31, 17). +edge(31, 69). +edge(31, 26). +edge(31, 77). +edge(31, 75). +edge(31, 35). +edge(31, 66). +edge(31, 3). +edge(31, 6). +edge(31, 98). +edge(31, 83). +edge(31, 24). +edge(31, 67). +edge(31, 20). +edge(31, 78). +edge(31, 60). +edge(31, 9). +edge(31, 64). +edge(31, 40). +edge(31, 47). +edge(31, 1). +edge(31, 7). +edge(31, 42). +edge(31, 97). +edge(31, 21). +edge(31, 46). +edge(31, 95). +edge(31, 5). +edge(31, 32). +edge(31, 19). +edge(31, 50). +edge(31, 49). +edge(31, 48). +edge(31, 56). +edge(31, 90). +edge(31, 82). +edge(31, 18). +edge(31, 94). +edge(31, 36). +edge(31, 45). +edge(31, 43). +edge(31, 15). +edge(31, 76). +edge(31, 91). +edge(31, 96). +edge(32, 16). +edge(32, 79). +edge(32, 7). +edge(32, 13). +edge(32, 59). +edge(32, 35). +edge(32, 77). +edge(32, 22). +edge(32, 40). +edge(32, 21). +edge(32, 10). +edge(32, 53). +edge(32, 5). +edge(32, 69). +edge(32, 9). +edge(32, 11). +edge(32, 31). +edge(32, 76). +edge(32, 94). +edge(32, 42). +edge(32, 18). +edge(33, 94). +edge(33, 84). +edge(33, 19). +edge(33, 41). +edge(33, 90). +edge(33, 87). +edge(33, 36). +edge(33, 66). +edge(33, 47). +edge(33, 45). +edge(33, 46). +edge(33, 64). +edge(33, 98). +edge(33, 85). +edge(33, 73). +edge(33, 23). +edge(33, 52). +edge(33, 62). +edge(33, 71). +edge(33, 42). +edge(33, 86). +edge(33, 92). +edge(33, 49). +edge(33, 26). +edge(33, 31). +edge(33, 91). +edge(33, 8). +edge(33, 54). +edge(33, 65). +edge(33, 37). +edge(33, 13). +edge(33, 72). +edge(33, 3). +edge(33, 88). +edge(33, 95). +edge(33, 50). +edge(33, 17). +edge(33, 18). +edge(33, 25). +edge(34, 94). +edge(34, 27). +edge(34, 98). +edge(34, 18). +edge(34, 26). +edge(34, 25). +edge(34, 50). +edge(34, 96). +edge(34, 64). +edge(34, 41). +edge(34, 20). +edge(34, 61). +edge(34, 82). +edge(34, 73). +edge(34, 23). +edge(34, 58). +edge(34, 71). +edge(34, 85). +edge(34, 69). +edge(34, 90). +edge(34, 30). +edge(34, 46). +edge(34, 32). +edge(34, 63). +edge(34, 87). +edge(34, 52). +edge(35, 8). +edge(35, 33). +edge(35, 92). +edge(35, 7). +edge(35, 5). +edge(35, 79). +edge(35, 62). +edge(35, 3). +edge(35, 43). +edge(35, 89). +edge(35, 54). +edge(35, 36). +edge(35, 83). +edge(35, 58). +edge(35, 60). +edge(35, 90). +edge(35, 65). +edge(35, 51). +edge(35, 45). +edge(35, 94). +edge(35, 53). +edge(35, 88). +edge(35, 71). +edge(35, 44). +edge(35, 23). +edge(35, 93). +edge(35, 96). +edge(35, 91). +edge(35, 57). +edge(35, 32). +edge(35, 17). +edge(35, 99). +edge(35, 9). +edge(35, 19). +edge(35, 55). +edge(35, 12). +edge(35, 84). +edge(36, 59). +edge(36, 8). +edge(36, 18). +edge(36, 92). +edge(36, 37). +edge(36, 29). +edge(36, 85). +edge(36, 10). +edge(37, 43). +edge(37, 28). +edge(37, 18). +edge(37, 70). +edge(37, 56). +edge(37, 10). +edge(37, 4). +edge(37, 92). +edge(37, 24). +edge(37, 36). +edge(37, 26). +edge(37, 44). +edge(37, 55). +edge(37, 25). +edge(37, 31). +edge(37, 8). +edge(37, 62). +edge(37, 38). +edge(37, 60). +edge(37, 84). +edge(37, 7). +edge(37, 85). +edge(37, 68). +edge(37, 9). +edge(37, 66). +edge(37, 49). +edge(37, 42). +edge(37, 33). +edge(37, 76). +edge(37, 35). +edge(37, 59). +edge(37, 50). +edge(37, 91). +edge(37, 75). +edge(37, 41). +edge(37, 15). +edge(37, 73). +edge(38, 44). +edge(38, 33). +edge(38, 65). +edge(38, 68). +edge(38, 73). +edge(38, 2). +edge(38, 22). +edge(38, 25). +edge(38, 70). +edge(38, 29). +edge(38, 3). +edge(38, 87). +edge(38, 26). +edge(38, 1). +edge(38, 83). +edge(38, 54). +edge(38, 39). +edge(38, 18). +edge(38, 49). +edge(38, 94). +edge(38, 84). +edge(38, 50). +edge(38, 95). +edge(38, 56). +edge(38, 9). +edge(38, 99). +edge(38, 57). +edge(38, 55). +edge(38, 37). +edge(38, 12). +edge(38, 47). +edge(38, 91). +edge(38, 8). +edge(38, 90). +edge(38, 4). +edge(38, 21). +edge(38, 27). +edge(38, 98). +edge(38, 16). +edge(38, 80). +edge(38, 96). +edge(38, 20). +edge(38, 28). +edge(38, 41). +edge(38, 7). +edge(38, 89). +edge(38, 79). +edge(38, 77). +edge(39, 28). +edge(39, 63). +edge(39, 92). +edge(39, 61). +edge(39, 40). +edge(39, 9). +edge(39, 12). +edge(39, 53). +edge(39, 85). +edge(39, 50). +edge(39, 30). +edge(39, 95). +edge(39, 56). +edge(39, 21). +edge(39, 20). +edge(39, 98). +edge(39, 82). +edge(39, 79). +edge(39, 22). +edge(40, 43). +edge(40, 54). +edge(40, 15). +edge(40, 83). +edge(40, 41). +edge(40, 22). +edge(40, 70). +edge(40, 36). +edge(40, 55). +edge(40, 1). +edge(40, 68). +edge(40, 60). +edge(40, 97). +edge(40, 71). +edge(40, 30). +edge(40, 19). +edge(40, 27). +edge(40, 81). +edge(40, 14). +edge(40, 62). +edge(40, 93). +edge(40, 47). +edge(40, 3). +edge(40, 49). +edge(40, 46). +edge(40, 34). +edge(40, 35). +edge(40, 92). +edge(40, 86). +edge(41, 77). +edge(41, 79). +edge(41, 42). +edge(41, 44). +edge(41, 20). +edge(41, 80). +edge(41, 54). +edge(41, 82). +edge(41, 12). +edge(41, 38). +edge(41, 96). +edge(41, 23). +edge(41, 34). +edge(41, 74). +edge(41, 71). +edge(41, 95). +edge(41, 31). +edge(41, 43). +edge(41, 84). +edge(41, 6). +edge(41, 69). +edge(41, 98). +edge(41, 60). +edge(41, 35). +edge(41, 1). +edge(41, 29). +edge(41, 92). +edge(41, 56). +edge(41, 13). +edge(41, 88). +edge(41, 21). +edge(41, 26). +edge(41, 68). +edge(41, 78). +edge(41, 28). +edge(41, 46). +edge(41, 36). +edge(41, 53). +edge(41, 73). +edge(41, 63). +edge(41, 83). +edge(41, 8). +edge(41, 67). +edge(41, 97). +edge(41, 30). +edge(41, 10). +edge(41, 72). +edge(42, 59). +edge(42, 64). +edge(42, 77). +edge(42, 95). +edge(42, 23). +edge(42, 71). +edge(42, 32). +edge(42, 17). +edge(42, 45). +edge(42, 76). +edge(42, 8). +edge(42, 3). +edge(42, 21). +edge(42, 78). +edge(42, 93). +edge(42, 97). +edge(42, 65). +edge(42, 89). +edge(42, 39). +edge(42, 20). +edge(42, 4). +edge(42, 66). +edge(42, 69). +edge(42, 16). +edge(42, 52). +edge(42, 86). +edge(42, 9). +edge(42, 15). +edge(42, 60). +edge(42, 41). +edge(42, 81). +edge(42, 18). +edge(42, 99). +edge(42, 75). +edge(42, 70). +edge(42, 79). +edge(42, 38). +edge(42, 22). +edge(42, 19). +edge(42, 36). +edge(42, 26). +edge(42, 6). +edge(42, 53). +edge(42, 35). +edge(42, 33). +edge(42, 10). +edge(42, 13). +edge(43, 2). +edge(43, 84). +edge(43, 17). +edge(43, 88). +edge(43, 79). +edge(43, 87). +edge(43, 85). +edge(43, 1). +edge(43, 70). +edge(43, 89). +edge(43, 5). +edge(43, 24). +edge(43, 10). +edge(43, 58). +edge(43, 28). +edge(43, 12). +edge(43, 41). +edge(43, 94). +edge(43, 7). +edge(43, 61). +edge(43, 96). +edge(43, 62). +edge(43, 63). +edge(43, 26). +edge(43, 22). +edge(43, 27). +edge(43, 66). +edge(43, 25). +edge(43, 50). +edge(43, 74). +edge(43, 91). +edge(43, 13). +edge(43, 65). +edge(43, 29). +edge(43, 99). +edge(43, 9). +edge(43, 81). +edge(43, 47). +edge(43, 57). +edge(43, 44). +edge(43, 52). +edge(43, 16). +edge(43, 72). +edge(43, 68). +edge(43, 76). +edge(43, 64). +edge(43, 46). +edge(43, 23). +edge(43, 54). +edge(43, 30). +edge(43, 69). +edge(43, 8). +edge(43, 55). +edge(43, 14). +edge(43, 35). +edge(43, 49). +edge(44, 72). +edge(44, 12). +edge(44, 47). +edge(44, 69). +edge(44, 73). +edge(44, 76). +edge(44, 33). +edge(44, 62). +edge(44, 60). +edge(44, 3). +edge(44, 26). +edge(44, 95). +edge(44, 49). +edge(44, 5). +edge(44, 40). +edge(44, 85). +edge(44, 29). +edge(44, 87). +edge(44, 91). +edge(44, 10). +edge(44, 19). +edge(44, 13). +edge(44, 70). +edge(44, 84). +edge(44, 78). +edge(44, 20). +edge(44, 4). +edge(44, 66). +edge(44, 81). +edge(44, 51). +edge(44, 58). +edge(44, 90). +edge(44, 64). +edge(44, 31). +edge(44, 52). +edge(44, 88). +edge(44, 42). +edge(44, 7). +edge(44, 48). +edge(44, 77). +edge(44, 45). +edge(45, 29). +edge(45, 85). +edge(45, 32). +edge(45, 66). +edge(45, 60). +edge(45, 9). +edge(45, 15). +edge(45, 70). +edge(45, 25). +edge(45, 5). +edge(45, 81). +edge(45, 58). +edge(45, 86). +edge(45, 10). +edge(45, 72). +edge(45, 83). +edge(45, 49). +edge(45, 75). +edge(45, 61). +edge(45, 3). +edge(45, 2). +edge(45, 87). +edge(45, 20). +edge(45, 89). +edge(45, 98). +edge(46, 79). +edge(46, 81). +edge(46, 38). +edge(46, 78). +edge(46, 27). +edge(46, 68). +edge(46, 20). +edge(46, 40). +edge(46, 86). +edge(46, 98). +edge(46, 82). +edge(46, 61). +edge(46, 91). +edge(46, 28). +edge(46, 95). +edge(46, 75). +edge(46, 48). +edge(46, 62). +edge(46, 15). +edge(46, 66). +edge(46, 56). +edge(46, 51). +edge(46, 88). +edge(46, 33). +edge(46, 59). +edge(46, 9). +edge(46, 89). +edge(46, 39). +edge(46, 45). +edge(46, 23). +edge(46, 76). +edge(46, 49). +edge(46, 52). +edge(46, 1). +edge(46, 10). +edge(46, 50). +edge(46, 12). +edge(46, 85). +edge(46, 36). +edge(46, 71). +edge(46, 99). +edge(46, 25). +edge(46, 3). +edge(46, 70). +edge(46, 17). +edge(46, 29). +edge(46, 32). +edge(46, 63). +edge(46, 83). +edge(46, 64). +edge(46, 65). +edge(46, 55). +edge(46, 18). +edge(46, 73). +edge(46, 97). +edge(47, 58). +edge(47, 30). +edge(47, 81). +edge(47, 43). +edge(47, 32). +edge(47, 67). +edge(47, 69). +edge(47, 16). +edge(47, 72). +edge(47, 52). +edge(47, 42). +edge(47, 46). +edge(47, 25). +edge(47, 15). +edge(47, 78). +edge(47, 38). +edge(47, 37). +edge(47, 98). +edge(47, 68). +edge(47, 17). +edge(47, 65). +edge(47, 87). +edge(47, 41). +edge(47, 19). +edge(47, 7). +edge(47, 48). +edge(47, 1). +edge(47, 18). +edge(47, 88). +edge(47, 95). +edge(47, 64). +edge(47, 82). +edge(47, 20). +edge(47, 83). +edge(47, 5). +edge(47, 96). +edge(47, 50). +edge(47, 34). +edge(48, 72). +edge(48, 5). +edge(48, 95). +edge(48, 84). +edge(48, 11). +edge(48, 76). +edge(48, 13). +edge(48, 9). +edge(48, 7). +edge(48, 80). +edge(48, 21). +edge(48, 50). +edge(48, 4). +edge(48, 70). +edge(48, 38). +edge(48, 85). +edge(48, 52). +edge(48, 14). +edge(48, 32). +edge(48, 87). +edge(48, 27). +edge(48, 57). +edge(48, 20). +edge(48, 43). +edge(48, 97). +edge(48, 98). +edge(48, 64). +edge(48, 68). +edge(49, 81). +edge(49, 24). +edge(49, 29). +edge(49, 28). +edge(49, 95). +edge(49, 72). +edge(49, 91). +edge(49, 50). +edge(49, 13). +edge(49, 75). +edge(49, 4). +edge(49, 66). +edge(49, 83). +edge(49, 31). +edge(49, 84). +edge(49, 79). +edge(49, 77). +edge(49, 51). +edge(49, 69). +edge(49, 93). +edge(49, 71). +edge(49, 62). +edge(49, 99). +edge(49, 3). +edge(49, 14). +edge(50, 98). +edge(50, 27). +edge(50, 13). +edge(50, 60). +edge(50, 14). +edge(50, 80). +edge(50, 41). +edge(50, 20). +edge(50, 67). +edge(50, 75). +edge(50, 7). +edge(50, 63). +edge(50, 81). +edge(50, 64). +edge(50, 59). +edge(50, 77). +edge(50, 3). +edge(50, 10). +edge(50, 87). +edge(50, 66). +edge(50, 65). +edge(50, 5). +edge(50, 21). +edge(50, 89). +edge(50, 82). +edge(50, 34). +edge(50, 90). +edge(50, 40). +edge(50, 28). +edge(50, 17). +edge(50, 11). +edge(50, 47). +edge(50, 18). +edge(50, 46). +edge(50, 31). +edge(50, 8). +edge(50, 35). +edge(50, 15). +edge(50, 61). +edge(50, 36). +edge(50, 4). +edge(50, 85). +edge(50, 72). +edge(50, 70). +edge(50, 79). +edge(50, 55). +edge(50, 45). +edge(50, 19). +edge(50, 26). +edge(50, 83). +edge(50, 48). +edge(50, 93). +edge(51, 95). +edge(51, 30). +edge(51, 29). +edge(51, 16). +edge(51, 5). +edge(51, 62). +edge(51, 31). +edge(51, 69). +edge(51, 80). +edge(51, 24). +edge(51, 65). +edge(51, 83). +edge(51, 12). +edge(51, 49). +edge(51, 98). +edge(51, 37). +edge(51, 81). +edge(51, 70). +edge(51, 82). +edge(51, 25). +edge(51, 48). +edge(51, 28). +edge(51, 84). +edge(51, 40). +edge(51, 45). +edge(51, 21). +edge(51, 41). +edge(51, 26). +edge(51, 99). +edge(51, 20). +edge(51, 10). +edge(51, 64). +edge(51, 35). +edge(51, 93). +edge(51, 8). +edge(51, 39). +edge(52, 33). +edge(52, 44). +edge(53, 79). +edge(53, 66). +edge(53, 13). +edge(53, 81). +edge(53, 35). +edge(53, 86). +edge(53, 92). +edge(53, 15). +edge(53, 95). +edge(53, 72). +edge(53, 87). +edge(53, 84). +edge(53, 26). +edge(53, 22). +edge(53, 58). +edge(53, 9). +edge(53, 63). +edge(54, 13). +edge(54, 60). +edge(54, 30). +edge(54, 25). +edge(54, 35). +edge(54, 63). +edge(54, 17). +edge(54, 85). +edge(54, 24). +edge(54, 28). +edge(54, 20). +edge(54, 39). +edge(54, 47). +edge(55, 40). +edge(55, 95). +edge(55, 81). +edge(55, 96). +edge(55, 86). +edge(55, 76). +edge(55, 58). +edge(55, 32). +edge(55, 99). +edge(55, 83). +edge(55, 64). +edge(55, 91). +edge(55, 31). +edge(55, 14). +edge(55, 62). +edge(55, 74). +edge(55, 94). +edge(55, 3). +edge(55, 85). +edge(55, 66). +edge(55, 10). +edge(55, 65). +edge(55, 80). +edge(55, 5). +edge(56, 31). +edge(56, 74). +edge(56, 15). +edge(56, 79). +edge(56, 54). +edge(56, 57). +edge(56, 51). +edge(56, 73). +edge(56, 40). +edge(56, 71). +edge(56, 80). +edge(56, 70). +edge(56, 29). +edge(57, 24). +edge(57, 93). +edge(57, 2). +edge(57, 59). +edge(58, 94). +edge(58, 50). +edge(58, 49). +edge(58, 47). +edge(58, 40). +edge(58, 56). +edge(58, 28). +edge(58, 15). +edge(59, 97). +edge(59, 50). +edge(59, 91). +edge(59, 16). +edge(59, 48). +edge(59, 40). +edge(59, 57). +edge(59, 94). +edge(59, 64). +edge(59, 56). +edge(59, 23). +edge(59, 29). +edge(59, 87). +edge(59, 14). +edge(59, 13). +edge(59, 54). +edge(59, 27). +edge(59, 19). +edge(59, 84). +edge(59, 58). +edge(59, 82). +edge(59, 30). +edge(59, 24). +edge(59, 18). +edge(59, 9). +edge(59, 39). +edge(59, 81). +edge(59, 96). +edge(59, 69). +edge(59, 46). +edge(59, 12). +edge(59, 52). +edge(59, 67). +edge(59, 31). +edge(59, 7). +edge(59, 3). +edge(59, 45). +edge(59, 42). +edge(59, 33). +edge(59, 17). +edge(59, 51). +edge(59, 92). +edge(59, 10). +edge(59, 66). +edge(59, 49). +edge(59, 36). +edge(59, 74). +edge(60, 29). +edge(61, 54). +edge(61, 62). +edge(61, 92). +edge(61, 45). +edge(61, 53). +edge(61, 95). +edge(61, 69). +edge(61, 49). +edge(61, 32). +edge(61, 96). +edge(61, 26). +edge(61, 83). +edge(61, 88). +edge(61, 39). +edge(61, 27). +edge(61, 36). +edge(61, 94). +edge(61, 98). +edge(61, 72). +edge(61, 9). +edge(61, 93). +edge(61, 25). +edge(61, 79). +edge(61, 97). +edge(61, 20). +edge(61, 18). +edge(61, 51). +edge(61, 55). +edge(61, 29). +edge(61, 50). +edge(61, 43). +edge(61, 90). +edge(61, 86). +edge(61, 10). +edge(61, 91). +edge(61, 4). +edge(61, 76). +edge(61, 85). +edge(61, 68). +edge(61, 13). +edge(61, 64). +edge(61, 24). +edge(61, 66). +edge(61, 81). +edge(61, 8). +edge(61, 73). +edge(61, 77). +edge(62, 38). +edge(62, 96). +edge(62, 51). +edge(62, 37). +edge(62, 68). +edge(62, 2). +edge(62, 46). +edge(62, 39). +edge(62, 32). +edge(62, 25). +edge(62, 97). +edge(62, 71). +edge(62, 35). +edge(62, 5). +edge(62, 73). +edge(62, 3). +edge(62, 76). +edge(62, 85). +edge(62, 28). +edge(62, 20). +edge(62, 8). +edge(62, 30). +edge(62, 99). +edge(62, 91). +edge(62, 93). +edge(62, 64). +edge(62, 42). +edge(62, 59). +edge(62, 14). +edge(62, 31). +edge(62, 4). +edge(62, 10). +edge(62, 54). +edge(62, 41). +edge(62, 34). +edge(62, 80). +edge(63, 73). +edge(63, 85). +edge(63, 3). +edge(63, 15). +edge(63, 49). +edge(63, 55). +edge(63, 93). +edge(63, 35). +edge(63, 66). +edge(63, 8). +edge(63, 75). +edge(63, 78). +edge(63, 61). +edge(63, 80). +edge(63, 46). +edge(63, 56). +edge(63, 95). +edge(63, 2). +edge(63, 86). +edge(63, 13). +edge(63, 48). +edge(63, 31). +edge(63, 10). +edge(63, 16). +edge(63, 23). +edge(63, 39). +edge(63, 71). +edge(63, 70). +edge(63, 69). +edge(63, 4). +edge(63, 67). +edge(63, 32). +edge(63, 28). +edge(63, 98). +edge(63, 14). +edge(63, 91). +edge(63, 89). +edge(63, 84). +edge(63, 27). +edge(63, 40). +edge(63, 42). +edge(63, 72). +edge(63, 97). +edge(63, 37). +edge(63, 57). +edge(63, 12). +edge(63, 90). +edge(64, 4). +edge(64, 86). +edge(64, 57). +edge(64, 46). +edge(64, 39). +edge(64, 68). +edge(64, 97). +edge(64, 33). +edge(64, 1). +edge(64, 47). +edge(64, 62). +edge(64, 76). +edge(64, 51). +edge(64, 71). +edge(64, 58). +edge(64, 82). +edge(64, 29). +edge(64, 6). +edge(64, 40). +edge(64, 83). +edge(64, 90). +edge(64, 65). +edge(64, 80). +edge(64, 66). +edge(64, 34). +edge(64, 44). +edge(64, 54). +edge(64, 41). +edge(64, 19). +edge(64, 16). +edge(64, 14). +edge(64, 35). +edge(64, 94). +edge(64, 92). +edge(65, 15). +edge(65, 90). +edge(65, 34). +edge(65, 38). +edge(65, 29). +edge(65, 27). +edge(65, 8). +edge(65, 31). +edge(65, 39). +edge(65, 5). +edge(65, 23). +edge(65, 79). +edge(65, 50). +edge(65, 4). +edge(65, 41). +edge(65, 28). +edge(65, 22). +edge(65, 73). +edge(65, 6). +edge(65, 77). +edge(65, 9). +edge(65, 21). +edge(65, 71). +edge(65, 60). +edge(65, 97). +edge(65, 87). +edge(65, 51). +edge(65, 19). +edge(65, 70). +edge(66, 83). +edge(66, 80). +edge(66, 10). +edge(66, 65). +edge(66, 29). +edge(66, 8). +edge(66, 45). +edge(66, 84). +edge(66, 34). +edge(66, 4). +edge(66, 25). +edge(66, 71). +edge(66, 93). +edge(66, 57). +edge(66, 20). +edge(66, 22). +edge(66, 31). +edge(66, 41). +edge(66, 14). +edge(66, 6). +edge(66, 27). +edge(66, 44). +edge(66, 1). +edge(66, 32). +edge(66, 50). +edge(66, 60). +edge(66, 51). +edge(67, 2). +edge(67, 84). +edge(67, 65). +edge(67, 20). +edge(67, 52). +edge(67, 24). +edge(67, 82). +edge(67, 22). +edge(67, 10). +edge(67, 8). +edge(67, 55). +edge(67, 81). +edge(67, 90). +edge(67, 57). +edge(67, 9). +edge(67, 45). +edge(67, 43). +edge(67, 71). +edge(67, 99). +edge(67, 51). +edge(67, 79). +edge(67, 21). +edge(68, 29). +edge(68, 42). +edge(68, 35). +edge(68, 95). +edge(68, 21). +edge(68, 91). +edge(68, 4). +edge(69, 38). +edge(69, 2). +edge(69, 98). +edge(69, 17). +edge(69, 82). +edge(69, 57). +edge(69, 65). +edge(69, 71). +edge(69, 61). +edge(69, 58). +edge(69, 91). +edge(69, 23). +edge(69, 22). +edge(69, 56). +edge(69, 42). +edge(69, 35). +edge(69, 86). +edge(69, 55). +edge(69, 47). +edge(69, 37). +edge(69, 34). +edge(69, 21). +edge(69, 1). +edge(69, 92). +edge(69, 89). +edge(69, 40). +edge(69, 19). +edge(69, 85). +edge(69, 93). +edge(69, 90). +edge(69, 99). +edge(70, 62). +edge(70, 48). +edge(70, 22). +edge(70, 56). +edge(70, 5). +edge(70, 58). +edge(70, 68). +edge(70, 38). +edge(70, 74). +edge(70, 35). +edge(70, 63). +edge(70, 64). +edge(70, 73). +edge(70, 66). +edge(70, 71). +edge(70, 33). +edge(70, 32). +edge(70, 30). +edge(70, 55). +edge(70, 91). +edge(70, 81). +edge(70, 27). +edge(70, 40). +edge(70, 36). +edge(70, 21). +edge(70, 19). +edge(70, 86). +edge(70, 82). +edge(70, 10). +edge(70, 31). +edge(70, 47). +edge(70, 90). +edge(70, 20). +edge(70, 78). +edge(70, 17). +edge(70, 84). +edge(70, 65). +edge(70, 34). +edge(70, 97). +edge(70, 11). +edge(70, 26). +edge(70, 95). +edge(70, 93). +edge(70, 57). +edge(71, 16). +edge(71, 7). +edge(71, 3). +edge(71, 50). +edge(71, 6). +edge(71, 83). +edge(71, 72). +edge(71, 88). +edge(71, 45). +edge(71, 70). +edge(71, 90). +edge(71, 46). +edge(71, 38). +edge(71, 1). +edge(71, 60). +edge(71, 31). +edge(71, 40). +edge(71, 79). +edge(71, 57). +edge(71, 44). +edge(71, 89). +edge(71, 39). +edge(71, 53). +edge(71, 98). +edge(71, 25). +edge(71, 13). +edge(71, 49). +edge(71, 95). +edge(71, 68). +edge(71, 8). +edge(71, 23). +edge(71, 75). +edge(71, 52). +edge(71, 48). +edge(71, 34). +edge(71, 85). +edge(71, 33). +edge(71, 26). +edge(71, 32). +edge(71, 80). +edge(71, 17). +edge(71, 9). +edge(71, 55). +edge(71, 92). +edge(71, 27). +edge(71, 20). +edge(71, 29). +edge(71, 10). +edge(71, 18). +edge(71, 43). +edge(72, 77). +edge(72, 76). +edge(72, 73). +edge(72, 89). +edge(72, 58). +edge(72, 6). +edge(72, 3). +edge(72, 75). +edge(72, 99). +edge(72, 92). +edge(72, 57). +edge(72, 56). +edge(72, 52). +edge(72, 9). +edge(72, 20). +edge(72, 69). +edge(72, 95). +edge(72, 91). +edge(72, 45). +edge(72, 38). +edge(72, 44). +edge(72, 35). +edge(72, 46). +edge(72, 81). +edge(72, 90). +edge(72, 54). +edge(72, 39). +edge(72, 1). +edge(72, 50). +edge(72, 40). +edge(72, 80). +edge(72, 71). +edge(72, 55). +edge(72, 19). +edge(73, 1). +edge(73, 81). +edge(73, 16). +edge(73, 44). +edge(73, 9). +edge(73, 74). +edge(73, 95). +edge(73, 79). +edge(73, 30). +edge(74, 83). +edge(74, 39). +edge(74, 9). +edge(74, 4). +edge(74, 23). +edge(75, 87). +edge(75, 92). +edge(75, 52). +edge(75, 39). +edge(75, 59). +edge(75, 67). +edge(75, 76). +edge(75, 61). +edge(75, 69). +edge(75, 63). +edge(75, 84). +edge(75, 2). +edge(75, 1). +edge(75, 41). +edge(75, 20). +edge(75, 82). +edge(75, 73). +edge(75, 4). +edge(75, 44). +edge(75, 11). +edge(76, 46). +edge(76, 88). +edge(76, 77). +edge(76, 65). +edge(76, 49). +edge(76, 13). +edge(76, 6). +edge(76, 33). +edge(76, 32). +edge(76, 50). +edge(76, 38). +edge(76, 9). +edge(76, 10). +edge(76, 1). +edge(76, 20). +edge(76, 68). +edge(76, 82). +edge(76, 87). +edge(76, 23). +edge(76, 25). +edge(76, 15). +edge(76, 78). +edge(76, 71). +edge(76, 80). +edge(76, 41). +edge(76, 94). +edge(76, 58). +edge(76, 17). +edge(76, 3). +edge(76, 11). +edge(76, 31). +edge(76, 30). +edge(76, 54). +edge(76, 83). +edge(76, 44). +edge(76, 96). +edge(76, 16). +edge(76, 95). +edge(76, 29). +edge(76, 63). +edge(76, 5). +edge(76, 97). +edge(76, 36). +edge(76, 74). +edge(76, 92). +edge(76, 69). +edge(76, 91). +edge(76, 21). +edge(76, 86). +edge(76, 26). +edge(76, 52). +edge(77, 36). +edge(77, 42). +edge(77, 86). +edge(77, 46). +edge(77, 74). +edge(77, 71). +edge(77, 25). +edge(77, 79). +edge(77, 20). +edge(77, 73). +edge(77, 14). +edge(77, 50). +edge(77, 39). +edge(77, 59). +edge(77, 24). +edge(77, 76). +edge(77, 22). +edge(77, 1). +edge(77, 81). +edge(77, 78). +edge(77, 88). +edge(77, 11). +edge(78, 26). +edge(78, 90). +edge(78, 20). +edge(78, 23). +edge(78, 45). +edge(78, 14). +edge(78, 46). +edge(78, 13). +edge(78, 30). +edge(78, 33). +edge(78, 91). +edge(78, 60). +edge(78, 37). +edge(78, 56). +edge(78, 40). +edge(78, 18). +edge(78, 95). +edge(78, 75). +edge(78, 28). +edge(78, 69). +edge(78, 73). +edge(78, 50). +edge(78, 97). +edge(78, 24). +edge(78, 86). +edge(78, 87). +edge(78, 53). +edge(78, 59). +edge(78, 89). +edge(78, 83). +edge(78, 29). +edge(78, 71). +edge(78, 21). +edge(78, 94). +edge(78, 61). +edge(78, 49). +edge(78, 66). +edge(78, 68). +edge(78, 6). +edge(78, 22). +edge(78, 51). +edge(78, 10). +edge(78, 74). +edge(78, 88). +edge(78, 27). +edge(78, 62). +edge(78, 47). +edge(78, 84). +edge(78, 98). +edge(78, 36). +edge(79, 56). +edge(79, 26). +edge(79, 57). +edge(79, 85). +edge(79, 55). +edge(79, 73). +edge(79, 83). +edge(79, 59). +edge(79, 96). +edge(79, 36). +edge(79, 22). +edge(79, 92). +edge(80, 96). +edge(80, 42). +edge(80, 40). +edge(80, 91). +edge(80, 5). +edge(80, 74). +edge(80, 43). +edge(80, 88). +edge(80, 25). +edge(80, 2). +edge(80, 21). +edge(80, 92). +edge(80, 81). +edge(80, 86). +edge(80, 49). +edge(80, 75). +edge(80, 4). +edge(80, 1). +edge(80, 83). +edge(80, 94). +edge(80, 35). +edge(80, 13). +edge(80, 16). +edge(80, 47). +edge(80, 27). +edge(80, 32). +edge(80, 26). +edge(80, 58). +edge(80, 76). +edge(80, 36). +edge(80, 28). +edge(80, 90). +edge(80, 87). +edge(80, 48). +edge(80, 18). +edge(80, 37). +edge(80, 24). +edge(80, 7). +edge(80, 38). +edge(80, 69). +edge(80, 67). +edge(80, 93). +edge(80, 12). +edge(80, 78). +edge(80, 14). +edge(80, 45). +edge(80, 95). +edge(80, 50). +edge(80, 64). +edge(80, 84). +edge(81, 5). +edge(81, 83). +edge(81, 22). +edge(81, 89). +edge(81, 34). +edge(81, 36). +edge(81, 91). +edge(81, 4). +edge(81, 10). +edge(81, 37). +edge(81, 94). +edge(81, 59). +edge(81, 44). +edge(81, 96). +edge(81, 54). +edge(81, 61). +edge(81, 31). +edge(81, 64). +edge(81, 43). +edge(81, 16). +edge(81, 88). +edge(81, 8). +edge(81, 98). +edge(81, 67). +edge(81, 50). +edge(81, 45). +edge(81, 66). +edge(81, 87). +edge(81, 93). +edge(81, 15). +edge(81, 39). +edge(81, 28). +edge(81, 63). +edge(81, 11). +edge(81, 77). +edge(81, 78). +edge(81, 14). +edge(81, 12). +edge(81, 95). +edge(81, 70). +edge(81, 99). +edge(81, 40). +edge(81, 71). +edge(81, 7). +edge(82, 22). +edge(82, 57). +edge(82, 29). +edge(82, 92). +edge(82, 15). +edge(82, 21). +edge(82, 78). +edge(82, 53). +edge(82, 94). +edge(82, 95). +edge(82, 30). +edge(82, 84). +edge(82, 64). +edge(82, 72). +edge(82, 19). +edge(82, 81). +edge(82, 18). +edge(82, 89). +edge(82, 67). +edge(82, 76). +edge(82, 70). +edge(82, 4). +edge(82, 2). +edge(82, 61). +edge(82, 68). +edge(82, 17). +edge(82, 28). +edge(82, 46). +edge(82, 5). +edge(82, 16). +edge(82, 85). +edge(82, 8). +edge(82, 24). +edge(82, 49). +edge(82, 99). +edge(82, 39). +edge(82, 25). +edge(82, 26). +edge(82, 40). +edge(82, 71). +edge(82, 97). +edge(82, 13). +edge(82, 10). +edge(82, 9). +edge(82, 38). +edge(82, 83). +edge(82, 27). +edge(82, 44). +edge(82, 79). +edge(82, 48). +edge(82, 41). +edge(82, 31). +edge(82, 54). +edge(83, 4). +edge(83, 42). +edge(83, 20). +edge(83, 2). +edge(83, 95). +edge(83, 70). +edge(83, 3). +edge(83, 98). +edge(83, 67). +edge(83, 1). +edge(83, 14). +edge(83, 56). +edge(83, 82). +edge(83, 46). +edge(83, 63). +edge(83, 62). +edge(83, 90). +edge(83, 96). +edge(83, 59). +edge(83, 68). +edge(83, 26). +edge(83, 38). +edge(83, 81). +edge(83, 75). +edge(83, 72). +edge(83, 34). +edge(83, 35). +edge(83, 27). +edge(83, 78). +edge(83, 97). +edge(83, 43). +edge(83, 25). +edge(83, 60). +edge(83, 55). +edge(83, 89). +edge(83, 10). +edge(83, 40). +edge(83, 6). +edge(83, 49). +edge(83, 45). +edge(83, 86). +edge(83, 77). +edge(83, 21). +edge(83, 99). +edge(83, 66). +edge(84, 44). +edge(84, 93). +edge(84, 76). +edge(84, 99). +edge(85, 17). +edge(85, 34). +edge(85, 86). +edge(85, 68). +edge(85, 37). +edge(85, 45). +edge(85, 50). +edge(85, 28). +edge(85, 70). +edge(85, 41). +edge(85, 4). +edge(85, 5). +edge(85, 94). +edge(85, 98). +edge(85, 51). +edge(85, 56). +edge(86, 36). +edge(86, 38). +edge(86, 54). +edge(86, 81). +edge(86, 2). +edge(86, 50). +edge(86, 8). +edge(86, 29). +edge(86, 83). +edge(86, 22). +edge(86, 35). +edge(86, 87). +edge(86, 15). +edge(86, 76). +edge(86, 9). +edge(86, 98). +edge(86, 4). +edge(86, 43). +edge(86, 53). +edge(87, 31). +edge(87, 94). +edge(87, 24). +edge(87, 43). +edge(87, 21). +edge(87, 16). +edge(87, 25). +edge(87, 66). +edge(87, 58). +edge(87, 23). +edge(87, 63). +edge(87, 42). +edge(87, 57). +edge(87, 18). +edge(87, 84). +edge(87, 62). +edge(87, 97). +edge(87, 68). +edge(87, 88). +edge(87, 13). +edge(87, 82). +edge(87, 92). +edge(87, 19). +edge(87, 17). +edge(87, 75). +edge(87, 27). +edge(87, 7). +edge(87, 91). +edge(87, 77). +edge(87, 5). +edge(87, 50). +edge(87, 38). +edge(87, 49). +edge(87, 26). +edge(87, 12). +edge(87, 41). +edge(87, 30). +edge(87, 70). +edge(87, 53). +edge(87, 33). +edge(87, 46). +edge(87, 86). +edge(87, 59). +edge(87, 47). +edge(88, 89). +edge(88, 95). +edge(88, 62). +edge(88, 63). +edge(88, 53). +edge(88, 46). +edge(88, 84). +edge(88, 54). +edge(88, 71). +edge(88, 39). +edge(88, 21). +edge(88, 26). +edge(88, 17). +edge(88, 59). +edge(88, 31). +edge(88, 10). +edge(88, 82). +edge(88, 20). +edge(88, 77). +edge(88, 9). +edge(88, 47). +edge(88, 28). +edge(88, 3). +edge(89, 75). +edge(89, 84). +edge(89, 47). +edge(89, 56). +edge(89, 91). +edge(89, 49). +edge(89, 79). +edge(89, 92). +edge(89, 50). +edge(89, 97). +edge(89, 70). +edge(89, 59). +edge(89, 57). +edge(89, 33). +edge(89, 83). +edge(89, 82). +edge(89, 67). +edge(89, 24). +edge(89, 22). +edge(89, 8). +edge(89, 51). +edge(89, 16). +edge(89, 13). +edge(89, 98). +edge(89, 94). +edge(89, 17). +edge(89, 43). +edge(89, 37). +edge(89, 53). +edge(89, 21). +edge(89, 78). +edge(89, 28). +edge(89, 4). +edge(89, 72). +edge(89, 65). +edge(89, 36). +edge(89, 55). +edge(89, 6). +edge(89, 30). +edge(90, 18). +edge(90, 26). +edge(90, 81). +edge(90, 40). +edge(90, 20). +edge(90, 25). +edge(90, 74). +edge(90, 23). +edge(90, 99). +edge(90, 2). +edge(90, 38). +edge(90, 47). +edge(90, 83). +edge(90, 28). +edge(90, 98). +edge(90, 42). +edge(90, 75). +edge(90, 80). +edge(90, 13). +edge(90, 85). +edge(90, 96). +edge(90, 24). +edge(90, 22). +edge(90, 12). +edge(90, 16). +edge(90, 59). +edge(90, 29). +edge(90, 3). +edge(90, 48). +edge(90, 61). +edge(90, 65). +edge(90, 63). +edge(90, 17). +edge(90, 6). +edge(90, 62). +edge(90, 53). +edge(90, 67). +edge(90, 32). +edge(90, 27). +edge(90, 55). +edge(90, 60). +edge(90, 72). +edge(90, 57). +edge(90, 11). +edge(90, 93). +edge(90, 50). +edge(90, 82). +edge(90, 77). +edge(90, 95). +edge(90, 91). +edge(90, 79). +edge(91, 34). +edge(91, 51). +edge(91, 84). +edge(91, 58). +edge(91, 87). +edge(91, 47). +edge(91, 73). +edge(91, 9). +edge(91, 13). +edge(91, 68). +edge(91, 70). +edge(91, 24). +edge(91, 5). +edge(91, 1). +edge(91, 74). +edge(91, 14). +edge(91, 55). +edge(91, 33). +edge(91, 37). +edge(91, 78). +edge(91, 20). +edge(91, 80). +edge(91, 75). +edge(91, 93). +edge(91, 44). +edge(91, 10). +edge(91, 59). +edge(91, 38). +edge(91, 15). +edge(91, 97). +edge(91, 12). +edge(91, 19). +edge(91, 60). +edge(91, 39). +edge(91, 40). +edge(91, 43). +edge(91, 28). +edge(91, 96). +edge(91, 77). +edge(91, 81). +edge(91, 26). +edge(91, 36). +edge(91, 46). +edge(91, 71). +edge(91, 48). +edge(91, 27). +edge(92, 61). +edge(92, 34). +edge(92, 59). +edge(92, 78). +edge(92, 65). +edge(92, 40). +edge(92, 37). +edge(92, 46). +edge(92, 47). +edge(92, 58). +edge(92, 27). +edge(92, 48). +edge(92, 4). +edge(92, 13). +edge(92, 23). +edge(92, 8). +edge(92, 86). +edge(92, 80). +edge(92, 33). +edge(92, 57). +edge(92, 30). +edge(92, 81). +edge(92, 16). +edge(92, 39). +edge(92, 17). +edge(92, 71). +edge(92, 44). +edge(92, 63). +edge(93, 99). +edge(93, 74). +edge(93, 92). +edge(93, 28). +edge(94, 55). +edge(94, 53). +edge(94, 93). +edge(94, 19). +edge(94, 38). +edge(94, 14). +edge(94, 82). +edge(94, 25). +edge(94, 12). +edge(94, 48). +edge(94, 88). +edge(94, 91). +edge(94, 44). +edge(94, 36). +edge(94, 61). +edge(94, 32). +edge(94, 20). +edge(94, 6). +edge(94, 33). +edge(94, 62). +edge(94, 54). +edge(94, 78). +edge(94, 86). +edge(94, 69). +edge(94, 10). +edge(94, 45). +edge(94, 5). +edge(94, 97). +edge(94, 71). +edge(94, 27). +edge(94, 83). +edge(94, 42). +edge(94, 92). +edge(94, 63). +edge(94, 95). +edge(94, 31). +edge(94, 46). +edge(94, 81). +edge(94, 73). +edge(94, 47). +edge(94, 87). +edge(94, 21). +edge(94, 39). +edge(94, 30). +edge(94, 74). +edge(94, 40). +edge(94, 96). +edge(94, 15). +edge(94, 84). +edge(95, 6). +edge(95, 68). +edge(95, 97). +edge(95, 1). +edge(95, 63). +edge(95, 19). +edge(95, 41). +edge(95, 64). +edge(95, 65). +edge(95, 96). +edge(95, 77). +edge(95, 93). +edge(95, 66). +edge(95, 34). +edge(95, 2). +edge(95, 58). +edge(95, 38). +edge(95, 24). +edge(95, 18). +edge(95, 82). +edge(95, 81). +edge(95, 76). +edge(95, 55). +edge(95, 37). +edge(95, 85). +edge(95, 36). +edge(95, 79). +edge(95, 7). +edge(95, 31). +edge(95, 42). +edge(95, 30). +edge(95, 45). +edge(95, 25). +edge(95, 71). +edge(95, 92). +edge(95, 62). +edge(95, 17). +edge(95, 51). +edge(95, 47). +edge(95, 98). +edge(95, 22). +edge(95, 46). +edge(95, 60). +edge(95, 33). +edge(95, 72). +edge(95, 73). +edge(95, 8). +edge(96, 2). +edge(96, 55). +edge(96, 7). +edge(96, 69). +edge(96, 59). +edge(96, 44). +edge(96, 73). +edge(96, 72). +edge(96, 41). +edge(96, 26). +edge(96, 56). +edge(96, 74). +edge(96, 33). +edge(97, 91). +edge(97, 63). +edge(97, 95). +edge(97, 47). +edge(97, 44). +edge(97, 18). +edge(97, 35). +edge(97, 60). +edge(97, 33). +edge(97, 88). +edge(97, 27). +edge(97, 37). +edge(97, 57). +edge(97, 31). +edge(97, 73). +edge(97, 11). +edge(97, 50). +edge(97, 81). +edge(97, 28). +edge(97, 25). +edge(97, 74). +edge(97, 86). +edge(97, 66). +edge(97, 70). +edge(97, 94). +edge(97, 93). +edge(97, 22). +edge(97, 79). +edge(97, 12). +edge(97, 13). +edge(97, 90). +edge(97, 76). +edge(97, 16). +edge(97, 10). +edge(97, 2). +edge(97, 34). +edge(97, 98). +edge(97, 38). +edge(97, 20). +edge(97, 40). +edge(97, 9). +edge(97, 30). +edge(97, 80). +edge(97, 8). +edge(98, 82). +edge(98, 16). +edge(98, 63). +edge(98, 56). +edge(98, 97). +edge(98, 76). +edge(98, 99). +edge(98, 21). +edge(98, 41). +edge(98, 58). +edge(98, 47). +edge(98, 32). +edge(98, 27). +edge(98, 6). +edge(98, 52). +edge(98, 5). +edge(98, 62). +edge(98, 33). +edge(98, 24). +edge(99, 29). +edge(99, 4). +edge(99, 1). +edge(99, 12). +edge(99, 40). +edge(99, 67). +edge(99, 45). +edge(99, 30). +edge(99, 8). +edge(99, 84). +edge(99, 41). +edge(99, 27). +edge(99, 32). +edge(99, 49). diff --git a/packages/meld/examples/pagerank/l4.meld b/packages/meld/examples/pagerank/l4.meld new file mode 100644 index 000000000..77d5acc62 --- /dev/null +++ b/packages/meld/examples/pagerank/l4.meld @@ -0,0 +1,7 @@ +%edge(0,1). +edge(0,4). +%edge(1,2). +edge(1,4). +%edge(2,3). +edge(2,4). +edge(3,4). diff --git a/packages/meld/examples/pagerank/pagerank.meld b/packages/meld/examples/pagerank/pagerank.meld new file mode 100644 index 000000000..d0c4756e2 --- /dev/null +++ b/packages/meld/examples/pagerank/pagerank.meld @@ -0,0 +1,49 @@ + +type rank(node, int, float). +type calcRank(node, int, sum float). +% type persistent numPages(node, int). +type persistent numPages(node, sum int). +type numLinks(node, sum int). +type path(node, node). + +const damping = 0.85. +const num_iterations = 100. +% extern float to_float(int). +% extern float float_abs(float). + +rank(A, 0, 1.0 / to_float(T)) :- numPages(A,T). +rank(A, I, V) :- + numLinks(B,L), + numPages(A, Ps), + calcRank(A, I, T), +% Before = I - 1, +% rank(A, Before, VOld), + V = damping + (1.0 - damping) * T, + I =< num_iterations. + +% //float_abs((damping + (1.0 - damping) * T) - VOld) > 0.001. + +calcRank(A, I + 1, 0.0) :- + rank(A, I, _). +calcRank(A, I + 1, O / to_float(C)) :- + edge(B, A), + rank(B, I, O), + numLinks(B, C). + +numLinks(A, 1) :- + edge(A,B). + +numPages(A, 1) :- path(A,_). + +path(A, B) :- + edge(A,B). +path(A, B) :- + edge(B,A). +path(A, B) :- + edge(A,C), + path(C,B). +path(A, B) :- + edge(C,A), + path(C,B). + + diff --git a/packages/meld/graph0.meld b/packages/meld/examples/temperature/graph0.meld similarity index 100% rename from packages/meld/graph0.meld rename to packages/meld/examples/temperature/graph0.meld diff --git a/packages/meld/graph1.meld b/packages/meld/examples/temperature/graph1.meld similarity index 100% rename from packages/meld/graph1.meld rename to packages/meld/examples/temperature/graph1.meld diff --git a/packages/meld/graph2.meld b/packages/meld/examples/temperature/graph2.meld similarity index 100% rename from packages/meld/graph2.meld rename to packages/meld/examples/temperature/graph2.meld diff --git a/packages/meld/graph3.meld b/packages/meld/examples/temperature/graph3.meld similarity index 100% rename from packages/meld/graph3.meld rename to packages/meld/examples/temperature/graph3.meld diff --git a/packages/meld/maxtemp.meld b/packages/meld/examples/temperature/maxtemp.meld similarity index 100% rename from packages/meld/maxtemp.meld rename to packages/meld/examples/temperature/maxtemp.meld diff --git a/packages/meld/meld.yap b/packages/meld/meld.yap index f03f40b33..34db94391 100644 --- a/packages/meld/meld.yap +++ b/packages/meld/meld.yap @@ -7,10 +7,14 @@ :- module(meld_core, [simulate/1, op(1200, fy, (type)), - op(1150, fy, (logical_neighbor)), - op(1150, fy, (extensional)), + op(1150, fy, (logical_neighbor)), + op(1150, fy, (const)), + op(1150, fy, (extensional)), + op(1150, fy, (persistent)), + op(1150, fy, (extern)), op( 500, fy, (first)), op( 500, fy, (max)), + op( 500, fy, (sum)), op( 950, fy, (forall)), op( 900, xfy, (then)) ]). diff --git a/packages/meld/meldc.yap b/packages/meld/meldc.yap index c9256bc02..a4228e0d3 100644 --- a/packages/meld/meldc.yap +++ b/packages/meld/meldc.yap @@ -1,3 +1,8 @@ +% +% A compiler for Meld programs +% can understand aggregates. +% + :- module(meld_compiler, [ mcompile/1, @@ -10,7 +15,8 @@ push/1, first/2, min/3, - max/3 + max/3, + sum/3 ]). :- use_module(library(meld)). @@ -19,6 +25,13 @@ variable_in_term/2 ]). +:- use_module(library(ordsets), [ + ord_subset/2, + ord_union/3 + ]). + +:- dynamic meld_constants:const/2. + mcompile(Program) :- open(Program, read, P), init_mcompile(Program), @@ -40,6 +53,9 @@ init_mcompile(Program) :- mcompile(type(T), Program, Vars) :- ground_term(T, Vars), type_declaration(T, Program), !. +mcompile(const(T=V), _Program, Vars) :- + ground_term(T, Vars), + const_declaration(T, V), !. mcompile((Head :- Body), _, _Vars) :- rule(Head, Body). @@ -50,6 +66,10 @@ type_declaration(extensional(T), Program) :- !, type_declaration(T, Program). type_declaration(logical_neighbor(T), Program) :- !, type_declaration(T, Program). +type_declaration(persistent(T), Program) :- !, + type_declaration(T, Program). +type_declaration(extern(T), Program) :- !, + type_declaration(T, Program). type_declaration(T, _) :- functor(T, N, A), dynamic(meld_program:N/A), @@ -68,9 +88,15 @@ assert_type(NT, Program, Agg) :- functor(Spec, Na, Ar), assert(type(Spec, NT, Program, Agg)). +const_declaration(C,V) :- !, + ( atom(C) -> true ; throw(type_error(atom,C),const(C=V))), + ( number(V) -> true ; throw(type_error(number,V),const(C=V))), + assert(meld_constants:const(C, V)). + check_aggregate([first(Type)|Args], I, [Type|Args], first, I) :- !. check_aggregate([max(Type)|Args], I, [Type|Args], max, I) :- !. check_aggregate([min(Type)|Args], I, [Type|Args], min, I) :- !. +check_aggregate([sum(Type)|Args], I, [Type|Args], sum, I) :- !. check_aggregate([Type|Args], I, [Type|NewArgs], Agg, Arg) :- atom(Type), I1 is I+1, @@ -78,15 +104,68 @@ check_aggregate([Type|Args], I, [Type|NewArgs], Agg, Arg) :- ground_term(_, []). +% +% Rule compiler +% rule(Head, Body) :- - bodytolist(Body, L, []), - compile_goals(L, [], Head). + bodytolist(Body, L0, []), + builtins(L0, L, R), + builtins([Head], RLH, []), + join(RLH, NHead, R, []), + compile_goals(L, [], NHead). + +builtins([]) --> []. +builtins(G.Gs) --> + builtin(G), + builtins(Gs). + +builtin(Res = Op) --> !, + process_constants(Op, Res). +builtin(Goal) --> + process_constants(Goal, NGoal), + [ NGoal ]. + +process_constants(G, G) --> + { var(G) }, !. +process_constants(C, V) --> + { meld_constants:const(C,V) }, !. +process_constants(G, G) --> + { atomic(G) }, !. +process_constants(to_float(Arg1), NArg1) --> !, + process_constants(Arg1, NArg1). +process_constants(A, NA) --> + { arithmetic(A, Op, Arg1, Arg2) }, !, + process_constants(Arg1, NArg1), + process_constants(Arg2, NArg2), + { arithmetic(NExp, Op, NArg1, NArg2) }, + [ NA is NExp ]. +process_constants(A, NA) --> + { arithmetic(A, Op, Arg1) }, !, + process_constants(Arg1, NArg1), + { arithmetic(NExp, Op, NArg1) }, + [ NA is NExp ]. +process_constants(G, NG) --> + { G =.. [A|Args] }, + process_args(Args, NArgs), + { NG =.. [A|NArgs] }. + +process_args([], []) --> []. +process_args(A.Args, NA.NArgs) --> + process_constants(A, NA), + process_args(Args, NArgs). + +join([H0], H0) --> !. +join([H|T], H0) --> + [H], + join(T, H0). compile_goals([], _, _). compile_goals([Goal|Goals], Gs, Head) :- compile_goal(Goal, Goals, Gs, Head), compile_goals(Goals, [Goal|Gs], Head). +compile_goal(BIP, _Goals, _Gs, _Head) :- + meld_builtin(BIP, _, _), !. compile_goal((forall G then Do), Goals, Gs, Head) :- !, % make sure quantified variables are not seen outside quantified_vars(G,Gs+Goals,NG), @@ -100,21 +179,27 @@ compile_goal((forall G then Do), Goals, Gs, Head) :- !, extra_head(Head, BL1, []), % add the delete operation extra_delete(Head, DelBL1, []), + % reorder builtins + reorder_builtins(NG, BLF, BLF2), + reorder_builtins(DelNG, DelBLF, DelBLF2), % create the body as a conjunction - listtobody(BLF, Body), - listtobody(DelBLF, DelBody), + listtobody(BLF2, Body), + listtobody(DelBLF2, DelBody), % done - assert(meld_program:(run(NG) :- Body)), - assert(meld_program:(run(delete(DelNG)) :- DelBody)). + assert_static(meld_program:(run(NG) :- Body)), + assert_static(meld_program:(run(delete(DelNG)) :- DelBody)). compile_goal(Goal, Goals, Gs, Head) :- collect_body(Gs, Goals, BLF, BL1), copy_term(h(Head,BLF,BL1,Goal), h(Head,DelBLF,DelBL1,DelGoal)), extra_head(Head, BL1, []), extra_delete(Head, DelBL1, []), - listtobody(BLF, Body), - listtobody(DelBLF, DelBody), - assert(meld_program:(run(Goal) :- Body)), - assert(meld_program:(run(deleted(DelGoal)) :- DelBody)). + % reorder builtins + reorder_builtins(Goal, BLF, BLF2), + reorder_builtins(DelGoal, DelBLF, DelBLF2), + listtobody(BLF2, Body), + listtobody(DelBLF2, DelBody), + assert_static(meld_program:(run(Goal) :- Body)), + assert_static(meld_program:(run(deleted(DelGoal)) :- DelBody)). % quantified variables should not leave the scope of the forall. quantified_vars(G,Extern,NG) :- @@ -162,6 +247,10 @@ extra_head(Head) --> { type(Head, _, _, aggregation(min, Arg)), freshen(Head, Arg, VHead) }, [ meld_interpreter:min(VHead, Arg, Head)]. +extra_head(Head) --> + { type(Head, _, _, aggregation(sum, Arg)), + freshen(Head, Arg, VHead) }, + [ meld_interpreter:sum(VHead, Arg, Head)]. extra_delete(Head) --> { type(Head, _, _, horn) }, @@ -178,6 +267,10 @@ extra_delete(Head) --> { type(Head, _, _, aggregation(min, Arg)), freshen(Head, Arg, VHead) }, [ meld_interpreter:delete_from_min(VHead, Arg, Head)]. +extra_delete(Head) --> + { type(Head, _, _, aggregation(sum, Arg)), + freshen(Head, Arg, VHead) }, + [ meld_interpreter:delete_from_sum(VHead, Arg, Head)]. freshen(Head, Arg, VHead) :- Head =.. [N|Args], @@ -217,4 +310,64 @@ listtobody([G], G) :- !. listtobody([G|GL], (G,Gs)) :- listtobody(GL, Gs). +reorder_builtins(Head, BLF, BLF2) :- + term_variables(Head, Vs0), + sort(Vs0, Vs), + reorder_term(BLF, Vs, [], BLF2). +% 4 arguments +% list of input goals +% queue of built-ins waiting for execution +% list of current variables +% output variables +% +reorder_term([], _, [], []). +reorder_term(G.Gs, Vs0, Queue, NGs) :- + meld_builtin(G, Is, Os), !, + term_variables(Is, InpVs0), + sort(InpVs0, InpVs), + continue_reorder_term(Gs, G, InpVs, Vs0, Queue, Os, NGs). +reorder_term(G.Gs, Vs0, Queue, G.NGs) :- + term_variables(G, GVs0), + sort(GVs0, GVs), + ord_union(GVs, Vs0, Vs), + wake_queue(Queue, NewQueue, Vs, Vs0, NewQueue, FVs, NGs, NGs0), + reorder_term(Gs, FVs, NewQueue, NGs0). + +continue_reorder_term(Gs, G, InpVs, Vs0, Queue, Os, G.NGs) :- + ord_subset(InpVs, Vs0), !, + term_variables(Os, OutVs0), + sort(OutVs0, OutVs), + ord_union(OutVs, Vs0, Vs), + wake_queue(Queue, NewQueue, Vs, Vs0, NewQueue, FVs, NGs, NGs0), + reorder_term(Gs, FVs, NewQueue, NGs0). +continue_reorder_term(Gs, G, InpVs, Vs0, Queue, Os, NGs) :- + term_variables(Os, OutVs0), + sort(OutVs0, OutVs), + reorder_term(Gs, Vs0, q(InpVs, OutVs, G).Queue, NGs). + +wake_queue([], _, Vs, _, [], Vs) --> []. +wake_queue(Q.Queue, _, Vs, Vs0, Q.Queue, Vs) --> { Vs == Vs0 }, !. +wake_queue(q(InpVs,OutVs,G).Queue, NewQueue, Vs, Vs0, Queue, FVs) --> + { ord_subset(InpVs, Vs) }, !, + [G], + { ord_union(OutVs, Vs, NVs) }, + % restart from beginning + wake_queue(NewQueue, NewNewQueue, NVs, Vs0, NewNewQueue, FVs). +wake_queue(Q.Queue, NewQueue, NVs, Vs0, Q.NQueue, FVs) --> + wake_queue(Queue, NewQueue, NVs, Vs0, NQueue, FVs). + + +meld_builtin(O is I, I, O). +meld_builtin(I1 =< I2, I1-I2, []). +meld_builtin(I1 >= I2, I1-I2, []). +meld_builtin(I1 =:= I2, I1-I2, []). + +arithmetic( A+B, (+), A, B). +arithmetic( A-B, (-), A, B). +arithmetic( A*B, (*), A, B). +arithmetic( A/B, (/), A, B). + +arithmetic( sin(A), sin, A). +arithmetic( cos(A), cos, A). +arithmetic( tan(A), tan, A). diff --git a/packages/meld/meldi.yap b/packages/meld/meldi.yap index 98ca6f2a5..d1ff1799c 100644 --- a/packages/meld/meldi.yap +++ b/packages/meld/meldi.yap @@ -7,6 +7,7 @@ first/2, min/3, max/3, + sum/3, minval/3, maxval/3 ]). @@ -22,7 +23,8 @@ [ nb_queue/1, nb_queue_enqueue/2, - nb_queue_dequeue/2 + nb_queue_dequeue/2, + nb_queue_replace/3 ]). @@ -34,7 +36,7 @@ live :- repeat, ( pop(Goal) -> - format('-~w~n',[Goal]), +% format('<- ~w~n',[Goal]), run(Goal), fail ; @@ -49,6 +51,7 @@ done :- done :- current_predicate(meld_program:P), P \= run/1, + P \= trace/2, % P \= neighbor/2, % P \= root/1, listing(meld_program:P), @@ -57,10 +60,18 @@ done. delete(Fact) :- + once(retract(meld_program:Fact)), nb_getval(meld_queue, Queue), - retract(meld_program:Fact), - nb_queue_enqueue(Queue, deleted(Fact)), - live. + ( +% nb:nb_queue_show(Queue, L ), writeln(show:Fact:L), + nb_queue_replace(Queue, Fact, [] ), +% format('R ~w~n', [Fact]), + deleted(Fact) + -> + true + ; + nb_queue_enqueue(Queue, deleted(Fact)) + ). pop(Goal) :- nb_getval(meld_queue, Queue), @@ -72,10 +83,12 @@ push(Goal) :- increase_reference_count(Ref), fail. push(Goal) :- - format('+~w~n',[Goal]), +% format('-> ~w~n',[Goal]), nb_getval(meld_queue, Queue), !, assert(meld_program:Goal), - nb_queue_enqueue(Queue, Goal). + nb_queue_enqueue(Queue, Goal), +% nb:nb_queue_show(Queue, L ), writeln(show:Goal:L), + fail. % create a queue @@ -114,6 +127,22 @@ min(Skel,_,Goal) :- cache(Goal), push(Goal). +sum(Skel,Arg,Goal) :- + copy_term(Skel, NGoal), + meld_program:Skel, !, + arg(Arg, Skel, A0), + arg(Arg, Goal, A), + AN is A0+A, + AN \= A0, + delete(Skel), + arg(Arg, NGoal, AN), +% format('S ~w~n',[NGoal-Skel]), + push(NGoal). +sum(_Skel,_Arg,Goal) :- +% format('S ~w~n',[Goal]), + push(Goal). + + clean(Skel) :- % format('D~w~n',[Skel]), retractall(meld_program:Skel). @@ -222,6 +251,17 @@ delete_from_max(Goal) :- retract(meld_cache:Goal), push(deleted(Goal)). +delete_from_sum(Skel,Arg,Goal) :- + copy_term(Skel, NGoal), + once(meld_program:Skel), + arg(Arg, Skel, A0), + arg(Arg, Goal, A), + AN is A0-A, + AN \= A0, + delete(Skel), + arg(Arg, NGoal, AN), + push(NGoal). + new_max(VGoal,Arg) :- arg(Arg, VGoal, A), maxval(A, meld_cache:VGoal, VGoal), diff --git a/packages/meld/meldp.yap b/packages/meld/meldp.yap index 1dc4ba72f..5c7e02011 100644 --- a/packages/meld/meldp.yap +++ b/packages/meld/meldp.yap @@ -21,3 +21,4 @@ trace(A,B) :- !, trace. +run([]) :- fail. diff --git a/pl/arith.yap b/pl/arith.yap index 8210d9546..2d692e19f 100644 --- a/pl/arith.yap +++ b/pl/arith.yap @@ -92,7 +92,7 @@ do_not_compile_expressions :- set_value('$c_arith',[]). nonvar(Y), % Don't rewrite variables !, ( - number(Y), + number(Y) -> P = ( X = Y); % This case reduces to an unification '$expand_expr'(Y, P0, X0), '$drop_is'(X0, X, P0, P) diff --git a/pl/boot.yap b/pl/boot.yap index 12423bb03..3b1da2ca1 100755 --- a/pl/boot.yap +++ b/pl/boot.yap @@ -193,14 +193,13 @@ true :- true. '$enter_top_level' :- '$disable_docreep', prompt(_,'| '), - prompt1(' ?- '), '$run_toplevel_hooks', + prompt1('|: '), '$read_vars'(user_input,Command,_,Pos,Varnames, ' ?- '), nb_setval('$spy_gn',1), % stop at spy-points if debugging is on. nb_setval('$debug_run',off), nb_setval('$debug_jump',off), - prompt1('|: '), '$command'(Command,Varnames,Pos,top), '$sync_mmapped_arrays', set_value('$live','$false'). @@ -1096,8 +1095,7 @@ bootstrap(F) :- stream_property(Stream, file_name(File)), '$start_consult'(consult, File, LC), file_directory_name(File, Dir), - getcwd(OldD), - cd(Dir), + working_directory(OldD, Dir), ( get_value('$lf_verbose',silent) -> @@ -1107,7 +1105,7 @@ bootstrap(F) :- format(user_error, '~*|% consulting ~w...~n', [LC,F]) ), '$loop'(Stream,consult), - cd(OldD), + working_directory(_, OldD), '$end_consult', ( get_value('$lf_verbose',silent) @@ -1379,10 +1377,6 @@ b_getval(GlobalVariable, Val) :- '$do_error'(existence_error(variable, GlobalVariable),b_getval(GlobalVariable, Val)) ). -cd(Dir) :- working_directory(_, Dir). - -getcwd(Dir) :- working_directory(Dir, Dir). - diff --git a/pl/consult.yap b/pl/consult.yap index 4e48341bd..514e52ad0 100755 --- a/pl/consult.yap +++ b/pl/consult.yap @@ -243,7 +243,7 @@ use_module(M,F,Is) :- ( OldMode == off -> '$enter_system_mode' ; true ), '$record_loaded'(Stream, ContextModule, Reconsult), '$current_module'(OldModule,ContextModule), - getcwd(OldD), + working_directory(OldD,OldD), nb_getval('$consulting_file',OldF), '$set_consulting_file'(Stream), H0 is heapused, '$cputime'(T0,_), @@ -290,7 +290,7 @@ use_module(M,F,Is) :- '$comp_mode'(CompMode, OldCompMode), nb_setval('$consulting',Old), nb_setval('$consulting_file',OldF), - cd(OldD), + working_directory(_,OldD), % surely, we were in run mode or we would not have included the file! nb_setval('$if_skip_mode',run), % back to include mode! @@ -454,7 +454,7 @@ initialization(G,OPT) :- ( '$access_yap_flags'(15, 0) -> true ; halt). '$skip_unix_comments'(Stream) :- - peek(Stream, 0'#), !, % 35 is ASCII for '# + peek_code(Stream, 0'#), !, % 35 is ASCII for '# skip(Stream, 10), '$skip_unix_comments'(Stream). '$skip_unix_comments'(_). @@ -613,7 +613,7 @@ remove_from_path(New) :- '$check_path'(New,Path), % '$set_consulting_dir'(F) :- file_directory_name(F, Dir), - cd(Dir). + working_directory(_, Dir). '$record_loaded'(Stream, M, Reconsult) :- Stream \= user, diff --git a/pl/tabling.yap b/pl/tabling.yap index 53b15ed78..65e5049cc 100644 --- a/pl/tabling.yap +++ b/pl/tabling.yap @@ -17,8 +17,72 @@ tabling_mode(:,?), abolish_table(:), show_table(:), + show_table(?,:), table_statistics(:), - table_statistics(:,:). + table_statistics(?,:). + + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% show_tabled_predicates/0 %% +%% show_global_trie/0 %% +%% show_all_tables/0 %% +%% show_all_local_tables/0 %% +%% global_trie_statistics/0 %% +%% tabling_statistics/0 %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +show_tabled_predicates :- + current_output(Stream), + show_tabled_predicates(Stream). + +show_global_trie :- + current_output(Stream), + show_global_trie(Stream). + +show_all_tables :- + current_output(Stream), + show_all_tables(Stream). + +show_all_local_tables :- + current_output(Stream), + show_all_local_tables(Stream). + +global_trie_statistics :- + current_output(Stream), + global_trie_statistics(Stream). + +tabling_statistics :- + current_output(Stream), + tabling_statistics(Stream). + + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% tabling_statistics/2 %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%% should match with code in OPTYap/opt.preds.c +tabling_statistics(total_memory,[BytesInUse,BytesAllocated]) :- + '$c_get_optyap_statistics'(0,BytesInUse,BytesAllocated). +tabling_statistics(table_entries,[BytesInUse,StructsInUse]) :- + '$c_get_optyap_statistics'(1,BytesInUse,StructsInUse). +tabling_statistics(subgoal_frames,[BytesInUse,StructsInUse]) :- + '$c_get_optyap_statistics'(2,BytesInUse,StructsInUse). +tabling_statistics(dependency_frames,[BytesInUse,StructsInUse]) :- + '$c_get_optyap_statistics'(3,BytesInUse,StructsInUse). +tabling_statistics(subgoal_trie_nodes,[BytesInUse,StructsInUse]) :- + '$c_get_optyap_statistics'(6,BytesInUse,StructsInUse). +tabling_statistics(answer_trie_nodes,[BytesInUse,StructsInUse]) :- + '$c_get_optyap_statistics'(7,BytesInUse,StructsInUse). +tabling_statistics(subgoal_trie_hashes,[BytesInUse,StructsInUse]) :- + '$c_get_optyap_statistics'(8,BytesInUse,StructsInUse). +tabling_statistics(answer_trie_hashes,[BytesInUse,StructsInUse]) :- + '$c_get_optyap_statistics'(9,BytesInUse,StructsInUse). +tabling_statistics(global_trie_nodes,[BytesInUse,StructsInUse]) :- + '$c_get_optyap_statistics'(10,BytesInUse,StructsInUse). +tabling_statistics(global_trie_hashes,[BytesInUse,StructsInUse]) :- + '$c_get_optyap_statistics'(11,BytesInUse,StructsInUse). @@ -195,98 +259,80 @@ abolish_table(Pred) :- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% show_table/1 %% +%% show_table/2 %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% show_table(Pred) :- - '$current_module'(Mod), - '$do_show_table'(Mod,Pred). + current_output(Stream), + show_table(Stream,Pred). -'$do_show_table'(Mod,Pred) :- +show_table(Stream,Pred) :- + '$current_module'(Mod), + '$do_show_table'(Stream,Mod,Pred). + +'$do_show_table'(_,Mod,Pred) :- var(Pred), !, '$do_error'(instantiation_error,show_table(Mod:Pred)). -'$do_show_table'(_,Mod:Pred) :- !, - '$do_show_table'(Mod,Pred). -'$do_show_table'(_,[]) :- !. -'$do_show_table'(Mod,[HPred|TPred]) :- !, - '$do_show_table'(Mod,HPred), - '$do_show_table'(Mod,TPred). -'$do_show_table'(Mod,(Pred1,Pred2)) :- !, - '$do_show_table'(Mod,Pred1), - '$do_show_table'(Mod,Pred2). -'$do_show_table'(Mod,PredName/PredArity) :- +'$do_show_table'(Stream,_,Mod:Pred) :- !, + '$do_show_table'(Stream,Mod,Pred). +'$do_show_table'(_,_,[]) :- !. +'$do_show_table'(Stream,Mod,[HPred|TPred]) :- !, + '$do_show_table'(Stream,Mod,HPred), + '$do_show_table'(Stream,Mod,TPred). +'$do_show_table'(Stream,Mod,(Pred1,Pred2)) :- !, + '$do_show_table'(Stream,Mod,Pred1), + '$do_show_table'(Stream,Mod,Pred2). +'$do_show_table'(Stream,Mod,PredName/PredArity) :- atom(PredName), integer(PredArity), functor(PredFunctor,PredName,PredArity), '$flags'(PredFunctor,Mod,Flags,Flags), !, ( - Flags /\ 0x000040 =\= 0, !, '$c_show_table'(Mod,PredFunctor) + Flags /\ 0x000040 =\= 0, !, '$c_show_table'(Stream,Mod,PredFunctor) ; '$do_error'(domain_error(table,Mod:PredName/PredArity),show_table(Mod:PredName/PredArity)) ). -'$do_show_table'(Mod,Pred) :- +'$do_show_table'(_,Mod,Pred) :- '$do_error'(type_error(callable,Mod:Pred),show_table(Mod:Pred)). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% table_statistics/1 %% +%% table_statistics/2 %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% table_statistics(Pred) :- - '$current_module'(Mod), - '$do_table_statistics'(Mod,Pred). + current_output(Stream), + table_statistics(Stream,Pred). -'$do_table_statistics'(Mod,Pred) :- +table_statistics(Stream,Pred) :- + '$current_module'(Mod), + '$do_table_statistics'(Stream,Mod,Pred). + +'$do_table_statistics'(_,Mod,Pred) :- var(Pred), !, '$do_error'(instantiation_error,table_statistics(Mod:Pred)). -'$do_table_statistics'(_,Mod:Pred) :- !, - '$do_table_statistics'(Mod,Pred). -'$do_table_statistics'(_,[]) :- !. -'$do_table_statistics'(Mod,[HPred|TPred]) :- !, - '$do_table_statistics'(Mod,HPred), - '$do_table_statistics'(Mod,TPred). -'$do_table_statistics'(Mod,(Pred1,Pred2)) :- !, - '$do_table_statistics'(Mod,Pred1), - '$do_table_statistics'(Mod,Pred2). -'$do_table_statistics'(Mod,PredName/PredArity) :- +'$do_table_statistics'(Stream,_,Mod:Pred) :- !, + '$do_table_statistics'(Stream,Mod,Pred). +'$do_table_statistics'(_,_,[]) :- !. +'$do_table_statistics'(Stream,Mod,[HPred|TPred]) :- !, + '$do_table_statistics'(Stream,Mod,HPred), + '$do_table_statistics'(Stream,Mod,TPred). +'$do_table_statistics'(Stream,Mod,(Pred1,Pred2)) :- !, + '$do_table_statistics'(Stream,Mod,Pred1), + '$do_table_statistics'(Stream,Mod,Pred2). +'$do_table_statistics'(Stream,Mod,PredName/PredArity) :- atom(PredName), integer(PredArity), functor(PredFunctor,PredName,PredArity), '$flags'(PredFunctor,Mod,Flags,Flags), !, ( - Flags /\ 0x000040 =\= 0, !, '$c_table_statistics'(Mod,PredFunctor) + Flags /\ 0x000040 =\= 0, !, '$c_table_statistics'(Stream,Mod,PredFunctor) ; '$do_error'(domain_error(table,Mod:PredName/PredArity),table_statistics(Mod:PredName/PredArity)) ). -'$do_table_statistics'(Mod,Pred) :- +'$do_table_statistics'(_,Mod,Pred) :- '$do_error'(type_error(callable,Mod:Pred),table_statistics(Mod:Pred)). - - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% tabling_statistics/2 %% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -%% should match with code in OPTYap/opt.preds.c -tabling_statistics(total_memory,[BytesInUse,BytesAllocated]) :- - '$c_get_optyap_statistics'(0,BytesInUse,BytesAllocated). -tabling_statistics(table_entries,[BytesInUse,StructsInUse]) :- - '$c_get_optyap_statistics'(1,BytesInUse,StructsInUse). -tabling_statistics(subgoal_frames,[BytesInUse,StructsInUse]) :- - '$c_get_optyap_statistics'(2,BytesInUse,StructsInUse). -tabling_statistics(dependency_frames,[BytesInUse,StructsInUse]) :- - '$c_get_optyap_statistics'(3,BytesInUse,StructsInUse). -tabling_statistics(subgoal_trie_nodes,[BytesInUse,StructsInUse]) :- - '$c_get_optyap_statistics'(6,BytesInUse,StructsInUse). -tabling_statistics(answer_trie_nodes,[BytesInUse,StructsInUse]) :- - '$c_get_optyap_statistics'(7,BytesInUse,StructsInUse). -tabling_statistics(subgoal_trie_hashes,[BytesInUse,StructsInUse]) :- - '$c_get_optyap_statistics'(8,BytesInUse,StructsInUse). -tabling_statistics(answer_trie_hashes,[BytesInUse,StructsInUse]) :- - '$c_get_optyap_statistics'(9,BytesInUse,StructsInUse). -tabling_statistics(global_trie_nodes,[BytesInUse,StructsInUse]) :- - '$c_get_optyap_statistics'(10,BytesInUse,StructsInUse). -tabling_statistics(global_trie_hashes,[BytesInUse,StructsInUse]) :- - '$c_get_optyap_statistics'(11,BytesInUse,StructsInUse). - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \ No newline at end of file diff --git a/pl/utils.yap b/pl/utils.yap index 5ea3410f2..01ed7fb0a 100644 --- a/pl/utils.yap +++ b/pl/utils.yap @@ -218,6 +218,10 @@ current_op(X,Y,Z) :- cd :- cd('~'). +cd(F) :- absolute_file_name(F, Dir, [file_type(directory)]), working_directory(_, Dir). + +getcwd(Dir) :- working_directory(Dir, Dir). + ls :- getcwd(X), '$load_system_ls'(X,L), diff --git a/pl/yapor.yap b/pl/yapor.yap index 75f53b58a..eeae929cc 100644 --- a/pl/yapor.yap +++ b/pl/yapor.yap @@ -12,12 +12,25 @@ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% :- meta_predicate - or_statistics(:,:), - opt_statistics(:,:), default_sequential(:). +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% or_statistics/0 %% +%% opt_statistics/0 %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +or_statistics :- + current_output(Stream), + or_statistics(Stream). + +opt_statistics :- + current_output(Stream), + opt_statistics(Stream). + + + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% or_statistics/2 %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/pl/yio.yap b/pl/yio.yap index 62e9b77ff..f4500ac41 100644 --- a/pl/yio.yap +++ b/pl/yio.yap @@ -116,13 +116,13 @@ read_term(T, Options) :- '$check_io_opts'(Options,read_term(T, Options)), current_input(S), '$preprocess_read_terms_options'(Options,Module), - '$read_vars'(S,T,Module,Pos,VL), + '$read_vars'(S,T,Module,Pos,VL,'|: '), '$postprocess_read_terms_options'(Options, T, VL, Pos). read_term(Stream, T, Options) :- '$check_io_opts'(Options,read_term(T, Options)), '$preprocess_read_terms_options'(Options,Module), - '$read_vars'(Stream,T,Module,Pos,VL), + '$read_vars'(Stream,T,Module,Pos,VL,'|: '), '$postprocess_read_terms_options'(Options, T, VL, Pos). %