[m-rev.] diff: misc module cleanups

Zoltan Somogyi zs at cs.mu.OZ.AU
Mon Aug 29 17:07:28 AEST 2005


This diff cleans up a bunch of modules. It has no algorithmic changes
other than in the formatting of error messages.

compiler/error_util.m:
	Delete the obsolete predicate append_punctuation, since the suffix
	format component can now do more, and do it more easily.

compiler/goal_util.m:
compiler/hlds_goal.m:
compiler/hlds_llds.m:
compiler/instmap.m:
compiler/const_prop.m:
	Change the argument order of some the predicates exported by these
	modules to make them easier to use with state variable syntax.

compiler/*.m:
	Convert a bunch of these modules to four space indentation, and fix
	departures from our coding style.

	Conform to the changed argument order above.

	Use suffixes instead of append_punctuation.

tests/invalid/circ_*.err_exp:
tests/warnings/unused_args_*.exp:
	Expect the updated error messages, which format sym_names consistently
	the same way as other messages.

Zoltan.

cvs diff: Diffing .
cvs diff: Diffing analysis
cvs diff: Diffing bindist
cvs diff: Diffing boehm_gc
cvs diff: Diffing boehm_gc/Mac_files
cvs diff: Diffing boehm_gc/cord
cvs diff: Diffing boehm_gc/cord/private
cvs diff: Diffing boehm_gc/doc
cvs diff: Diffing boehm_gc/include
cvs diff: Diffing boehm_gc/include/private
cvs diff: Diffing boehm_gc/tests
cvs diff: Diffing browser
cvs diff: Diffing bytecode
cvs diff: Diffing compiler
Index: compiler/accumulator.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/accumulator.m,v
retrieving revision 1.39
diff -u -b -r1.39 accumulator.m
--- compiler/accumulator.m	8 Aug 2005 02:57:08 -0000	1.39
+++ compiler/accumulator.m	28 Aug 2005 01:20:15 -0000
@@ -1218,7 +1218,7 @@
         % Swap the arguments.
         [A, B] = set__to_sorted_list(Vars),
         map__from_assoc_list([A-B, B-A], Subst),
-        goal_util__rename_vars_in_goal(Goal, Subst, SwappedGoal),
+        goal_util__rename_vars_in_goal(Subst, Goal, SwappedGoal),
         CSGoal = SwappedGoal - InstMap
     ),
 
@@ -1557,7 +1557,7 @@
     U = create_new_orig_recursive_goals(UpdateBase, Update,
         HeadToCallSubst, UpdateSubst, C),
 
-    goal_util__rename_vars_in_goal(Call, CallToHeadSubst, BaseCall),
+    goal_util__rename_vars_in_goal(CallToHeadSubst, Call, BaseCall),
     Cbefore = goal_list(set__to_sorted_list(Before), C),
     Uupdate = goal_list(set__to_sorted_list(UpdateBase) `append`
         set__to_sorted_list(Update), U),
@@ -1580,7 +1580,7 @@
     BaseIds = base(_UpdateBase, AssocBase, OtherBase),
     Sets = sets(Before, Assoc, ConstructAssoc, Construct, Update, _Reject),
 
-    goal_util__rename_vars_in_goal(Call, RecCallSubst, RecCall),
+    goal_util__rename_vars_in_goal(RecCallSubst, Call, RecCall),
 
     Cbefore = goal_list(set__to_sorted_list(Before), C),
 
@@ -1790,7 +1790,7 @@
     list__foldl(
         (pred(Id::in, GS0::in, GS::out) is det :-
             goal_store__lookup(From, Id, Goal0 - InstMap),
-            goal_util__rename_vars_in_goal(Goal0, Subst, Goal),
+            goal_util__rename_vars_in_goal(Subst, Goal0, Goal),
             goal_store__det_insert(GS0, Id, Goal - InstMap, GS)
         ), Ids, Initial, Final).
 
Index: compiler/add_class.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/add_class.m,v
retrieving revision 1.1
diff -u -b -r1.1 add_class.m
--- compiler/add_class.m	26 Jul 2005 01:56:20 -0000	1.1
+++ compiler/add_class.m	27 Aug 2005 14:20:11 -0000
@@ -454,13 +454,13 @@
         % Add the body of the introduced pred.
         % First the goal info, ...
         goal_info_init(GoalInfo0),
-        goal_info_set_context(GoalInfo0, Context, GoalInfo1),
+        goal_info_set_context(Context, GoalInfo0, GoalInfo1),
         set__list_to_set(HeadVars, NonLocals),
-        goal_info_set_nonlocals(GoalInfo1, NonLocals, GoalInfo2),
+        goal_info_set_nonlocals(NonLocals, GoalInfo1, GoalInfo2),
         ( check_marker(Markers, (impure)) ->
-            goal_info_add_feature(GoalInfo2, (impure), GoalInfo)
+            goal_info_add_feature((impure), GoalInfo2, GoalInfo)
         ; check_marker(Markers, (semipure)) ->
-            goal_info_add_feature(GoalInfo2, (semipure), GoalInfo)
+            goal_info_add_feature((semipure), GoalInfo2, GoalInfo)
         ;
             GoalInfo = GoalInfo2
         ),
Index: compiler/add_clause.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/add_clause.m,v
retrieving revision 1.4
diff -u -b -r1.4 add_clause.m
--- compiler/add_clause.m	12 Aug 2005 02:33:09 -0000	1.4
+++ compiler/add_clause.m	27 Aug 2005 14:20:25 -0000
@@ -522,7 +522,7 @@
         !ModuleInfo, !QualInfo, !SInfo, !IO) :-
     transform_goal_2(Goal0, Context, Subst, Goal - GoalInfo1,
         !VarSet, !ModuleInfo, !QualInfo, !SInfo, !IO),
-    goal_info_set_context(GoalInfo1, Context, GoalInfo).
+    goal_info_set_context(Context, GoalInfo1, GoalInfo).
 
 :- pred transform_goal_2(goal_expr::in, prog_context::in,
     prog_substitution::in, hlds_goal::out,
@@ -737,7 +737,7 @@
             CallId = call(predicate - Name/Arity)
         ),
         goal_info_init(Context, GoalInfo0),
-        add_goal_info_purity_feature(GoalInfo0, Purity, GoalInfo),
+        add_goal_info_purity_feature(Purity, GoalInfo0, GoalInfo),
         Goal0 = Call - GoalInfo,
 
         record_called_pred_or_func(predicate, Name, Arity, !QualInfo),
Index: compiler/add_mode.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/add_mode.m,v
retrieving revision 1.1
diff -u -b -r1.1 add_mode.m
--- compiler/add_mode.m	26 Jul 2005 01:56:20 -0000	1.1
+++ compiler/add_mode.m	28 Aug 2005 15:20:06 -0000
@@ -202,14 +202,12 @@
         % where <kind> is either "inst" or "mode".
         %
         Kinds = (if Expansions = [_] then Kind else Kind ++ "s"),
-        Pieces0 = list__map(
+        ExpansionPieces = list__map(
             (func(SymName - Arity) =
-                error_util__describe_sym_name_and_arity(
-                    SymName / Arity)),
+                sym_name_and_arity(SymName / Arity)),
             Expansions),
-        Pieces1 = error_util__list_to_pieces(Pieces0),
-        Pieces = append_punctuation([words("Error: circular equivalence"),
-            fixed(Kinds) | Pieces1], '.'),
+        Pieces = [words("Error: circular equivalence"), fixed(Kinds)]
+            ++ component_list_to_pieces(ExpansionPieces) ++ [suffix(".")],
         error_util__write_error_pieces(Context, 0, Pieces, !IO),
         io__set_exit_status(1, !IO)
     ;
Index: compiler/add_pragma.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/add_pragma.m,v
retrieving revision 1.3
diff -u -b -r1.3 add_pragma.m
--- compiler/add_pragma.m	14 Aug 2005 03:20:37 -0000	1.3
+++ compiler/add_pragma.m	28 Aug 2005 00:17:15 -0000
@@ -608,8 +608,8 @@
             map__init(VarTypes0),
             goal_info_init(GoalInfo0),
             set__list_to_set(Args, NonLocals),
-            goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo1),
-            goal_info_set_context(GoalInfo1, Context, GoalInfo),
+            goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo1),
+            goal_info_set_context(Context, GoalInfo1, GoalInfo),
 
             %
             % We don't record the called predicate as used -- it
@@ -1905,11 +1905,11 @@
         write_error_pieces(Context, 0, Pieces1 ++ Pieces2, !IO)
     ;
         MultipleArgs = [],
-            % build the pragma_c_code
+        % Build the foreign_proc.
         goal_info_init(GoalInfo0),
-        goal_info_set_context(GoalInfo0, Context, GoalInfo1),
+        goal_info_set_context(Context, GoalInfo0, GoalInfo1),
         % Put the purity in the goal_info in case this foreign code is inlined.
-        add_goal_info_purity_feature(GoalInfo1, Purity, GoalInfo),
+        add_goal_info_purity_feature(Purity, GoalInfo1, GoalInfo),
         make_foreign_args(HeadVars, ArgInfo, OrigArgTypes, ForeignArgs),
         HldsGoal0 = foreign_proc(Attributes, PredId, ProcId, ForeignArgs, [],
             PragmaImpl) - GoalInfo,
Index: compiler/add_pred.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/add_pred.m,v
retrieving revision 1.1
diff -u -b -r1.1 add_pred.m
--- compiler/add_pred.m	26 Jul 2005 01:56:21 -0000	1.1
+++ compiler/add_pred.m	28 Aug 2005 00:17:27 -0000
@@ -244,7 +244,7 @@
         %
     goal_info_init(Context, GoalInfo0),
     set__list_to_set(HeadVars, NonLocals),
-    goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+    goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
     Goal = Call - GoalInfo,
     Clause = clause([], Goal, mercury, Context),
 
Index: compiler/add_type.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/add_type.m,v
retrieving revision 1.1
diff -u -b -r1.1 add_type.m
--- compiler/add_type.m	26 Jul 2005 01:56:21 -0000	1.1
+++ compiler/add_type.m	28 Aug 2005 06:20:16 -0000
@@ -68,6 +68,7 @@
 :- import_module require.
 :- import_module std_util.
 :- import_module string.
+:- import_module svmap.
 :- import_module term.
 
 module_add_type_defn(TVarSet, Name, Args, TypeDefn, _Cond, Context,
@@ -668,7 +669,7 @@
     ;
         QualifiedConsDefns = [ConsDefn | QualifiedConsDefns1]
     ),
-    map__set(!.Ctors, QualifiedConsId, QualifiedConsDefns, !:Ctors),
+    svmap__set(QualifiedConsId, QualifiedConsDefns, !Ctors),
 
     ( QualifiedConsId = cons(qualified(Module, ConsName), Arity) ->
         % Add unqualified version of the cons_id to the
Index: compiler/clause_to_proc.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/clause_to_proc.m,v
retrieving revision 1.53
diff -u -b -r1.53 clause_to_proc.m
--- compiler/clause_to_proc.m	16 Aug 2005 15:36:14 -0000	1.53
+++ compiler/clause_to_proc.m	27 Aug 2005 13:31:08 -0000
@@ -224,13 +224,13 @@
         ;
             proc_info_context(!.Proc, Context)
         ),
-        goal_info_set_context(GoalInfo0, Context, GoalInfo1),
+        goal_info_set_context(Context, GoalInfo0, GoalInfo1),
 
         %
         % The non-local vars are just the head variables.
         %
         set__list_to_set(HeadVars, NonLocalVars),
-        goal_info_set_nonlocals(GoalInfo1, NonLocalVars, GoalInfo2),
+        goal_info_set_nonlocals(NonLocalVars, GoalInfo1, GoalInfo2),
 
         %
         % The disjunction is impure/semipure if any of the disjuncts
@@ -239,7 +239,7 @@
         ( contains_nonpure_goal(GoalList) ->
             list__map(get_purity, GoalList, PurityList),
             Purity = list__foldl(worst_purity, PurityList, (pure)),
-            add_goal_info_purity_feature(GoalInfo2, Purity, GoalInfo)
+            add_goal_info_purity_feature(Purity, GoalInfo2, GoalInfo)
         ;
             GoalInfo2 = GoalInfo
         ),
@@ -397,7 +397,7 @@
     Goals = Goals0 ++ ExistsCastHeadGoals ++ ExistsCastExtraGoals,
     HeadVars = ExtraHeadVars ++ OrigHeadVars,
     set__list_to_set(HeadVars, NonLocals),
-    goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+    goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
     Body = conj(Goals) - GoalInfo,
     proc_info_set_body(VarSet, VarTypes, HeadVars, Body, RttiVarMaps,
         !ProcInfo).
Index: compiler/complexity.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/complexity.m,v
retrieving revision 1.3
diff -u -b -r1.3 complexity.m
--- compiler/complexity.m	3 Jun 2005 07:04:16 -0000	1.3
+++ compiler/complexity.m	27 Aug 2005 14:36:14 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 2004-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -26,25 +28,24 @@
 	% Try to read in a complexity proc map from FileName. If successful,
 	% return the proc map and the number of entries in it. If not, return
 	% an error message.
-
+    %
 :- pred read_spec_file(string::in,
-	maybe_error(pair(int, complexity_proc_map))::out,
-	io::di, io::uo) is det.
+    maybe_error(pair(int, complexity_proc_map))::out, io::di, io::uo) is det.
 
 	% is_in_complexity_proc_map(ProcMap, ModuleInfo, PredId, ProcId):
 	% If PredId/ProcId in ModuleInfo is in ProcMap, return its slot number
 	% in the complexity table.
-
+    %
 :- func is_in_complexity_proc_map(complexity_proc_map, module_info,
 	pred_id, proc_id) = maybe(int).
 
 	% Return the name of the given procedure in the format required by the
 	% complexity map file.
-
+    %
 :- func complexity_proc_name(module_info, pred_id, proc_id) = string.
 
 	% Transform the given procedure if it is in the complexity map.
-
+    %
 :- pred process_proc_msg(int::in, complexity_proc_map::in,
 	pred_id::in, proc_id::in, proc_info::in, proc_info::out,
 	module_info::in, module_info::out, io::di, io::uo) is det.
@@ -262,11 +263,10 @@
 	set__list_to_set(HeadVars, OrigNonLocals),
 	OrigGoal = _ - OrigGoalInfo,
 	goal_info_get_instmap_delta(OrigGoalInfo, OrigInstMapDelta),
-	add_goal_info_purity_feature(OrigGoalInfo, impure, ImpureOrigGoalInfo),
+    add_goal_info_purity_feature(impure, OrigGoalInfo, ImpureOrigGoalInfo),
 
 	IsActiveVarName = "IsActive",
-	generate_new_var(IsActiveVarName, is_active_type,
-		!ProcInfo, IsActiveVar),
+    generate_new_var(IsActiveVarName, is_active_type, !ProcInfo, IsActiveVar),
 
 	classify_args(HeadVars, ArgModes, !.ModuleInfo, VarSet, VarTypes,
 		VarInfos),
@@ -321,17 +321,14 @@
 		TransformedGoal = TransformedGoalExpr - ImpureOrigGoalInfo
 	;
 		CodeModel = model_semi,
-		OrigAfterGoal =
-			conj([OrigGoal, ExitGoal]) - ImpureOrigGoalInfo,
-		DisjGoal =
-			disj([OrigAfterGoal, FailGoal]) - ImpureOrigGoalInfo,
-		TransformedGoal =
-			conj(SlotGoals ++ [DisjGoal]) - ImpureOrigGoalInfo
+        OrigAfterGoal = conj([OrigGoal, ExitGoal]) - ImpureOrigGoalInfo,
+        DisjGoal = disj([OrigAfterGoal, FailGoal]) - ImpureOrigGoalInfo,
+        TransformedGoal = conj(SlotGoals ++ [DisjGoal]) - ImpureOrigGoalInfo
 	;
 		CodeModel = model_non,
 		RedoGoal0 = RedoGoalExpr - RedoGoalInfo0,
-		goal_info_add_feature(RedoGoalInfo0,
-			preserve_backtrack_into, RedoGoalInfo),
+        goal_info_add_feature(preserve_backtrack_into,
+            RedoGoalInfo0, RedoGoalInfo),
 		RedoGoal = RedoGoalExpr - RedoGoalInfo,
 
 		instmap_delta_init_reachable(AfterInstMapDelta),
@@ -339,20 +336,15 @@
 			multidet, impure, Context, AfterGoalInfo),
 		AfterGoal = disj([ExitGoal, RedoGoal]) - AfterGoalInfo,
 
-		OrigAfterGoal =
-			conj([OrigGoal, AfterGoal]) - ImpureOrigGoalInfo,
-		DisjGoal =
-			disj([OrigAfterGoal, FailGoal]) - ImpureOrigGoalInfo,
-		TransformedGoal =
-			conj(SlotGoals ++ [DisjGoal]) - ImpureOrigGoalInfo
+        OrigAfterGoal = conj([OrigGoal, AfterGoal]) - ImpureOrigGoalInfo,
+        DisjGoal = disj([OrigAfterGoal, FailGoal]) - ImpureOrigGoalInfo,
+        TransformedGoal = conj(SlotGoals ++ [DisjGoal]) - ImpureOrigGoalInfo
 	),
 
 	mercury_term_size_prof_builtin_module(TSPB),
 	SwitchArms = [
-		case(cons(qualified(TSPB, "is_inactive"), 0),
-			TransformedGoal),
-		case(cons(qualified(TSPB, "is_active"), 0),
-			OrigGoal)
+        case(cons(qualified(TSPB, "is_inactive"), 0), TransformedGoal),
+        case(cons(qualified(TSPB, "is_active"), 0), OrigGoal)
 	],
 
 	SwitchExpr = switch(IsActiveVar, cannot_fail, SwitchArms),
@@ -387,7 +379,7 @@
 	%
 	% prefixed by the goals required to generate the typeinfos we need
 	% to compute the sizes.
-
+    %
 :- pred generate_slot_goals(int::in, assoc_list(prog_var, int)::in,
 	int::in, term__context::in, pred_id::in,
 	proc_info::in, proc_info::out, module_info::in, module_info::out,
@@ -481,8 +473,7 @@
 	hlds_goal::out) is det.
 
 complexity_generate_foreign_proc(PredName, Detism, Args, ExtraArgs,
-		PrefixCode, Code, SuffixCode, BoundVars, ModuleInfo, Context,
-		Goal) :-
+        PrefixCode, Code, SuffixCode, BoundVars, ModuleInfo, Context, Goal) :-
 	mercury_term_size_prof_builtin_module(BuiltinModule),
 	Attrs0 = default_attributes(c),
 	set_may_call_mercury(will_not_call_mercury, Attrs0, Attrs),
@@ -499,9 +490,9 @@
 
 classify_args([], [], _, _, _, []).
 classify_args([_ | _], [], _, _, _, _) :-
-	error("classify_args: lists not same length").
+    unexpected(this_file, "classify_args: lists not same length").
 classify_args([], [_ | _], _, _, _, _) :-
-	error("classify_args: lists not same length").
+    unexpected(this_file, "classify_args: lists not same length").
 classify_args([Var | Vars], [Mode | Modes], ModuleInfo, VarSet, VarTypes,
 		[Var - complexity_arg_info(MaybeName, Kind) | VarInfos]) :-
 	classify_args(Vars, Modes, ModuleInfo, VarSet, VarTypes, VarInfos),
@@ -533,11 +524,9 @@
 	( Kind = complexity_input_variable_size ->
 		allocate_slot_numbers_cl(VarInfos, Offset + 1,
 			NumberedProfiledVarsTail),
-		NumberedProfiledVars =
-			[Var - Offset | NumberedProfiledVarsTail]
+        NumberedProfiledVars = [Var - Offset | NumberedProfiledVarsTail]
 	;
-		allocate_slot_numbers_cl(VarInfos, Offset,
-			NumberedProfiledVars)
+        allocate_slot_numbers_cl(VarInfos, Offset, NumberedProfiledVars)
 	).
 
 :- func ground_vars(list(prog_var)) = assoc_list(prog_var, inst).
@@ -573,3 +562,11 @@
 		!ProcInfo, !:ModuleInfo),
 	require(unify(PredInfo0, PredInfo),
 		"complexity__make_type_info_var: modified pred_info").
+
+%-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "complexity.m".
+
+%-----------------------------------------------------------------------------%
Index: compiler/const_prop.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/const_prop.m,v
retrieving revision 1.28
diff -u -b -r1.28 const_prop.m
--- compiler/const_prop.m	1 Apr 2005 08:22:21 -0000	1.28
+++ compiler/const_prop.m	28 Aug 2005 01:20:34 -0000
@@ -1,4 +1,6 @@
 %---------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%---------------------------------------------------------------------------%
 % Copyright (C) 1997-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -30,18 +32,17 @@
 
 :- import_module list.
 
-	% evaluate_call(PredId, ProcId, Args, GoalInfo0,
-	%	GoalExpr, GoalInfo, VarTypes, Instmap, !ModuleInfo):
+    % evaluate_call(PredId, ProcId, Args, VarTypes, Instmap, ModuleInfo,
+    %   GoalExpr, GoalInfo):
+    %
+    % This attempts to evaluate a call to the specified procedure with the
+    % specified arguments. If the call can be statically evaluated,
+    % evaluate_builtin will succeed, returning the new goal in GoalExpr
+    % (and updating GoalInfo). Otherwise it fails.
 	%
-	% This attempts to evaluate a call to the specified procedure
-	% with the specified arguments.  If the call can be statically
-	% evaluated, evaluate_builtin will succeed, returning the new
-	% goal in GoalExpr (and the new GoalInfo).
-	% Otherwise it fails.
-
 :- pred evaluate_call(pred_id::in, proc_id::in, list(prog_var)::in,
-	hlds_goal_info::in, vartypes::in, instmap::in, module_info::in,
-	hlds_goal_expr::out, hlds_goal_info::out) is semidet.
+    vartypes::in, instmap::in, module_info::in, hlds_goal_expr::out,
+    hlds_goal_info::in, hlds_goal_info::out) is semidet.
 
 %------------------------------------------------------------------------------%
 
@@ -77,15 +78,15 @@
 
 	% This type groups the information from the HLDS
 	% about a procedure call argument.
-:- type arg_hlds_info --->
-	arg_hlds_info(
+:- type arg_hlds_info
+    --->    arg_hlds_info(
 		arg_var		:: prog_var,
 		arg_type	:: prog_data__type,
 		arg_inst	:: (inst)
 	).
 
-evaluate_call(PredId, ProcId, Args, GoalInfo0, VarTypes, InstMap, ModuleInfo,
-		Goal, GoalInfo) :-
+evaluate_call(PredId, ProcId, Args, VarTypes, InstMap, ModuleInfo, Goal,
+        GoalInfo0, GoalInfo) :-
 	predicate_module(ModuleInfo, PredId, ModuleName),
 	predicate_name(ModuleInfo, PredId, PredName),
 	proc_id_to_int(ProcId, ProcInt),
@@ -95,35 +96,30 @@
 	),
 	ArgHldsInfos = list__map(LookupArgs, Args),
 	evaluate_call_2(ModuleName, PredName, ProcInt, ArgHldsInfos,
-		GoalInfo0, Goal, GoalInfo).
+       Goal, GoalInfo0, GoalInfo).
 
 :- pred evaluate_call_2(module_name::in, string::in, int::in,
-	list(arg_hlds_info)::in, hlds_goal_info::in,
-	hlds_goal_expr::out, hlds_goal_info::out) is semidet.
+    list(arg_hlds_info)::in, hlds_goal_expr::out,
+    hlds_goal_info::in, hlds_goal_info::out) is semidet.
 
-	% Module_info is not actually used at the moment.
-
-evaluate_call_2(Module, Pred, ModeNum, Args, GoalInfo0, Goal, GoalInfo) :-
+evaluate_call_2(Module, Pred, ModeNum, Args, Goal, !GoalInfo) :-
 	% -- not yet:
 	% Module = qualified(unqualified("std"), Mod),
 	Module = unqualified(Mod),
 	( evaluate_det_call(Mod, Pred, ModeNum, Args, OutputArg, Cons) ->
-		make_construction_goal(OutputArg, Cons, GoalInfo0,
-			Goal, GoalInfo)
+        make_construction_goal(OutputArg, Cons, Goal, !GoalInfo)
 	; evaluate_test(Mod, Pred, ModeNum, Args, Succeeded) ->
-		make_true_or_fail(Succeeded, GoalInfo0, Goal, GoalInfo)
+        make_true_or_fail(Succeeded, Goal)
 	; evaluate_semidet_call(Mod, Pred, ModeNum, Args, Result) ->
 		(
 			Result = yes(OutputArg - const(Cons)),
-			make_construction_goal(OutputArg, Cons, GoalInfo0,
-				Goal, GoalInfo)
+            make_construction_goal(OutputArg, Cons, Goal, !GoalInfo)
 		;
 			Result = yes(OutputArg - var(InputArg)),
-			make_assignment_goal(OutputArg, InputArg, GoalInfo0,
-				Goal, GoalInfo)
+            make_assignment_goal(OutputArg, InputArg, Goal, !GoalInfo)
 		;
 			Result = no,
-			make_true_or_fail(no, GoalInfo0, Goal, GoalInfo)
+            make_true_or_fail(no, Goal)
 		)
 	;
 		fail
@@ -142,7 +138,7 @@
 	% OutputArg being whichever of Args is output,
 	% and with OutputArgVal being the computed value of OutputArg.
 	% Otherwise it fails.
-
+    %
 :- pred evaluate_det_call(string::in, string::in, int::in,
 	list(arg_hlds_info)::in, arg_hlds_info::out, cons_id::out) is semidet.
 
@@ -534,27 +530,26 @@
 %------------------------------------------------------------------------------%
 
 :- pred make_assignment_goal(arg_hlds_info::in, arg_hlds_info::in,
-	hlds_goal_info::in, hlds_goal_expr::out, hlds_goal_info::out) is det.
+    hlds_goal_expr::out, hlds_goal_info::in, hlds_goal_info::out) is det.
 
-make_assignment_goal(OutputArg, InputArg, GoalInfo0, Goal, GoalInfo) :-
+make_assignment_goal(OutputArg, InputArg, Goal, !GoalInfo) :-
 	make_assignment(OutputArg, InputArg, Goal),
-	goal_info_get_instmap_delta(GoalInfo0, Delta0),
-	instmap_delta_set(Delta0, OutputArg ^ arg_var, InputArg ^ arg_inst,
-		Delta),
-	goal_info_set_instmap_delta(GoalInfo0, Delta, GoalInfo1),
-	goal_info_set_determinism(GoalInfo1, det, GoalInfo).
-
+    goal_info_get_instmap_delta(!.GoalInfo, Delta0),
+    instmap_delta_set(OutputArg ^ arg_var, InputArg ^ arg_inst,
+        Delta0, Delta),
+    goal_info_set_instmap_delta(Delta, !GoalInfo),
+    goal_info_set_determinism(det, !GoalInfo).
 
 :- pred make_construction_goal(arg_hlds_info::in, cons_id::in,
-	hlds_goal_info::in, hlds_goal_expr::out, hlds_goal_info::out) is det.
+    hlds_goal_expr::out, hlds_goal_info::in, hlds_goal_info::out) is det.
 
-make_construction_goal(OutputArg, Cons, GoalInfo0, Goal, GoalInfo) :-
+make_construction_goal(OutputArg, Cons, Goal, !GoalInfo) :-
 	make_construction(OutputArg, Cons, Goal),
-	goal_info_get_instmap_delta(GoalInfo0, Delta0),
-	instmap_delta_set(Delta0, OutputArg ^ arg_var,
-		bound(unique, [functor(Cons, [])]), Delta),
-	goal_info_set_instmap_delta(GoalInfo0, Delta, GoalInfo1),
-	goal_info_set_determinism(GoalInfo1, det, GoalInfo).
+    goal_info_get_instmap_delta(!.GoalInfo, Delta0),
+    instmap_delta_set(OutputArg ^ arg_var, bound(unique, [functor(Cons, [])]),
+        Delta0, Delta),
+    goal_info_set_instmap_delta(Delta, !GoalInfo),
+    goal_info_set_determinism(det, !GoalInfo).
 
 :- pred make_assignment(arg_hlds_info::in, arg_hlds_info::in,
 	hlds_goal_expr::out) is det.
@@ -567,8 +562,7 @@
 	InputArgMode = (Inst -> Inst),
 	UniMode = OutputArgMode - InputArgMode,
 	Context = unify_context(explicit, []),
-	Goal = unify(OutVar, var(InVar), UniMode, assign(OutVar, InVar),
-		Context).
+    Goal = unify(OutVar, var(InVar), UniMode, assign(OutVar, InVar), Context).
 
 	% recompute_instmap_delta is run by simplify.m if anything changes,
 	% so the insts are not important here.
@@ -580,10 +574,9 @@
 
 %------------------------------------------------------------------------------%
 
-:- pred make_true_or_fail(bool::in, hlds_goal_info::in,
-	hlds_goal_expr::out, hlds_goal_info::out) is det.
+:- pred make_true_or_fail(bool::in, hlds_goal_expr::out) is det.
 
-make_true_or_fail(yes, GoalInfo, conj([]), GoalInfo).
-make_true_or_fail(no, GoalInfo, disj([]), GoalInfo).
+make_true_or_fail(yes, conj([])).
+make_true_or_fail(no, disj([])).
 
 %------------------------------------------------------------------------------%
Index: compiler/constraint.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/constraint.m,v
retrieving revision 1.61
diff -u -b -r1.61 constraint.m
--- compiler/constraint.m	24 May 2005 04:47:49 -0000	1.61
+++ compiler/constraint.m	28 Aug 2005 01:21:28 -0000
@@ -104,8 +104,8 @@
     goal_list_determinism(Goals, ConjDetism),
     goal_list_purity(Goals, Purity),
     goal_info_init(NonLocals, Delta, ConjDetism, pure, Context, GoalInfo1),
-    goal_info_set_features(GoalInfo1, Features0, GoalInfo2),
-    add_goal_info_purity_feature(GoalInfo2, Purity, GoalInfo),
+    goal_info_set_features(Features0, GoalInfo1, GoalInfo2),
+    add_goal_info_purity_feature(Purity, GoalInfo2, GoalInfo),
     conj_list_to_goal(Goals, GoalInfo, Goal).
 
 :- pred propagate_conj_sub_goal(hlds_goal::in,
@@ -536,7 +536,7 @@
 :- func add_constraint_feature(hlds_goal) = hlds_goal.
 
 add_constraint_feature(Goal - GoalInfo0) = Goal - GoalInfo :-
-    goal_info_add_feature(GoalInfo0, constraint, GoalInfo).
+    goal_info_add_feature(constraint, GoalInfo0, GoalInfo).
 
 %-----------------------------------------------------------------------------%
 
@@ -564,10 +564,9 @@
         !:Info = !.Info ^ varset := VarSet,
         !:Info = !.Info ^ vartypes := VarTypes,
         map__from_assoc_list([ConstructVar - NewVar], Subn),
-        goal_util__rename_vars_in_goal(Construct0, Subn, Construct),
+        rename_vars_in_goal(Subn, Construct0, Construct),
         Constructs = [Construct | Constructs0],
-        goal_util__rename_vars_in_goal(ConstraintGoal0, Subn,
-            ConstraintGoal),
+        rename_vars_in_goal(Subn, ConstraintGoal0, ConstraintGoal),
         Constraint = constraint(ConstraintGoal, ChangedVars,
             IncompatibleInstVars, Constructs)
     ;
@@ -812,7 +811,7 @@
 strip_constraint_markers(Goal - GoalInfo0) =
         strip_constraint_markers_expr(Goal) - GoalInfo :-
     ( goal_info_has_feature(GoalInfo0, constraint) ->
-        goal_info_remove_feature(GoalInfo0, constraint, GoalInfo)
+        goal_info_remove_feature(constraint, GoalInfo0, GoalInfo)
     ;
         GoalInfo = GoalInfo0
     ).
Index: compiler/context.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/context.m,v
retrieving revision 1.11
diff -u -b -r1.11 context.m
--- compiler/context.m	24 Mar 2005 02:00:20 -0000	1.11
+++ compiler/context.m	27 Aug 2005 16:50:39 -0000
@@ -346,7 +346,7 @@
 	context__create_magic_call(MagicCall, yes, Subn, _),
 	{ context__rename_vars_in_call_list(CallList0,
 		Subn, CallList) },
-	{ goal_util__rename_vars_in_goals(AfterGoals0, no, Subn, AfterGoals) },
+	{ goal_util__rename_vars_in_goals(no, Subn, AfterGoals0, AfterGoals) },
 	magic_info_get_magic_vars(Vars),
 	{ list__condense([Vars, Inputs, Outputs], NonLocals0) },
 	{ set__list_to_set(NonLocals0, NonLocals) },
@@ -526,8 +526,7 @@
 		magic_info_set_proc_info(ProcInfo),
 		{ goal_info_get_nonlocals(GoalInfo1, GoalNonLocals1) },
 		magic_util__restrict_nonlocals(GoalNonLocals1, GoalNonLocals),
-		{ goal_info_set_nonlocals(GoalInfo1,
-			GoalNonLocals, GoalInfo) },
+		{ goal_info_set_nonlocals(GoalNonLocals, GoalInfo1,GoalInfo) },
 		magic_info_get_pred_info(PredInfo),
 		{ PredModule = pred_info_module(PredInfo) },
 		{ PredName = pred_info_name(PredInfo) },
@@ -589,7 +588,7 @@
 context__rename_vars_in_call_list([], _, []).
 context__rename_vars_in_call_list([Goals0 - Call0 | Calls0],
 		Subn, [Goals - Call | Calls]) :-
-	goal_util__rename_vars_in_goals(Goals0, no, Subn, Goals),
+	goal_util__rename_vars_in_goals(no, Subn, Goals0, Goals),
 	magic_util__rename_vars_in_db_call(Call0, Subn, Call),
 	context__rename_vars_in_call_list(Calls0, Subn, Calls).
 
Index: compiler/cse_detection.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/cse_detection.m,v
retrieving revision 1.84
diff -u -b -r1.84 cse_detection.m
--- compiler/cse_detection.m	22 Jul 2005 12:31:53 -0000	1.84
+++ compiler/cse_detection.m	27 Aug 2005 16:52:52 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1995-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -48,6 +50,7 @@
 :- import_module hlds__quantification.
 :- import_module libs__globals.
 :- import_module libs__options.
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__prog_data.
 :- import_module parse_tree__prog_type.
 
@@ -67,10 +70,9 @@
 
 %-----------------------------------------------------------------------------%
 
+detect_cse(!ModuleInfo, !IO) :-
 	% Traverse the module structure, calling `detect_cse_in_goal'
 	% for each procedure body.
-
-detect_cse(!ModuleInfo, !IO) :-
 	module_info_predids(!.ModuleInfo, PredIds),
 	detect_cse_in_preds(PredIds, !ModuleInfo, !IO).
 
@@ -114,17 +116,15 @@
 		;
 			VeryVerbose = no
 		),
-		modecheck_proc(ProcId, PredId, !ModuleInfo, Errs, _Changed,
-			!IO),
+        modecheck_proc(ProcId, PredId, !ModuleInfo, Errs, _Changed, !IO),
 		( Errs > 0 ->
-			error("mode check fails when repeated")
+            unexpected(this_file, "mode check fails when repeated")
 		;
 			true
 		),
 		(
 			VeryVerbose = yes,
-			io__write_string("% Repeating switch detection for ",
-				!IO),
+            io__write_string("% Repeating switch detection for ", !IO),
 			hlds_out__write_pred_id(!.ModuleInfo, PredId, !IO),
 			io__write_string("\n", !IO)
 		;
@@ -160,9 +160,9 @@
 	pred_info_procedures(PredInfo0, ProcTable0),
 	map__lookup(ProcTable0, ProcId, ProcInfo0),
 
-		% To process each ProcInfo, we get the goal,
-		% initialize the instmap based on the modes of the head vars,
-		% and pass these to `detect_cse_in_goal'.
+    % To process each ProcInfo, we get the goal, initialize the instmap
+    % based on the modes of the head vars, and pass these to
+    % `detect_cse_in_goal'.
 
 	proc_info_goal(ProcInfo0, Goal0),
 	proc_info_get_initial_instmap(ProcInfo0, ModuleInfo0, InstMap0),
@@ -178,7 +178,7 @@
 	;
 		Redo = yes,
 
-		% ModuleInfo should not be changed by detect_cse_in_goal
+        % ModuleInfo should not be changed by detect_cse_in_goal.
 		CseInfo = cse_info(VarSet1, VarTypes1, RttiVarMaps, _),
 		proc_info_headvars(ProcInfo0, HeadVars),
 
@@ -202,7 +202,7 @@
 	% find disjunctions that contain common subexpressions
 	% and hoist these out of the disjunction. At the moment
 	% we only look for cses that are deconstruction unifications.
-
+    %
 :- pred detect_cse_in_goal(hlds_goal::in, instmap::in, cse_info::in,
 	cse_info::out, bool::out, hlds_goal::out) is det.
 
@@ -213,7 +213,7 @@
 	% the resulting instmap on exit from the goal, which is
 	% computed by applying the instmap delta specified in the
 	% goal's goalinfo.
-
+    %
 :- pred detect_cse_in_goal_1(hlds_goal::in, instmap::in, cse_info::in,
 	cse_info::out, bool::out, hlds_goal::out, instmap::out) is det.
 
@@ -224,7 +224,7 @@
 	instmap__apply_instmap_delta(InstMap0, InstMapDelta, InstMap).
 
 	% Here we process each of the different sorts of goals.
-
+    %
 :- pred detect_cse_in_goal_2(hlds_goal_expr::in, hlds_goal_info::in,
 	instmap::in, cse_info::in, cse_info::out, bool::out,
 	hlds_goal_expr::out) is det.
@@ -241,8 +241,7 @@
 			NonLocalVars, Vars, Modes, Det, Goal0)
 	->
 		ModuleInfo = !.CseInfo ^ module_info,
-		instmap__pre_lambda_update(ModuleInfo,
-			Vars, Modes, InstMap0, InstMap),
+        instmap__pre_lambda_update(ModuleInfo, Vars, Modes, InstMap0, InstMap),
 		detect_cse_in_goal(Goal0, InstMap, !CseInfo, Redo, Goal),
 		RHS = lambda_goal(Purity, PredOrFunc, EvalMethod, FixModes,
 			NonLocalVars, Vars, Modes, Det, Goal)
@@ -286,8 +285,8 @@
 		InstMap, !CseInfo, Redo, Goal).
 
 detect_cse_in_goal_2(shorthand(_), _, _, _, _, _, _) :-
-	% these should have been expanded out by now
-	error("detect_cse_in_goal_2: unexpected shorthand").
+    % These should have been expanded out by now.
+    unexpected(this_file, "detect_cse_in_goal_2: unexpected shorthand").
 
 %-----------------------------------------------------------------------------%
 
@@ -295,10 +294,8 @@
 	cse_info::out, bool::out, list(hlds_goal)::out) is det.
 
 detect_cse_in_conj([], _InstMap, !CseInfo, no, []).
-detect_cse_in_conj([Goal0 | Goals0], InstMap0, !CseInfo,
-		Redo, Goals) :-
-	detect_cse_in_goal_1(Goal0, InstMap0, !CseInfo, Redo1, Goal1,
-		InstMap1),
+detect_cse_in_conj([Goal0 | Goals0], InstMap0, !CseInfo, Redo, Goals) :-
+    detect_cse_in_goal_1(Goal0, InstMap0, !CseInfo, Redo1, Goal1, InstMap1),
 	detect_cse_in_conj(Goals0, InstMap1, !CseInfo, Redo2, Goals1),
 	( Goal1 = conj(ConjGoals) - _ ->
 		list__append(ConjGoals, Goals1, Goals)
@@ -325,7 +322,7 @@
 	% structure, and we've got a list of the non-local variables of that
 	% structure. Now for each non-local variable, we check whether each
 	% branch matches that variable against the same functor.
-
+    %
 :- pred detect_cse_in_disj(list(prog_var)::in, list(hlds_goal)::in,
 	hlds_goal_info::in, instmap::in, cse_info::in,
 	cse_info::out, bool::out, hlds_goal_expr::out) is det.
@@ -376,17 +373,15 @@
 		Var \= SwitchVar,
 		instmap__lookup_var(InstMap, Var, VarInst0),
 		ModuleInfo = !.CseInfo ^ module_info,
-		% XXX we only need inst_is_bound, but leave this as it is
-		% until mode analysis can handle aliasing between free
-		% variables.
+        % XXX We only need inst_is_bound, but leave this as it is until
+        % mode analysis can handle aliasing between free variables.
 		inst_is_ground_or_any(ModuleInfo, VarInst0),
 		common_deconstruct_cases(Cases0, Var, !CseInfo,
 			Unify, FirstOldNew, LaterOldNew, Cases)
 	->
 		maybe_update_existential_data_structures(Unify,
 			FirstOldNew, LaterOldNew, !CseInfo),
-		Goal = conj([Unify, switch(SwitchVar, CanFail, Cases)
-			- GoalInfo]),
+        Goal = conj([Unify, switch(SwitchVar, CanFail, Cases) - GoalInfo]),
 		Redo = yes
 	;
 		detect_cse_in_cases(Vars, SwitchVar, CanFail, Cases0, GoalInfo,
@@ -419,9 +414,8 @@
 	(
 		ModuleInfo = !.CseInfo ^ module_info,
 		instmap__lookup_var(InstMap, Var, VarInst0),
-		% XXX we only need inst_is_bound, but leave this as it is
-		% until mode analysis can handle aliasing between free
-		% variables.
+        % XXX We only need inst_is_bound, but leave this as it is until
+        % mode analysis can handle aliasing between free variables.
 		inst_is_ground_or_any(ModuleInfo, VarInst0),
 		common_deconstruct([Then0, Else0], Var, !CseInfo,
 			Unify, FirstOldNew, LaterOldNew, Goals),
@@ -451,19 +445,19 @@
 
 %-----------------------------------------------------------------------------%
 
-% common_deconstruct(Goals0, Var, !CseInfo, Unify, Goals):
-% input vars:
-%	Goals0 is a list of parallel goals in a branched structure
-%	(disjunction, if-then-else, or switch).
-%	Var is the variable we are looking for a common deconstruction on.
-%	!.CseInfo contains the original varset and type map.
-% output vars:
-%	!:CseInfo has a varset and a type map reflecting the new variables
-%	we have introduced.
-%	Goals is the modified version of Goals0 after the common deconstruction
-%	has been hoisted out, with the new variables as the functor arguments.
-%	Unify is the unification that was hoisted out.
-
+    % common_deconstruct(Goals0, Var, !CseInfo, Unify, Goals):
+    % input vars:
+    %   Goals0 is a list of parallel goals in a branched structure
+    %   (disjunction, if-then-else, or switch).
+    %   Var is the variable we are looking for a common deconstruction on.
+    %   !.CseInfo contains the original varset and type map.
+    % output vars:
+    %   !:CseInfo has a varset and a type map reflecting the new variables
+    %   we have introduced.
+    %   Goals is the modified version of Goals0 after the common deconstruction
+    %   has been hoisted out, with the new variables as the functor arguments.
+    %   Unify is the unification that was hoisted out.
+    %
 :- pred common_deconstruct(list(hlds_goal)::in, prog_var::in, cse_info::in,
 	cse_info::out, hlds_goal::out, assoc_list(prog_var)::out,
 	list(assoc_list(prog_var))::out, list(hlds_goal)::out) is semidet.
@@ -471,8 +465,7 @@
 common_deconstruct(Goals0, Var, !CseInfo, Unify, FirstOldNew, LaterOldNew,
 		Goals) :-
 	common_deconstruct_2(Goals0, Var, before_candidate,
-		have_candidate(Unify, FirstOldNew, LaterOldNew),
-		!CseInfo, Goals),
+        have_candidate(Unify, FirstOldNew, LaterOldNew), !CseInfo, Goals),
 	LaterOldNew = [_ | _].
 
 :- pred common_deconstruct_2(list(hlds_goal)::in, prog_var::in,
@@ -496,8 +489,7 @@
 common_deconstruct_cases(Cases0, Var, !CseInfo, Unify,
 		FirstOldNew, LaterOldNew, Cases) :-
 	common_deconstruct_cases_2(Cases0, Var, before_candidate,
-		have_candidate(Unify, FirstOldNew, LaterOldNew),
-		!CseInfo, Cases),
+        have_candidate(Unify, FirstOldNew, LaterOldNew), !CseInfo, Cases),
 	LaterOldNew = [_ | _].
 
 :- pred common_deconstruct_cases_2(list(case)::in, prog_var::in,
@@ -510,8 +502,7 @@
 	find_bind_var(Var, find_bind_var_for_cse_in_deconstruct, Goal0, Goal,
 		!CseState, !CseInfo, yes),
 	!.CseState = have_candidate(_, _, _),
-	common_deconstruct_cases_2(Cases0, Var, !CseState,
-		!CseInfo, Cases).
+    common_deconstruct_cases_2(Cases0, Var, !CseState, !CseInfo, Cases).
 
 %-----------------------------------------------------------------------------%
 
@@ -550,8 +541,8 @@
 		!CseState, !CseInfo) :-
 	(
 		!.CseState = before_candidate,
-		construct_common_unify(Var, Goal0, !CseInfo,
-			OldNewVars, HoistedGoal, Goals),
+        construct_common_unify(Var, Goal0, !CseInfo, OldNewVars,
+            HoistedGoal, Goals),
 		!:CseState = have_candidate(HoistedGoal, OldNewVars, [])
 	;
 		!.CseState = have_candidate(HoistedGoal,
@@ -586,21 +577,21 @@
 		GoalExpr0 = unify(_, Term, Umode, Unif0, Ucontext),
 		Unif0 = deconstruct(_, Consid, Args, Submodes, CanFail, CanCGC)
 	->
-		Unif = deconstruct(Var, Consid, Args, Submodes, CanFail,
-			CanCGC),
+        Unif = deconstruct(Var, Consid, Args, Submodes, CanFail, CanCGC),
 		( Term = functor(_, _, _) ->
 			GoalExpr1 = unify(Var, Term, Umode, Unif, Ucontext)
 		;
-			error("non-functor unify in construct_common_unify")
+            unexpected(this_file,
+                "non-functor unify in construct_common_unify")
 		),
 		goal_info_get_context(GoalInfo, Context),
 		create_parallel_subterms(Args, Context, Ucontext,
 			!CseInfo, OldNewVars, Replacements),
 		map__from_assoc_list(OldNewVars, Sub),
-		goal_util__rename_vars_in_goal(GoalExpr1 - GoalInfo, Sub,
-			HoistedGoal)
+        goal_util__rename_vars_in_goal(Sub,
+            GoalExpr1 - GoalInfo, HoistedGoal)
 	;
-		error("non-unify goal in construct_common_unify")
+        unexpected(this_file, "non-unify goal in construct_common_unify")
 	).
 
 :- pred create_parallel_subterms(list(prog_var)::in, prog_context::in,
@@ -657,7 +648,8 @@
 			OldHoistedVars),
 		pair_subterms(OldHoistedVars, Context, OC, Replacements)
 	;
-		error("find_similar_deconstruct: non-deconstruct unify")
+        unexpected(this_file,
+            "find_similar_deconstruct: non-deconstruct unify")
 	).
 
 :- pred pair_subterms(assoc_list(prog_var)::in, prog_context::in,
@@ -754,8 +746,7 @@
 		map__lookup(VarTypes, Var, Type),
 		type_util__is_existq_cons(ModuleInfo, Type, ConsId)
 	->
-		update_existential_data_structures(FirstOldNew, LaterOldNew,
-			!CseInfo)
+        update_existential_data_structures(FirstOldNew, LaterOldNew, !CseInfo)
 	;
 		true
 	).
@@ -772,27 +763,25 @@
 	RttiVarMaps0 = !.CseInfo ^ rtti_varmaps,
 	VarTypes0 = !.CseInfo ^ vartypes,
 
-		% Build a map for all locations in the rtti_varmaps that are
-		% changed by the application of FirstOldNewMap.  The keys
-		% of this map are the new locations, and the values are
-		% the tvars (from the first branch) that have had their
-		% locations moved.
+    % Build a map for all locations in the rtti_varmaps that are changed
+    % by the application of FirstOldNewMap. The keys of this map are the
+    % new locations, and the values are the tvars (from the first branch)
+    % that have had their locations moved.
 		%
 	rtti_varmaps_tvars(RttiVarMaps0, TvarsList),
 	list__foldl(find_type_info_locn_tvar_map(RttiVarMaps0, FirstOldNewMap),
 		TvarsList, map__init, NewTvarMap),
 
-		% Traverse TVarsList again, this time looking for locations
-		% in later branches that merge with locations in the first
-		% branch.  When we find one, add a type substitution which
-		% represents the type variables that were merged.
+    % Traverse TVarsList again, this time looking for locations in later
+    % branches that merge with locations in the first branch. When we find one,
+    % add a type substitution which represents the type variables that were
+    % merged.
 		%
 	list__foldl(find_merged_tvars(RttiVarMaps0, LaterOldNewMap, NewTvarMap),
 		TvarsList, map__init, TSubst),
 
-		% Apply the full old->new map and the type substitution
-		% to the rtti_varmaps, and apply the type substitution to the
-		% vartypes.
+    % Apply the full old->new map and the type substitution to the
+    % rtti_varmaps, and apply the type substitution to the vartypes.
 		%
 	list__append(FirstOldNew, LaterOldNew, OldNew),
 	map__from_assoc_list(OldNew, OldNewMap),
@@ -836,11 +825,16 @@
 		( NewTvar = Tvar ->
 			true
 		;
-			svmap__det_insert(Tvar, term__variable(NewTvar),
-				!TSubst)
+            svmap__det_insert(Tvar, term__variable(NewTvar), !TSubst)
 		)
 	;
 		true
 	).
+
+%-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "cse_detection.m".
 
 %-----------------------------------------------------------------------------%
Index: compiler/dead_proc_elim.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/dead_proc_elim.m,v
retrieving revision 1.100
diff -u -b -r1.100 dead_proc_elim.m
--- compiler/dead_proc_elim.m	23 May 2005 03:15:34 -0000	1.100
+++ compiler/dead_proc_elim.m	28 Aug 2005 06:25:23 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1996-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -32,25 +34,26 @@
 	--->	warning_pass
 	;	final_optimization_pass.
 
-	% Eliminate dead procedures.
-	% If the first argument is `warning_pass',
+    % Eliminate dead procedures. If the first argument is `warning_pass',
 	% also warn about any user-defined procedures that are dead.
-	% If the first argument is `final_optimization_pass',
-	% also eliminate any opt_imported procedures.
+    % If the first argument is `final_optimization_pass', also eliminate
+    % any opt_imported procedures.
+    %
 :- pred dead_proc_elim(dead_proc_pass::in, module_info::in, module_info::out,
 	io::di, io::uo) is det.
 
-	% Analyze which entities are needed, and for those entities
-	% which are needed, record how many times they are referenced
-	% (this information is used by our inlining heuristics).
+    % Analyze which entities are needed, and for those entities which are
+    % needed, record how many times they are referenced (this information
+    % is used by our inlining heuristics).
+    %
 :- pred dead_proc_elim__analyze(module_info::in, needed_map::out) is det.
 
-	% Optimize away any dead predicates.
-	% This is performed immediately after make_hlds.m to avoid doing
-	% semantic checking and optimization on predicates from `.opt'
-	% files which are not used in the current module. This assumes that
-	% the clauses_info is still valid, so it cannot be run after mode
-	% analysis.
+    % Optimize away any dead predicates. This is performed immediately after
+    % building the HLDS to avoid doing semantic checking and optimization
+    % on predicates from `.opt' files which are not used in the current module.
+    % This assumes that the clauses_info is still valid, so it cannot be run
+    % after mode analysis.
+    %
 :- pred dead_pred_elim(module_info::in, module_info::out) is det.
 
 :- type entity
@@ -81,6 +84,9 @@
 :- import_module require.
 :- import_module set.
 :- import_module string.
+:- import_module svmap.
+:- import_module svqueue.
+:- import_module svset.
 
 %-----------------------------------------------------------------------------%
 
@@ -115,18 +121,15 @@
 
 %-----------------------------------------------------------------------------%
 
-	% Find all needed entities.
-
-dead_proc_elim__analyze(ModuleInfo0, Needed) :-
+dead_proc_elim__analyze(ModuleInfo0, !:Needed) :-
 	set__init(Examined0),
-	dead_proc_elim__initialize(ModuleInfo0, Queue0, Needed0),
-	dead_proc_elim__examine(Queue0, Examined0, ModuleInfo0,
-		Needed0, Needed).
+    dead_proc_elim__initialize(ModuleInfo0, Queue0, !:Needed),
+    dead_proc_elim__examine(Queue0, Examined0, ModuleInfo0, !Needed).
 
 	% Add all exported entities to the queue and map.
-	% Note: changes here are likely to require changes to
-	% dead_pred_elim as well.
-
+    % Note: changes here are likely to require changes to dead_pred_elim
+    % as well.
+    %
 :- pred dead_proc_elim__initialize(module_info::in,
 	entity_queue::out, needed_map::out) is det.
 
@@ -149,7 +152,7 @@
 
 	% Add all normally exported procedures within the listed predicates
 	% to the queue and map.
-
+    %
 :- pred dead_proc_elim__initialize_preds(list(pred_id)::in, pred_table::in,
 	entity_queue::in, entity_queue::out, needed_map::in, needed_map::out)
 	is det.
@@ -163,7 +166,7 @@
 	dead_proc_elim__initialize_preds(PredIds, PredTable, !Queue, !Needed).
 
 	% Add the listed procedures to the queue and map.
-
+    %
 :- pred dead_proc_elim__initialize_procs(pred_id::in, list(proc_id)::in,
 	entity_queue::in, entity_queue::out, needed_map::in, needed_map::out)
 	is det.
@@ -171,13 +174,13 @@
 dead_proc_elim__initialize_procs(_PredId, [], !Queue, !Needed).
 dead_proc_elim__initialize_procs(PredId, [ProcId | ProcIds],
 		!Queue, !Needed) :-
-	queue__put(!.Queue, proc(PredId, ProcId), !:Queue),
-	map__set(!.Needed, proc(PredId, ProcId), no, !:Needed),
+    svqueue__put(proc(PredId, ProcId), !Queue),
+    svmap__set(proc(PredId, ProcId), no, !Needed),
 	dead_proc_elim__initialize_procs(PredId, ProcIds, !Queue, !Needed).
 
 	% Add procedures exported to C by a pragma(export, ...) declaration
 	% to the queue and map.
-
+    %
 :- pred dead_proc_elim__initialize_pragma_exports(
 	list(pragma_exported_proc)::in,
 	entity_queue::in, entity_queue::out, needed_map::in, needed_map::out)
@@ -187,10 +190,9 @@
 dead_proc_elim__initialize_pragma_exports([PragmaProc | PragmaProcs],
 		!Queue, !Needed) :-
 	PragmaProc = pragma_exported_proc(PredId, ProcId, _CFunction, _Ctxt),
-	queue__put(!.Queue, proc(PredId, ProcId), !:Queue),
-	map__set(!.Needed, proc(PredId, ProcId), no, !:Needed),
-	dead_proc_elim__initialize_pragma_exports(PragmaProcs,
-		!Queue, !Needed).
+    svqueue__put(proc(PredId, ProcId), !Queue),
+    svmap__set(proc(PredId, ProcId), no, !Needed),
+    dead_proc_elim__initialize_pragma_exports(PragmaProcs, !Queue, !Needed).
 
 :- pred dead_proc_elim__initialize_base_gen_infos(list(type_ctor_gen_info)::in,
 	entity_queue::in, entity_queue::out, needed_map::in, needed_map::out)
@@ -205,24 +207,22 @@
 		% XXX: We'd like to do this, but there are problems.
 		% status_is_exported(Status, yes)
 		%
-		% We need to do more thorough analysis of the
-		% reachability of the special predicates, in general,
-		% because using arg/3 allows us to get at type_ctor_info
-		% via the type_ctor_layout. The type_ctor_infos of
-		% arguments of functors may have had their special preds
-		% eliminated, but they can still be called. In addition,
-		% it would be nice for pragma C code to have some
-		% support for using compiler generated data structures
-		% and preds, so that they aren't just eliminated.
-		%
-		% So presently, all type_ctor_infos will be treated
-		% as exported, and hence no special preds will be
-		% eliminated.
+        % We need to do more thorough analysis of the reachability of the
+        % special predicates, in general, because using arg/3 allows us
+        % to get at type_ctor_info via the type_ctor_layout.
+        % The type_ctor_infos of arguments of functors may have had their
+        % special preds eliminated, but they can still be called. In addition,
+        % it would be nice for pragma C code to have some support for using
+        % compiler generated data structures and preds, so that they aren't
+        % just eliminated.
+        %
+        % So presently, all type_ctor_infos will be treated as exported,
+        % and hence no special preds will be eliminated.
 		semidet_succeed
 	->
 		Entity = base_gen_info(ModuleName, TypeName, Arity),
-		queue__put(!.Queue, Entity, !:Queue),
-		map__set(!.Needed, Entity, no, !:Needed)
+        svqueue__put(Entity, !Queue),
+        svmap__set(Entity, no, !Needed)
 	;
 		true
 	),
@@ -230,9 +230,8 @@
 		!Queue, !Needed).
 
 :- pred dead_proc_elim__initialize_class_methods(class_table::in,
-	instance_table::in,
-	entity_queue::in, entity_queue::out, needed_map::in, needed_map::out)
-	is det.
+    instance_table::in, entity_queue::in, entity_queue::out,
+    needed_map::in, needed_map::out) is det.
 
 dead_proc_elim__initialize_class_methods(Classes, Instances,
 		!Queue, !Needed) :-
@@ -248,18 +247,14 @@
 
 get_instance_pred_procs(Instance, !Queue, !Needed) :-
 	Instance = hlds_instance_defn(_, _, _, _, _, _, PredProcIds, _, _),
-
-	%
 	% We need to keep the instance methods for all instances
 	% for optimization of method lookups.
-	%
 	(
 			% This should never happen
 		PredProcIds = no
 	;
 		PredProcIds = yes(Ids),
-		list__foldl2(get_class_interface_pred_proc, Ids,
-			!Queue, !Needed)
+        list__foldl2(get_class_interface_pred_proc, Ids, !Queue, !Needed)
 	).
 
 :- pred get_class_pred_procs(hlds_class_defn::in,
@@ -276,37 +271,33 @@
 
 get_class_interface_pred_proc(ClassProc, !Queue, !Needed) :-
 	ClassProc = hlds_class_proc(PredId, ProcId),
-	queue__put(!.Queue, proc(PredId, ProcId), !:Queue),
-	map__set(!.Needed, proc(PredId, ProcId), no, !:Needed).
+    svqueue__put(proc(PredId, ProcId), !Queue),
+    svmap__set(proc(PredId, ProcId), no, !Needed).
 
 %-----------------------------------------------------------------------------%
 
 :- pred dead_proc_elim__examine(entity_queue::in, examined_set::in,
 	module_info::in, needed_map::in, needed_map::out) is det.
 
-dead_proc_elim__examine(Queue0, Examined0, ModuleInfo, !Needed) :-
+dead_proc_elim__examine(!.Queue, !.Examined, ModuleInfo, !Needed) :-
 	% see if the queue is empty
-	( queue__get(Queue0, Entity, Queue1) ->
+    ( svqueue__get(Entity, !Queue) ->
 		% see if the next element has been examined before
-		( set__member(Entity, Examined0) ->
-			dead_proc_elim__examine(Queue1, Examined0, ModuleInfo,
-				!Needed)
+        ( set__member(Entity, !.Examined) ->
+            dead_proc_elim__examine(!.Queue, !.Examined, ModuleInfo, !Needed)
 		;
-			set__insert(Examined0, Entity, Examined1),
+            svset__insert(Entity, !Examined),
 			(
 				Entity = proc(PredId, ProcId),
 				PredProcId = proc(PredId, ProcId),
-				dead_proc_elim__examine_proc(
-					PredProcId, ModuleInfo,
-					Queue1, Queue2, !Needed)
+                dead_proc_elim__examine_proc(PredProcId, ModuleInfo,
+                    !Queue, !Needed)
 			;
 				Entity = base_gen_info(Module, Type, Arity),
-				dead_proc_elim__examine_base_gen_info(
-					Module, Type, Arity, ModuleInfo,
-					Queue1, Queue2, !Needed)
+                dead_proc_elim__examine_base_gen_info(Module, Type, Arity,
+                    ModuleInfo, !Queue, !Needed)
 			),
-			dead_proc_elim__examine(Queue2, Examined1, ModuleInfo,
-				!Needed)
+            dead_proc_elim__examine(!.Queue, !.Examined, ModuleInfo, !Needed)
 		)
 	;
 		true
@@ -315,9 +306,8 @@
 %-----------------------------------------------------------------------------%
 
 :- pred dead_proc_elim__examine_base_gen_info(module_name::in, string::in,
-	arity::in, module_info::in,
-	entity_queue::in, entity_queue::out, needed_map::in, needed_map::out)
-	is det.
+    arity::in, module_info::in, entity_queue::in, entity_queue::out,
+    needed_map::in, needed_map::out) is det.
 
 dead_proc_elim__examine_base_gen_info(ModuleName, TypeName, Arity, ModuleInfo,
 		!Queue, !Needed) :-
@@ -339,8 +329,7 @@
 		[TypeCtorGenInfo | TypeCtorGenInfos], Refs) :-
 	(
 		TypeCtorGenInfo = type_ctor_gen_info(_TypeCtor, ModuleName,
-			TypeName, TypeArity, _Status, _HldsDefn,
-			Unify, Compare)
+            TypeName, TypeArity, _Status, _HldsDefn, Unify, Compare)
 	->
 		Refs = [Unify, Compare]
 	;
@@ -362,8 +351,8 @@
 dead_proc_elim__examine_refs([Ref | Refs], !Queue, !Needed) :-
 	Ref = proc(PredId, ProcId),
 	Entity = proc(PredId, ProcId),
-	queue__put(!.Queue, Entity, !:Queue),
-	map__set(!.Needed, Entity, no, !:Needed),
+    svqueue__put(Entity, !Queue),
+    svmap__set(Entity, no, !Needed),
 	dead_proc_elim__examine_refs(Refs, !Queue, !Needed).
 
 %-----------------------------------------------------------------------------%
@@ -444,7 +433,7 @@
 		% if it's reachable and recursive, then we can't
 		% eliminate or inline it
 		NewNotation = no,
-		map__set(!.Needed, proc(PredId, ProcId), NewNotation, !:Needed)
+        svmap__set(proc(PredId, ProcId), NewNotation, !Needed)
 	; map__search(!.Needed, proc(PredId, ProcId), OldNotation) ->
 		(
 			OldNotation = no,
@@ -453,42 +442,40 @@
 			OldNotation = yes(Count),
 			NewNotation = yes(Count + 1)
 		),
-		map__det_update(!.Needed, proc(PredId, ProcId), NewNotation,
-			!:Needed)
+        svmap__det_update(proc(PredId, ProcId), NewNotation, !Needed)
 	;
 		NewNotation = yes(1),
-		map__set(!.Needed, proc(PredId, ProcId), NewNotation, !:Needed)
+        svmap__set(proc(PredId, ProcId), NewNotation, !Needed)
 	).
 dead_proc_elim__examine_expr(foreign_proc(_, PredId, ProcId, _, _, _),
 		_CurrProc, !Queue, !Needed) :-
-	queue__put(!.Queue, proc(PredId, ProcId), !:Queue),
-	map__set(!.Needed, proc(PredId, ProcId), no, !:Needed).
+    svqueue__put(proc(PredId, ProcId), !Queue),
+    svmap__set(proc(PredId, ProcId), no, !Needed).
 dead_proc_elim__examine_expr(unify(_,_,_, Uni, _), _CurrProc,
 		!Queue, !Needed) :-
 	(
 		Uni = construct(_, ConsId, _, _, _, _, _),
 		(
 			ConsId = pred_const(ShroudedPredProcId, _),
-			proc(PredId, ProcId) =
-				unshroud_pred_proc_id(ShroudedPredProcId),
+            proc(PredId, ProcId) = unshroud_pred_proc_id(ShroudedPredProcId),
 			Entity = proc(PredId, ProcId)
 		;
 			ConsId = type_ctor_info_const(Module, TypeName, Arity),
 			Entity = base_gen_info(Module, TypeName, Arity)
 		)
 	->
-		queue__put(!.Queue, Entity, !:Queue),
-		map__set(!.Needed, Entity, no, !:Needed)
+        svqueue__put(Entity, !Queue),
+        svmap__set(Entity, no, !Needed)
 	;
 		true
 	).
-dead_proc_elim__examine_expr(shorthand(_), _, _, _, _, _) :-
-	% these should have been expanded out by now
-	error("detect_cse_in_goal_2: unexpected shorthand").
+dead_proc_elim__examine_expr(shorthand(_), _, !Queue, !Needed) :-
+    % These should have been expanded out by now.
+    unexpected(this_file, "detect_cse_in_goal_2: unexpected shorthand").
 
 %-----------------------------------------------------------------------------%
 
-		% information used during the elimination phase.
+        % Information used during the elimination phase.
 
 :- type elim_info
 	--->	elimination_info(
@@ -502,6 +489,7 @@
 
 	% Given the information about which entities are needed,
 	% eliminate procedures which are not needed.
+    %
 :- pred dead_proc_elim__eliminate(dead_proc_pass::in, needed_map::in,
 	module_info::in, module_info::out, io::di, io::uo) is det.
 
@@ -510,12 +498,10 @@
 	module_info_preds(!.ModuleInfo, PredTable0),
 
 	Changed0 = no,
-	ElimInfo0 = elimination_info(!.Needed, !.ModuleInfo, PredTable0,
-		Changed0),
+    ElimInfo0 = elimination_info(!.Needed, !.ModuleInfo, PredTable0, Changed0),
 	list__foldl2(dead_proc_elim__eliminate_pred(Pass), PredIds,
 		ElimInfo0, ElimInfo, !IO),
-	ElimInfo = elimination_info(!:Needed, !:ModuleInfo, PredTable,
-		Changed),
+    ElimInfo = elimination_info(!:Needed, !:ModuleInfo, PredTable, Changed),
 
 	module_info_set_preds(PredTable, !ModuleInfo),
 	module_info_type_ctor_gen_infos(!.ModuleInfo, TypeCtorGenInfos0),
@@ -524,28 +510,25 @@
 	module_info_set_type_ctor_gen_infos(TypeCtorGenInfos, !ModuleInfo),
 	(
 		Changed = yes,
-		% The dependency graph will still contain references to the
-		% eliminated procedures, so it must be rebuilt if it will
-		% be used later.
+        % The dependency graph will still contain references to the eliminated
+        % procedures, so it must be rebuilt if it will be used later.
 		module_info_clobber_dependency_info(!ModuleInfo)
 	;
 		Changed	= no
 	).
 
-		% eliminate any unused procedures for this pred
-
+    % Eliminate any unused procedures for this pred.
+    %
 :- pred dead_proc_elim__eliminate_pred(dead_proc_pass::in, pred_id::in,
 	elim_info::in, elim_info::out, io::di, io::uo) is det.
 
 dead_proc_elim__eliminate_pred(Pass, PredId, !ElimInfo, !IO) :-
-	!.ElimInfo = elimination_info(Needed, ModuleInfo, PredTable0,
-		Changed0),
+    !.ElimInfo = elimination_info(Needed, ModuleInfo, PredTable0, Changed0),
 	map__lookup(PredTable0, PredId, PredInfo0),
 	pred_info_import_status(PredInfo0, Status),
 	(
 		% Find out if the predicate is defined in this module.
-		% If yes, find out also whether any of its procedures
-		% must be kept.
+        % If yes, find out also whether any of its procedures must be kept.
 		( Status = local,
 			Keep = no,
 			(
@@ -555,13 +538,11 @@
 			->
 				WarnForThisProc = no
 			;
-				% Don't warn for procedures introduced from
-				% lambda expressions.  The only time those
-				% procedures will be unused is if the procedure
-				% containing the lambda expression is unused,
-				% and in that case, we already warn for that
-				% containing procedure if appropriate.
-				% Likewise, don't warn for procedures
+                % Don't warn for procedures introduced from lambda expressions.
+                % The only time those procedures will be unused is if the
+                % procedure containing the lambda expression is unused,
+                % and in that case, we already warn for that containing
+                % procedure if appropriate. Likewise, don't warn for procedures
 				% introduced for type specialization.
 				PredName = pred_info_name(PredInfo0),
 				( string__prefix(PredName, "IntroducedFrom__")
@@ -585,25 +566,22 @@
 		pred_info_procedures(PredInfo0, ProcTable0),
 		list__foldl3(dead_proc_elim__eliminate_proc(Pass, PredId,
 			Keep, WarnForThisProc, !.ElimInfo),
-			ProcIds, ProcTable0, ProcTable, Changed0, Changed,
-			!IO),
+            ProcIds, ProcTable0, ProcTable, Changed0, Changed, !IO),
 		pred_info_set_procedures(ProcTable, PredInfo0, PredInfo),
 		map__det_update(PredTable0, PredId, PredInfo, PredTable)
 	;
-		% Don't generate code in the current module for
-		% unoptimized opt_imported preds (that is, for
-		% opt_imported preds which we have not by this point
-		% managed to inline or specialize; this code should be
-		% called with `Pass = final_optimization_pass'
-		% only after inlining and specialization is complete).
+        % Don't generate code in the current module for unoptimized
+        % opt_imported preds (that is, for opt_imported preds which we have not
+        % by this point managed to inline or specialize; this code should be
+        % called with `Pass = final_optimization_pass' only after inlining
+        % and specialization is complete).
 		Pass = final_optimization_pass,
 		Status = opt_imported
 	->
 		Changed = yes,
 		ProcIds = pred_info_procids(PredInfo0),
 		pred_info_procedures(PredInfo0, ProcTable0),
-			% Reduce memory usage by replacing the goals with
-			% conj([]).
+            % Reduce memory usage by replacing the goals with conj([]).
 			% XXX this looks fishy to me - zs
 		DestroyGoal =
 			(pred(Id::in, PTable0::in, PTable::out) is det :-
@@ -618,12 +596,10 @@
 		pred_info_set_import_status(imported(interface),
 			PredInfo1, PredInfo),
 		map__det_update(PredTable0, PredId, PredInfo, PredTable),
-		globals__io_lookup_bool_option(very_verbose, VeryVerbose,
-			!IO),
+        globals__io_lookup_bool_option(very_verbose, VeryVerbose, !IO),
 		(
 			VeryVerbose = yes,
-			write_pred_progress_message(
-				"% Eliminated opt_imported predicate ",
+            write_pred_progress_message("% Eliminated opt_imported predicate ",
 				PredId, ModuleInfo, !IO)
 		;
 			VeryVerbose = no
@@ -635,12 +611,12 @@
 	),
 	!:ElimInfo = elimination_info(Needed, ModuleInfo, PredTable, Changed).
 
-		% eliminate a procedure, if unused
-
+    % Eliminate a procedure, if unused.
+    %
 :- pred dead_proc_elim__eliminate_proc(dead_proc_pass::in, pred_id::in,
 	maybe(proc_id)::in, bool::in, elim_info::in, proc_id::in,
-	proc_table::in, proc_table::out, bool::in, bool::out,
-	io::di, io::uo) is det.
+    proc_table::in, proc_table::out, bool::in, bool::out, io::di, io::uo)
+    is det.
 
 dead_proc_elim__eliminate_proc(Pass, PredId, Keep, WarnForThisProc, ElimInfo,
 		ProcId, !ProcTable, !Changed, !IO) :-
@@ -656,12 +632,12 @@
 	;
 		!:Changed = yes,
 		globals__io_lookup_bool_option(very_verbose, VeryVerbose, !IO),
-		( VeryVerbose = yes ->
-			write_proc_progress_message(
-				"% Eliminated the dead procedure ",
+        (
+            VeryVerbose = yes,
+            write_proc_progress_message("% Eliminated the dead procedure ",
 				PredId, ProcId, ModuleInfo, !IO)
 		;
-			true
+            VeryVerbose = no
 		),
 		(
 			Pass = warning_pass,
@@ -670,14 +646,12 @@
 			% since that is already checked by mercury_compile.m
 			% when deciding whether to invoke this warning_pass
 		->
-			proc_info_context(!.ProcTable ^ det_elem(ProcId),
-				Context),
-			warn_dead_proc(PredId, ProcId, Context, ModuleInfo,
-				!IO)
+            proc_info_context(!.ProcTable ^ det_elem(ProcId), Context),
+            warn_dead_proc(PredId, ProcId, Context, ModuleInfo, !IO)
 		;
 			true
 		),
-		map__delete(!.ProcTable, ProcId, !:ProcTable)
+        svmap__delete(ProcId, !ProcTable)
 	).
 
 :- pred warn_dead_proc(pred_id::in, proc_id::in, prog_context::in,
@@ -785,50 +759,47 @@
 :- pred dead_pred_elim_add_entity(entity::in, queue(pred_id)::in,
 	queue(pred_id)::out, set(pred_id)::in, set(pred_id)::out) is det.
 
-dead_pred_elim_add_entity(base_gen_info(_, _, _), Q, Q, Preds, Preds).
-dead_pred_elim_add_entity(proc(PredId, _), Q0, Q, Preds0, Preds) :-
-	queue__put(Q0, PredId, Q),
-	set__insert(Preds0, PredId, Preds).
+dead_pred_elim_add_entity(base_gen_info(_, _, _), !Queue, !Preds).
+dead_pred_elim_add_entity(proc(PredId, _), !Queue, !Preds) :-
+    svqueue__put(PredId, !Queue),
+    svset__insert(PredId, !Preds).
 
 :- pred dead_pred_elim_initialize(pred_id::in, dead_pred_info::in,
 	dead_pred_info::out) is det.
 
 dead_pred_elim_initialize(PredId, DeadInfo0, DeadInfo) :-
-	DeadInfo0 = dead_pred_info(ModuleInfo, Q0, Ex, Needed, NeededNames0),
+    some [!Queue, !NeededNames] (
+        DeadInfo0 = dead_pred_info(ModuleInfo, !:Queue, Ex, Needed,
+            !:NeededNames),
 	module_info_pred_info(ModuleInfo, PredId, PredInfo),
 	(
 		PredModule = pred_info_module(PredInfo),
 		PredName = pred_info_name(PredInfo),
 		PredArity = pred_info_orig_arity(PredInfo),
 		(
-			% Don't eliminate special preds since they won't
-			% be actually called from the HLDS until after
-			% polymorphism.
+                % Don't eliminate special preds since they won't be actually
+                % called from the HLDS until after polymorphism.
 			is_unify_or_compare_pred(PredInfo)
 		;
-			% Don't eliminate preds from builtin modules,
-			% since later passes of the compiler may introduce
-			% calls to them (e.g. polymorphism.m needs unify/2
-			% and friends).
+                % Don't eliminate preds from builtin modules, since later
+                % passes of the compiler may introduce calls to them
+                % (e.g. polymorphism.m needs unify/2 and friends).
 			any_mercury_builtin_module(PredModule)
 		;
-			% Don't attempt to eliminate local preds here, since we
-			% want to do semantic checking on those even if they
-			% aren't used.
+                % Don't attempt to eliminate local preds here, since we want
+                % to do semantic checking on those even if they aren't used.
 			\+ pred_info_is_imported(PredInfo),
 			\+ pred_info_import_status(PredInfo, opt_imported)
 		;
-			% Don't eliminate predicates declared in this module
-			% with a `:- external' or `:- pragma base_relation'
-			% declaration.
-			% magic.m will change the import_status to
-			% `exported' when it generates the interface
-			% procedure for a base relation.
+                % Don't eliminate predicates declared in this module with a
+                % `:- external' or `:- pragma base_relation' declaration.
+                % magic.m will change the import_status to `exported' when it
+                % generates the interface procedure for a base relation.
 			module_info_name(ModuleInfo, PredModule)
 		;
-			% Don't eliminate <foo>_init_any/1 predicates;
-			% modes.m may insert calls to them to initialize
-			% variables from inst `free' to inst `any'.
+                % Don't eliminate <foo>_init_any/1 predicates; modes.m may
+                % insert calls to them to initialize variables from inst `free'
+                % to inst `any'.
 			string__remove_suffix(PredName, "_init_any", _),
 			PredArity = 1
 		;
@@ -836,38 +807,40 @@
 			pred_info_get_goal_type(PredInfo, promise(_))
 		)
 	->
-		set__insert(NeededNames0, qualified(PredModule, PredName),
-			NeededNames),
-		queue__put(Q0, PredId, Q)
+            svset__insert(qualified(PredModule, PredName), !NeededNames),
+            svqueue__put(PredId, !Queue)
 	;
-		NeededNames = NeededNames0,
-		Q = Q0
+            true
 	),
-	DeadInfo = dead_pred_info(ModuleInfo, Q, Ex, Needed, NeededNames).
+        DeadInfo = dead_pred_info(ModuleInfo, !.Queue, Ex, Needed,
+            !.NeededNames)
+    ).
 
 :- pred dead_pred_elim_analyze(dead_pred_info::in, dead_pred_info::out) is det.
 
-dead_pred_elim_analyze(DeadInfo0, DeadInfo) :-
-	DeadInfo0 = dead_pred_info(ModuleInfo, Q0, Ex0, Needed0, NeededNames),
-	( queue__get(Q0, PredId, Q) ->
-		( set__member(PredId, Ex0) ->
-			DeadInfo2 = dead_pred_info(ModuleInfo, Q,
-				Ex0, Needed0, NeededNames)
-		;
-			set__insert(Needed0, PredId, Needed),
-			set__insert(Ex0, PredId, Ex),
-			DeadInfo1 = dead_pred_info(ModuleInfo, Q, Ex,
-				Needed, NeededNames),
+dead_pred_elim_analyze(!DeadInfo) :-
+    some [!Queue, !Ex, !Needed] (
+        !.DeadInfo = dead_pred_info(ModuleInfo, !:Queue, !:Ex,
+            !:Needed, NeededNames),
+        ( svqueue__get(PredId, !Queue) ->
+            ( set__member(PredId, !.Ex) ->
+                !:DeadInfo = dead_pred_info(ModuleInfo, !.Queue, !.Ex,
+                    !.Needed, NeededNames)
+            ;
+                svset__insert(PredId, !Needed),
+                svset__insert(PredId, !Ex),
+                !:DeadInfo = dead_pred_info(ModuleInfo, !.Queue, !.Ex,
+                    !.Needed, NeededNames),
 			module_info_pred_info(ModuleInfo, PredId, PredInfo),
 			pred_info_clauses_info(PredInfo, ClausesInfo),
 			clauses_info_clauses_rep(ClausesInfo, ClausesRep),
 			get_clause_list_any_order(ClausesRep, Clauses),
-			list__foldl(dead_pred_elim_process_clause, Clauses,
-				DeadInfo1, DeadInfo2)
+                list__foldl(dead_pred_elim_process_clause, Clauses, !DeadInfo)
 		),
-		dead_pred_elim_analyze(DeadInfo2, DeadInfo)
+            dead_pred_elim_analyze(!DeadInfo)
 	;
-		DeadInfo = DeadInfo0
+            true
+        )
 	).
 
 :- pred dead_pred_elim_process_clause(clause::in,
@@ -904,8 +877,8 @@
 pre_modecheck_examine_goal(unify(_, Rhs, _, _, _) - _, !DeadInfo) :-
 	pre_modecheck_examine_unify_rhs(Rhs, !DeadInfo).
 pre_modecheck_examine_goal(shorthand(_) - _, !DeadInfo) :-
-	% these should have been expanded out by now
-	error("pre_modecheck_examine_goal: unexpected shorthand").
+    % These should have been expanded out by now.
+    unexpected(this_file, "pre_modecheck_examine_goal: unexpected shorthand").
 
 :- pred pre_modecheck_examine_unify_rhs(unify_rhs::in,
 		dead_pred_info::in, dead_pred_info::out) is det.
@@ -924,24 +897,32 @@
 :- pred dead_pred_info_add_pred_name(sym_name::in,
 	dead_pred_info::in, dead_pred_info::out) is det.
 
-dead_pred_info_add_pred_name(Name, DeadInfo0, DeadInfo) :-
-	DeadInfo0 = dead_pred_info(ModuleInfo, Q0, Ex, Needed, NeededNames0),
-	( set__member(Name, NeededNames0) ->
-		DeadInfo = DeadInfo0
+dead_pred_info_add_pred_name(Name, !DeadInfo) :-
+    some [!Queue, !NeededNames] (
+        !.DeadInfo = dead_pred_info(ModuleInfo, !:Queue, Ex,
+            Needed, !:NeededNames),
+        ( set__member(Name, !.NeededNames) ->
+            true
 	;
 		module_info_get_predicate_table(ModuleInfo, PredicateTable),
-		set__insert(NeededNames0, Name, NeededNames),
+            svset__insert(Name, !NeededNames),
 		(
 			predicate_table_search_sym(PredicateTable,
 				may_be_partially_qualified, Name, PredIds)
 		->
-			queue__put_list(Q0, PredIds, Q)
+                svqueue__put_list(PredIds, !Queue)
 		;
-			Q = Q0
+                true
 		),
-		DeadInfo = dead_pred_info(ModuleInfo, Q, Ex,
-			Needed, NeededNames)
+            !:DeadInfo = dead_pred_info(ModuleInfo, !.Queue, Ex,
+                Needed, !.NeededNames)
+        )
 	).
 
 %-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "dead_proc_elim.m".
+
 %-----------------------------------------------------------------------------%
Index: compiler/deep_profiling.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/deep_profiling.m,v
retrieving revision 1.34
diff -u -b -r1.34 deep_profiling.m
--- compiler/deep_profiling.m	12 Aug 2005 05:14:09 -0000	1.34
+++ compiler/deep_profiling.m	28 Aug 2005 06:24:07 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 2001-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -39,6 +41,7 @@
 :- import_module ll_backend__code_util.
 :- import_module ll_backend__trace.
 :- import_module mdbcomp__prim_data.
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__prog_data.
 :- import_module parse_tree__prog_util.
 :- import_module parse_tree__prog_type.
@@ -55,6 +58,8 @@
 :- import_module set.
 :- import_module std_util.
 :- import_module string.
+:- import_module svmap.
+:- import_module svvarset.
 :- import_module term.
 :- import_module varset.
 
@@ -81,27 +86,25 @@
 :- pred apply_tail_recursion_transformation(module_info::in, module_info::out)
 	is det.
 
-apply_tail_recursion_transformation(ModuleInfo0, ModuleInfo) :-
-	module_info_ensure_dependency_info(ModuleInfo0, ModuleInfo1),
-	module_info_dependency_info(ModuleInfo1, DepInfo),
+apply_tail_recursion_transformation(!ModuleInfo) :-
+    module_info_ensure_dependency_info(!ModuleInfo),
+    module_info_dependency_info(!.ModuleInfo, DepInfo),
 	hlds_dependency_info_get_dependency_ordering(DepInfo, SCCs),
-	list__foldl(apply_tail_recursion_to_scc, SCCs,
-		ModuleInfo1, ModuleInfo).
+    list__foldl(apply_tail_recursion_to_scc, SCCs, !ModuleInfo).
 
 :- pred apply_tail_recursion_to_scc(list(pred_proc_id)::in,
 	module_info::in, module_info::out) is det.
 
-apply_tail_recursion_to_scc(SCC, ModuleInfo0, ModuleInfo) :-
+apply_tail_recursion_to_scc(SCC, !ModuleInfo) :-
 	% For the time being, we only look for self-tail-recursive calls.
-	list__foldl(apply_tail_recursion_to_proc, SCC,
-		ModuleInfo0, ModuleInfo).
+    list__foldl(apply_tail_recursion_to_proc, SCC, !ModuleInfo).
 
 :- pred apply_tail_recursion_to_proc(pred_proc_id::in,
 	module_info::in, module_info::out) is det.
 
-apply_tail_recursion_to_proc(PredProcId, ModuleInfo0, ModuleInfo) :-
+apply_tail_recursion_to_proc(PredProcId, !ModuleInfo) :-
 	PredProcId = proc(PredId, ProcId),
-	module_info_preds(ModuleInfo0, PredTable0),
+    module_info_preds(!.ModuleInfo, PredTable0),
 	map__lookup(PredTable0, PredId, PredInfo0),
 	pred_info_arg_types(PredInfo0, Types),
 	pred_info_procedures(PredInfo0, ProcTable0),
@@ -115,55 +118,46 @@
 		SolnCount \= at_most_many,
 		proc_info_headvars(ProcInfo0, HeadVars),
 		proc_info_argmodes(ProcInfo0, Modes),
-		find_list_of_output_args(HeadVars, Modes, Types, ModuleInfo0,
+        find_list_of_output_args(HeadVars, Modes, Types, !.ModuleInfo,
 			Outputs),
 		clone_proc_id(ProcTable0, ProcId, CloneProcId),
 		ClonePredProcId = proc(PredId, CloneProcId),
-		ApplyInfo = apply_tail_recursion_info(ModuleInfo0,
+        ApplyInfo = apply_tail_recursion_info(!.ModuleInfo,
 			[PredProcId - ClonePredProcId], Detism, Outputs),
-		apply_tail_recursion_to_goal(Goal0, ApplyInfo,
-			Goal, no, FoundTailCall, _),
+        apply_tail_recursion_to_goal(Goal0, ApplyInfo, Goal,
+        no, FoundTailCall, _),
 		FoundTailCall = yes
 	->
 		proc_info_set_goal(Goal, ProcInfo0, ProcInfo1),
 		figure_out_rec_call_numbers(Goal, 0, _N, [], TailCallSites),
 		OrigDeepRecInfo = yes(deep_recursion_info(
 			outer_proc(ClonePredProcId),
-			[visible_scc_data(PredProcId, ClonePredProcId,
-				TailCallSites)])),
-		OrigDeepProfileInfo = deep_profile_proc_info(
-			OrigDeepRecInfo, no),
-		CloneDeepRecInfo = yes(deep_recursion_info(
-			inner_proc(PredProcId),
-			[visible_scc_data(PredProcId, ClonePredProcId,
-				TailCallSites)])),
-		CloneDeepProfileInfo = deep_profile_proc_info(
-			CloneDeepRecInfo, no),
-		proc_info_set_maybe_deep_profile_info(
-			yes(OrigDeepProfileInfo), ProcInfo1, ProcInfo),
+            [visible_scc_data(PredProcId, ClonePredProcId, TailCallSites)])),
+        OrigDeepProfileInfo = deep_profile_proc_info(OrigDeepRecInfo, no),
+        CloneDeepRecInfo = yes(deep_recursion_info(inner_proc(PredProcId),
+            [visible_scc_data(PredProcId, ClonePredProcId, TailCallSites)])),
+        CloneDeepProfileInfo = deep_profile_proc_info(CloneDeepRecInfo, no),
+        proc_info_set_maybe_deep_profile_info(yes(OrigDeepProfileInfo),
+            ProcInfo1, ProcInfo),
 		proc_info_set_maybe_deep_profile_info(
 			yes(CloneDeepProfileInfo), ProcInfo1, CloneProcInfo),
 		map__det_update(ProcTable0, ProcId, ProcInfo, ProcTable1),
-		map__det_insert(ProcTable1, CloneProcId, CloneProcInfo,
-			ProcTable),
+        map__det_insert(ProcTable1, CloneProcId, CloneProcInfo, ProcTable),
 		pred_info_set_procedures(ProcTable, PredInfo0, PredInfo),
 		map__det_update(PredTable0, PredId, PredInfo, PredTable),
-		module_info_set_preds(PredTable, ModuleInfo0, ModuleInfo)
+        module_info_set_preds(PredTable, !ModuleInfo)
 	;
-		ModuleInfo = ModuleInfo0
+        true
 	).
 
 :- pred find_list_of_output_args(list(prog_var)::in, list(mode)::in,
 	list(type)::in, module_info::in, list(prog_var)::out) is det.
 
-find_list_of_output_args(Vars, Modes, Types, ModuleInfo, Outputs) :-
-	(
-		find_list_of_output_args_2(Vars, Modes, Types, ModuleInfo,
-			OutputsPrime)
-	->
-		Outputs = OutputsPrime
+find_list_of_output_args(Vars, Modes, Types, ModuleInfo, !:Outputs) :-
+    ( find_list_of_output_args_2(Vars, Modes, Types, ModuleInfo, !:Outputs) ->
+        true
 	;
-		error("find_list_of_output_args: list length mismatch")
+        unexpected(this_file, "find_list_of_output_args: list length mismatch")
 	).
 
 :- pred find_list_of_output_args_2(list(prog_var)::in, list(mode)::in,
@@ -222,7 +216,7 @@
 			ClonePredProcId = proc(ClonePredId, CloneProcId),
 			GoalExpr = call(ClonePredId, CloneProcId, Args,
 				Builtin, UnifyContext, SymName),
-			goal_info_add_feature(GoalInfo0, tailcall, GoalInfo),
+            goal_info_add_feature(tailcall, GoalInfo0, GoalInfo),
 			Goal = GoalExpr - GoalInfo,
 			!:FoundTailCall = yes
 		;
@@ -239,8 +233,8 @@
 		(
 			Unify0 = assign(ToVar, FromVar)
 		->
-			apply_tail_recursion_process_assign(
-				ApplyInfo ^ outputs, ToVar, FromVar, Outputs),
+            apply_tail_recursion_process_assign(ApplyInfo ^ outputs,
+                ToVar, FromVar, Outputs),
 			Continue = yes(Outputs)
 		;
 			Continue = no
@@ -253,8 +247,7 @@
 		Goal = GoalExpr - GoalInfo0
 	;
 		GoalExpr0 = disj(Goals0),
-		apply_tail_recursion_to_disj(Goals0, ApplyInfo, Goals,
-			!FoundTailCall),
+        apply_tail_recursion_to_disj(Goals0, ApplyInfo, Goals, !FoundTailCall),
 		GoalExpr = disj(Goals),
 		Goal = GoalExpr - GoalInfo0,
 		Continue = no
@@ -288,7 +281,7 @@
 		Continue = no
 	;
 		GoalExpr0 = shorthand(_),
-		error("shorthand in apply_tail_recursion_to_goal")
+        unexpected(this_file, "shorthand in apply_tail_recursion_to_goal")
 	).
 
 :- pred apply_tail_recursion_process_assign(list(prog_var)::in,
@@ -412,7 +405,7 @@
 		figure_out_rec_call_numbers(Goal1, !N, !TailCallSites)
 	;
 		GoalExpr = shorthand(_),
-		error("shorthand in apply_tail_recursion_to_goal")
+        unexpected(this_file, "shorthand in apply_tail_recursion_to_goal")
 	).
 
 :- pred figure_out_rec_call_numbers_in_goal_list(list(hlds_goal)::in,
@@ -458,7 +451,8 @@
 		Goal0 = foreign_proc(_, _, _, _, _, Impl) - _,
 		Impl = nondet(_, _, _, _, _, _, _, _, _)
 	->
-		error("deep profiling is incompatible with nondet foreign code")
+        unexpected(this_file,
+            "deep profiling is incompatible with nondet foreign code")
 	;
 		% We don't want to transform the procedures for
 		% managing the deep profiling call graph, or we'd get
@@ -514,8 +508,8 @@
 
 %-----------------------------------------------------------------------------%
 
-:- type deep_info --->
-	deep_info(
+:- type deep_info
+    --->    deep_info(
 		module_info		:: module_info,
 		pred_proc_id		:: pred_proc_id,
 		current_csd		:: prog_var,
@@ -533,28 +527,26 @@
 transform_det_proc(ModuleInfo, PredProcId, !ProcInfo) :-
 	proc_info_goal(!.ProcInfo, Goal0),
 	Goal0 = _ - GoalInfo0,
-	proc_info_varset(!.ProcInfo, Vars0),
-	proc_info_vartypes(!.ProcInfo, VarTypes0),
+    some [!VarSet, !VarTypes] (
+        proc_info_varset(!.ProcInfo, !:VarSet),
+        proc_info_vartypes(!.ProcInfo, !:VarTypes),
 	CPointerType = c_pointer_type,
-	varset__new_named_var(Vars0, "TopCSD", TopCSD, Vars1),
-	map__set(VarTypes0, TopCSD, CPointerType, VarTypes1),
-	varset__new_named_var(Vars1, "MiddleCSD", MiddleCSD, Vars2),
-	map__set(VarTypes1, MiddleCSD, CPointerType, VarTypes2),
-	varset__new_named_var(Vars2, "ProcStaticLayout", ProcStaticVar, Vars3),
-	map__set(VarTypes2, ProcStaticVar, CPointerType, VarTypes3),
+        svvarset__new_named_var("TopCSD", TopCSD, !VarSet),
+        svvarset__new_named_var("MiddleCSD", MiddleCSD, !VarSet),
+        svvarset__new_named_var("ProcStaticLayout", ProcStaticVar, !VarSet),
+        svmap__set(TopCSD, CPointerType, !VarTypes),
+        svmap__set(MiddleCSD, CPointerType, !VarTypes),
+        svmap__set(ProcStaticVar, CPointerType, !VarTypes),
 	module_info_globals(ModuleInfo, Globals),
 	globals__lookup_bool_option(Globals, use_activation_counts,
 		UseActivationCounts),
 	(
 		UseActivationCounts = no,
-		varset__new_named_var(Vars3, "ActivationPtr", ActivationPtr0,
-			Vars5),
-		map__set(VarTypes3, ActivationPtr0, CPointerType, VarTypes5),
+            svvarset__new_named_var("ActivationPtr", ActivationPtr0, !VarSet),
+            svmap__set(ActivationPtr0, CPointerType, !VarTypes),
 		MaybeActivationPtr = yes(ActivationPtr0)
 	;
 		UseActivationCounts = yes,
-		Vars5 = Vars3,
-		VarTypes5 = VarTypes3,
 		MaybeActivationPtr = no
 	),
 	ExcpVars = hlds_deep_excp_vars(TopCSD, MiddleCSD, MaybeActivationPtr),
@@ -565,8 +557,9 @@
 	proc_info_get_maybe_deep_profile_info(!.ProcInfo, MaybeDeepProfInfo),
 	extract_deep_rec_info(MaybeDeepProfInfo, MaybeRecInfo),
 	DeepInfo0 = deep_info(ModuleInfo, PredProcId, MiddleCSD,
-		counter__init(0), [], Vars5, VarTypes5,
-		FileName, MaybeRecInfo),
+            counter__init(0), [], !.VarSet, !.VarTypes,
+            FileName, MaybeRecInfo)
+    ),
 
 	transform_goal([], Goal0, TransformedGoal, _, DeepInfo0, DeepInfo),
 
@@ -595,8 +588,8 @@
 		generate_call(ModuleInfo, "det_call_port_code_sr", 4,
 			[ProcStaticVar, TopCSD, MiddleCSD, ActivationPtr1],
 			[TopCSD, MiddleCSD, ActivationPtr1], CallPortCode0),
-		goal_add_feature(CallPortCode0, save_deep_excp_vars,
-			CallPortCode),
+        goal_add_feature(save_deep_excp_vars,
+            CallPortCode0, CallPortCode),
 		generate_call(ModuleInfo, "det_exit_port_code_sr", 3,
 			[TopCSD, MiddleCSD, ActivationPtr1], [], ExitPortCode)
 	;
@@ -604,8 +597,8 @@
 		generate_call(ModuleInfo, "det_call_port_code_ac", 3,
 			[ProcStaticVar, TopCSD, MiddleCSD],
 			[TopCSD, MiddleCSD], CallPortCode0),
-		goal_add_feature(CallPortCode0, save_deep_excp_vars,
-			CallPortCode),
+        goal_add_feature(save_deep_excp_vars,
+            CallPortCode0, CallPortCode),
 		generate_call(ModuleInfo, "det_exit_port_code_ac", 2,
 			[TopCSD, MiddleCSD], [], ExitPortCode)
 	),
@@ -628,28 +621,26 @@
 transform_semi_proc(ModuleInfo, PredProcId, !ProcInfo) :-
 	proc_info_goal(!.ProcInfo, Goal0),
 	Goal0 = _ - GoalInfo0,
-	proc_info_varset(!.ProcInfo, Vars0),
-	proc_info_vartypes(!.ProcInfo, VarTypes0),
+    some [!VarSet, !VarTypes] (
+        proc_info_varset(!.ProcInfo, !:VarSet),
+        proc_info_vartypes(!.ProcInfo, !:VarTypes),
 	CPointerType = c_pointer_type,
-	varset__new_named_var(Vars0, "TopCSD", TopCSD, Vars1),
-	map__set(VarTypes0, TopCSD, CPointerType, VarTypes1),
-	varset__new_named_var(Vars1, "MiddleCSD", MiddleCSD, Vars2),
-	map__set(VarTypes1, MiddleCSD, CPointerType, VarTypes2),
-	varset__new_named_var(Vars2, "ProcStaticLayout", ProcStaticVar, Vars3),
-	map__set(VarTypes2, ProcStaticVar, CPointerType, VarTypes3),
+        svvarset__new_named_var("TopCSD", TopCSD, !VarSet),
+        svvarset__new_named_var("MiddleCSD", MiddleCSD, !VarSet),
+        svvarset__new_named_var("ProcStaticLayout", ProcStaticVar, !VarSet),
+        svmap__set(TopCSD, CPointerType, !VarTypes),
+        svmap__set(MiddleCSD, CPointerType, !VarTypes),
+        svmap__set(ProcStaticVar, CPointerType, !VarTypes),
 	module_info_globals(ModuleInfo, Globals),
 	globals__lookup_bool_option(Globals, use_activation_counts,
 		UseActivationCounts),
 	(
 		UseActivationCounts = no,
-		varset__new_named_var(Vars3, "ActivationPtr", ActivationPtr0,
-			Vars5),
-		map__set(VarTypes3, ActivationPtr0, CPointerType, VarTypes5),
+            svvarset__new_named_var("ActivationPtr", ActivationPtr0, !VarSet),
+            svmap__set(ActivationPtr0, CPointerType, !VarTypes),
 		MaybeActivationPtr = yes(ActivationPtr0)
 	;
 		UseActivationCounts = yes,
-		Vars5 = Vars3,
-		VarTypes5 = VarTypes3,
 		MaybeActivationPtr = no
 	),
 	ExcpVars = hlds_deep_excp_vars(TopCSD, MiddleCSD, MaybeActivationPtr),
@@ -660,8 +651,9 @@
 	proc_info_get_maybe_deep_profile_info(!.ProcInfo, MaybeDeepProfInfo),
 	extract_deep_rec_info(MaybeDeepProfInfo, MaybeRecInfo),
 	DeepInfo0 = deep_info(ModuleInfo, PredProcId, MiddleCSD,
-		counter__init(0), [], Vars5, VarTypes5,
-		FileName, MaybeRecInfo),
+            counter__init(0), [], !.VarSet, !.VarTypes,
+            FileName, MaybeRecInfo)
+    ),
 
 	transform_goal([], Goal0, TransformedGoal, _, DeepInfo0, DeepInfo),
 
@@ -690,8 +682,8 @@
 		generate_call(ModuleInfo, "semi_call_port_code_sr", 4,
 			[ProcStaticVar, TopCSD, MiddleCSD, ActivationPtr1],
 			[TopCSD, MiddleCSD, ActivationPtr1], CallPortCode0),
-		goal_add_feature(CallPortCode0, save_deep_excp_vars,
-			CallPortCode),
+        goal_add_feature(save_deep_excp_vars,
+            CallPortCode0, CallPortCode),
 		generate_call(ModuleInfo, "semi_exit_port_code_sr", 3,
 			[TopCSD, MiddleCSD, ActivationPtr1], [], ExitPortCode),
 		generate_call(ModuleInfo, "semi_fail_port_code_sr", 3,
@@ -703,8 +695,8 @@
 		generate_call(ModuleInfo, "semi_call_port_code_ac", 3,
 			[ProcStaticVar, TopCSD, MiddleCSD],
 			[TopCSD, MiddleCSD], CallPortCode0),
-		goal_add_feature(CallPortCode0, save_deep_excp_vars,
-			CallPortCode),
+        goal_add_feature(save_deep_excp_vars,
+            CallPortCode0, CallPortCode),
 		generate_call(ModuleInfo, "semi_exit_port_code_ac", 2,
 			[TopCSD, MiddleCSD], [], ExitPortCode),
 		generate_call(ModuleInfo, "semi_fail_port_code_ac", 2,
@@ -738,36 +730,33 @@
 transform_non_proc(ModuleInfo, PredProcId, !ProcInfo) :-
 	proc_info_goal(!.ProcInfo, Goal0),
 	Goal0 = _ - GoalInfo0,
-	proc_info_varset(!.ProcInfo, Vars0),
-	proc_info_vartypes(!.ProcInfo, VarTypes0),
+    some [!VarSet, !VarTypes] (
+        proc_info_varset(!.ProcInfo, !:VarSet),
+        proc_info_vartypes(!.ProcInfo, !:VarTypes),
 	CPointerType = c_pointer_type,
-	varset__new_named_var(Vars0, "TopCSD", TopCSD, Vars1),
-	map__set(VarTypes0, TopCSD, CPointerType, VarTypes1),
-	varset__new_named_var(Vars1, "MiddleCSD", MiddleCSD, Vars2),
-	map__set(VarTypes1, MiddleCSD, CPointerType, VarTypes2),
-	varset__new_named_var(Vars2, "ProcStaticLayout", ProcStaticVar, Vars3),
-	map__set(VarTypes2, ProcStaticVar, CPointerType, VarTypes3),
+        svvarset__new_named_var("TopCSD", TopCSD, !VarSet),
+        svvarset__new_named_var("MiddleCSD", MiddleCSD, !VarSet),
+        svvarset__new_named_var("ProcStaticLayout", ProcStaticVar, !VarSet),
+        svmap__set(TopCSD, CPointerType, !VarTypes),
+        svmap__set(MiddleCSD, CPointerType, !VarTypes),
+        svmap__set(ProcStaticVar, CPointerType, !VarTypes),
 	module_info_globals(ModuleInfo, Globals),
 	globals__lookup_bool_option(Globals, use_activation_counts,
 		UseActivationCounts),
 	(
 		UseActivationCounts = no,
-		varset__new_named_var(Vars3, "OldOutermost",
-			OldOutermostProcDyn0, Vars4),
-		map__set(VarTypes3, OldOutermostProcDyn0, CPointerType,
-			VarTypes4),
+            svvarset__new_named_var("OldOutermost", OldOutermostProcDyn0,
+                !VarSet),
+            svmap__set(OldOutermostProcDyn0, CPointerType, !VarTypes),
 		MaybeOldActivationPtr = yes(OldOutermostProcDyn0)
 	;
 		UseActivationCounts = yes,
-		Vars4 = Vars3,
-		VarTypes4 = VarTypes3,
 		MaybeOldActivationPtr = no
 	),
 	ExcpVars = hlds_deep_excp_vars(TopCSD, MiddleCSD,
 		MaybeOldActivationPtr),
-	varset__new_named_var(Vars4, "NewOutermost", NewOutermostProcDyn,
-		Vars5),
-	map__set(VarTypes4, NewOutermostProcDyn, CPointerType, VarTypes5),
+        svvarset__new_named_var("NewOutermost", NewOutermostProcDyn, !VarSet),
+        svmap__set(NewOutermostProcDyn, CPointerType, !VarTypes),
 	proc_info_context(!.ProcInfo, Context),
 	FileName = term__context_file(Context),
 	LineNumber = term__context_line(Context),
@@ -775,8 +764,8 @@
 	proc_info_get_maybe_deep_profile_info(!.ProcInfo, MaybeDeepProfInfo),
 	extract_deep_rec_info(MaybeDeepProfInfo, MaybeRecInfo),
 	DeepInfo0 = deep_info(ModuleInfo, PredProcId, MiddleCSD,
-		counter__init(0), [], Vars5, VarTypes5,
-		FileName, MaybeRecInfo),
+            counter__init(0), [], !.VarSet, !.VarTypes, FileName, MaybeRecInfo)
+    ),
 
 	transform_goal([], Goal0, TransformedGoal, _, DeepInfo0, DeepInfo),
 
@@ -786,8 +775,8 @@
 
 	PredProcId = proc(PredId, ProcId),
 	IsInInterface = is_proc_in_interface(ModuleInfo, PredId, ProcId),
-	ProcStatic = hlds_proc_static(FileName, LineNumber,
-		IsInInterface, CallSites),
+    ProcStatic = hlds_proc_static(FileName, LineNumber, IsInInterface,
+        CallSites),
 	ShroudedPredProcId = shroud_pred_proc_id(proc(PredId, ProcId)),
 	ProcStaticConsId = deep_profiling_proc_layout(ShroudedPredProcId),
 	generate_unify(ProcStaticConsId, ProcStaticVar, BindProcStaticVarGoal),
@@ -797,11 +786,10 @@
 		generate_call(ModuleInfo, "non_call_port_code_sr", 5,
 			[ProcStaticVar, TopCSD, MiddleCSD,
 			OldOutermostProcDyn2, NewOutermostProcDyn],
-			[TopCSD, MiddleCSD,
-				OldOutermostProcDyn2, NewOutermostProcDyn],
+            [TopCSD, MiddleCSD, OldOutermostProcDyn2, NewOutermostProcDyn],
 			CallPortCode0),
-		goal_add_feature(CallPortCode0, save_deep_excp_vars,
-			CallPortCode),
+        goal_add_feature(save_deep_excp_vars,
+            CallPortCode0, CallPortCode),
 		generate_call(ModuleInfo, "non_exit_port_code_sr", 3,
 			[TopCSD, MiddleCSD, OldOutermostProcDyn2], [],
 			ExitPortCode),
@@ -811,16 +799,15 @@
 		generate_call(ModuleInfo, "non_redo_port_code_sr", 2,
 			[MiddleCSD, NewOutermostProcDyn], no,
 			failure, RedoPortCode0),
-		NewNonlocals = list_to_set(
-			[TopCSD, MiddleCSD, OldOutermostProcDyn2])
+        NewNonlocals = list_to_set([TopCSD, MiddleCSD, OldOutermostProcDyn2])
 	;
 		MaybeOldActivationPtr = no,
 		generate_call(ModuleInfo, "non_call_port_code_ac", 4,
 			[ProcStaticVar, TopCSD, MiddleCSD, NewOutermostProcDyn],
 			[TopCSD, MiddleCSD, NewOutermostProcDyn],
 			CallPortCode0),
-		goal_add_feature(CallPortCode0, save_deep_excp_vars,
-			CallPortCode),
+        goal_add_feature(save_deep_excp_vars,
+            CallPortCode0, CallPortCode),
 		generate_call(ModuleInfo, "non_exit_port_code_ac", 2,
 			[TopCSD, MiddleCSD], [], ExitPortCode),
 		generate_call(ModuleInfo, "non_fail_port_code_ac", 2,
@@ -832,8 +819,8 @@
 	),
 
 	RedoPortCode0 = RedoPortExpr - RedoPortGoalInfo0,
-	goal_info_add_feature(RedoPortGoalInfo0,
-		preserve_backtrack_into, RedoPortGoalInfo),
+    goal_info_add_feature(preserve_backtrack_into,
+        RedoPortGoalInfo0, RedoPortGoalInfo),
 	RedoPortCode = RedoPortExpr - RedoPortGoalInfo,
 
 	% Even though the procedure has a model_non interface determinism,
@@ -845,7 +832,7 @@
 	goal_info_get_determinism(GoalInfo0, Detism0),
 	determinism_components(Detism0, CanFail, _),
 	determinism_components(Detism, CanFail, at_most_many),
-	goal_info_set_determinism(GoalInfo0, Detism, GoalInfo1),
+    goal_info_set_determinism(Detism, GoalInfo0, GoalInfo1),
 
 	ExitRedoNonLocals = set__union(NewNonlocals,
 		list_to_set([NewOutermostProcDyn])),
@@ -881,11 +868,11 @@
 transform_inner_proc(ModuleInfo, PredProcId, !ProcInfo) :-
 	proc_info_goal(!.ProcInfo, Goal0),
 	Goal0 = _ - GoalInfo0,
-	proc_info_varset(!.ProcInfo, Vars0),
+    proc_info_varset(!.ProcInfo, VarSet0),
 	proc_info_vartypes(!.ProcInfo, VarTypes0),
 	CPointerType = c_pointer_type,
 	% MiddleCSD should be unused
-	varset__new_named_var(Vars0, "MiddleCSD", MiddleCSD, Vars1),
+    varset__new_named_var(VarSet0, "MiddleCSD", MiddleCSD, VarSet1),
 	map__set(VarTypes0, MiddleCSD, CPointerType, VarTypes1),
 
 	goal_info_get_context(GoalInfo0, Context),
@@ -894,15 +881,15 @@
 	proc_info_get_maybe_deep_profile_info(!.ProcInfo, MaybeDeepProfInfo),
 	extract_deep_rec_info(MaybeDeepProfInfo, MaybeRecInfo),
 	DeepInfo0 = deep_info(ModuleInfo, PredProcId, MiddleCSD,
-		counter__init(0), [], Vars1, VarTypes1,
+        counter__init(0), [], VarSet1, VarTypes1,
 		FileName, MaybeRecInfo),
 
 	transform_goal([], Goal0, TransformedGoal, _, DeepInfo0, DeepInfo),
 
-	Vars = DeepInfo ^ vars,
+    VarSet = DeepInfo ^ vars,
 	VarTypes = DeepInfo ^ var_types,
 
-	proc_info_set_varset(Vars, !ProcInfo),
+    proc_info_set_varset(VarSet, !ProcInfo),
 	proc_info_set_vartypes(VarTypes, !ProcInfo),
 	proc_info_set_goal(TransformedGoal, !ProcInfo).
 
@@ -1014,7 +1001,8 @@
 	add_impurity_if_needed(AddedImpurity, GoalInfo0, GoalInfo).
 
 transform_goal(_, shorthand(_) - _, _, _, !DeepInfo) :-
-	error("transform_goal/6: shorthand should have gone by now").
+    unexpected(this_file,
+        "transform_goal/6: shorthand should have gone by now").
 
 transform_goal(Path, Goal0 - GoalInfo0, GoalAndInfo, AddedImpurity,
 		!DeepInfo) :-
@@ -1056,7 +1044,7 @@
 		AddedImpurity = no
 	;
 		GenericCall = aditi_builtin(_, _),
-		error("deep_profiling__transform_call: aditi_builtin")
+        unexpected(this_file, "deep_profiling__transform_call: aditi_builtin")
 	).
 
 :- pred transform_conj(int::in, goal_path::in,
@@ -1106,7 +1094,7 @@
 	Goal0 = GoalExpr - GoalInfo0,
 	ModuleInfo = !.DeepInfo ^ module_info,
 	goal_info_get_features(GoalInfo0, GoalFeatures),
-	goal_info_remove_feature(GoalInfo0, tailcall, GoalInfo1),
+    goal_info_remove_feature(tailcall, GoalInfo0, GoalInfo1),
 	make_impure(GoalInfo1, GoalInfo),
 
 	% We need to make the call itself impure. If we didn't do so,
@@ -1121,11 +1109,11 @@
 
 	SiteNumCounter0 = !.DeepInfo ^ site_num_counter,
 	counter__allocate(SiteNum, SiteNumCounter0, SiteNumCounter),
-	varset__new_named_var(!.DeepInfo ^ vars, "SiteNum", SiteNumVar, Vars1),
+    varset__new_named_var(!.DeepInfo ^ vars, "SiteNum", SiteNumVar, VarSet1),
 	IntType = int_type,
 	map__set(!.DeepInfo ^ var_types, SiteNumVar, IntType, VarTypes1),
 	generate_unify(int_const(SiteNum), SiteNumVar, SiteNumVarGoal),
-	!:DeepInfo = (((!.DeepInfo ^ vars := Vars1)
+    !:DeepInfo = (((!.DeepInfo ^ vars := VarSet1)
 		^ var_types := VarTypes1)
 		^ site_num_counter := SiteNumCounter),
 
@@ -1188,12 +1176,12 @@
 			Generic = class_method(TypeClassInfoVar, MethodNum,
 				_, _),
 			varset__new_named_var(!.DeepInfo ^ vars, "MethodNum",
-				MethodNumVar, Vars2),
+                MethodNumVar, VarSet2),
 			map__set(!.DeepInfo ^ var_types, MethodNumVar, IntType,
 				VarTypes2),
 			generate_unify(int_const(MethodNum), MethodNumVar,
 				MethodNumVarGoal),
-			!:DeepInfo = ((!.DeepInfo ^ vars := Vars2)
+            !:DeepInfo = ((!.DeepInfo ^ vars := VarSet2)
 				^ var_types := VarTypes2),
 			generate_call(ModuleInfo, "prepare_for_method_call", 3,
 				[SiteNumVar, TypeClassInfoVar, MethodNumVar],
@@ -1206,10 +1194,10 @@
 			CallSite = method_call(FileName, LineNumber, GoalPath)
 		;
 			Generic = cast(_),
-			error("deep_profiling__wrap_call: cast")
+            unexpected(this_file, "deep_profiling__wrap_call: cast")
 		;
 			Generic = aditi_builtin(_, _),
-			error("deep_profiling__wrap_call: aditi_builtin")
+            unexpected(this_file, "deep_profiling__wrap_call: aditi_builtin")
 		),
 		goal_info_get_code_model(GoalInfo0, GoalCodeModel),
 		module_info_globals(ModuleInfo, Globals),
@@ -1246,8 +1234,8 @@
 				SaveRestoreVars, !DeepInfo)
 		;
 			VisSCC = [_, _ | _],
-			error("wrap_call: multi-procedure SCCs " ++
-				"not yet implemented")
+            unexpected(this_file,
+                "wrap_call: multi-procedure SCCs not yet implemented")
 		),
 
 		goal_info_get_code_model(GoalInfo0, CodeModel),
@@ -1262,12 +1250,10 @@
 
 			ExtraVars = list_to_set([MiddleCSD | SaveRestoreVars]),
 			WrappedGoalGoalInfo =
-				goal_info_add_nonlocals_make_impure(GoalInfo,
-					ExtraVars),
+                goal_info_add_nonlocals_make_impure(GoalInfo, ExtraVars),
 
 			ReturnFailsGoalInfo =
-				impure_unreachable_init_goal_info(ExtraVars,
-					failure),
+                impure_unreachable_init_goal_info(ExtraVars, failure),
 
 			FailGoalInfo = fail_goal_info,
 			FailGoal = disj([]) - FailGoalInfo,
@@ -1291,22 +1277,18 @@
 			Goal = conj(Goals) - GoalInfo
 		)
 	;
-		Goal = conj([
-			SiteNumVarGoal,
-			PrepareGoal,
-			Goal2
-		]) - GoalInfo
+        Goal = conj([SiteNumVarGoal, PrepareGoal, Goal2]) - GoalInfo
 	).
 
 :- pred transform_higher_order_call(globals::in, code_model::in,
 	hlds_goal::in, hlds_goal::out, deep_info::in, deep_info::out) is det.
 
 transform_higher_order_call(Globals, CodeModel, Goal0, Goal, !DeepInfo) :-
-	Vars0 = !.DeepInfo ^ vars,
+    VarSet0 = !.DeepInfo ^ vars,
 	VarTypes0 = !.DeepInfo ^ var_types,
 
 	CPointerType = c_pointer_type,
-	varset__new_named_var(Vars0, "SavedPtr", SavedPtrVar, Vars1),
+    varset__new_named_var(VarSet0, "SavedPtr", SavedPtrVar, VarSet1),
 	map__set(VarTypes0, SavedPtrVar, CPointerType, VarTypes1),
 
 	globals__lookup_bool_option(Globals, use_activation_counts,
@@ -1315,11 +1297,10 @@
 		UseActivationCounts = yes,
 
 		IntType = int_type,
-		varset__new_named_var(Vars1, "SavedCounter", SavedCountVar,
-			Vars),
+        varset__new_named_var(VarSet1, "SavedCounter", SavedCountVar, VarSet),
 		map__set(VarTypes1, SavedCountVar, IntType, VarTypes),
 
-		!:DeepInfo = !.DeepInfo ^ vars := Vars,
+        !:DeepInfo = !.DeepInfo ^ vars := VarSet,
 		!:DeepInfo = !.DeepInfo ^ var_types := VarTypes,
 		ExtraNonLocals = set__list_to_set(
 			[SavedCountVar, SavedPtrVar]),
@@ -1337,7 +1318,7 @@
 	;
 		UseActivationCounts = no,
 
-		!:DeepInfo = !.DeepInfo ^ vars := Vars1,
+        !:DeepInfo = !.DeepInfo ^ vars := VarSet1,
 		!:DeepInfo = !.DeepInfo ^ var_types := VarTypes1,
 		ExtraNonLocals = set__list_to_set([SavedPtrVar]),
 
@@ -1358,8 +1339,7 @@
 
 	% XXX We should build up NoBindExtGoalInfo from scratch.
 	instmap_delta_init_reachable(EmptyDelta),
-	goal_info_set_instmap_delta(ExtGoalInfo, EmptyDelta,
-		NoBindExtGoalInfo),
+    goal_info_set_instmap_delta(EmptyDelta, ExtGoalInfo, NoBindExtGoalInfo),
 
 	FailGoalInfo = fail_goal_info,
 	FailGoal = disj([]) - FailGoalInfo,
@@ -1425,7 +1405,7 @@
 
 	SiteNumCounter0 = !.DeepInfo ^ site_num_counter,
 	counter__allocate(SiteNum, SiteNumCounter0, SiteNumCounter),
-	varset__new_named_var(!.DeepInfo ^ vars, "SiteNum", SiteNumVar, Vars),
+    varset__new_named_var(!.DeepInfo ^ vars, "SiteNum", SiteNumVar, VarSet),
 	map__set(!.DeepInfo ^ var_types, SiteNumVar, int_type, VarTypes),
 	generate_unify(int_const(SiteNum), SiteNumVar, SiteNumVarGoal),
 
@@ -1440,10 +1420,11 @@
 
 	make_impure(GoalInfo0, GoalInfo),
 	Goal = conj([SiteNumVarGoal, PrepareGoal, Goal0]) - GoalInfo,
-	!:DeepInfo = ((((!.DeepInfo ^ site_num_counter := SiteNumCounter)
-		^ vars := Vars)
-		^ var_types := VarTypes)
-		^ call_sites := !.DeepInfo ^ call_sites ++ [CallSite]).
+    !:DeepInfo = !.DeepInfo ^ site_num_counter := SiteNumCounter,
+    !:DeepInfo = !.DeepInfo ^ vars := VarSet,
+    !:DeepInfo = !.DeepInfo ^ var_types := VarTypes,
+    !:DeepInfo = !.DeepInfo ^ call_sites :=
+        !.DeepInfo ^ call_sites ++ [CallSite].
 
 :- pred compress_filename(deep_info::in, string::in, string::out) is det.
 
@@ -1455,13 +1436,15 @@
 	).
 
 :- type call_class
-			% For normal first order calls
 	--->	normal(pred_proc_id)
+            % For normal first order calls
+
+    ;       special(pred_proc_id, prog_var)
 			% For calls to unify/2, compare/3 and
 			% compare_representation/3
-	;	special(pred_proc_id, prog_var)
-			% For higher order and typeclass method calls
+
 	;	generic(generic_call).
+            % For higher order and typeclass method calls
 
 :- pred classify_call(module_info::in, hlds_goal_expr::in,
 	call_class::out) is det.
@@ -1496,7 +1479,7 @@
 	; Expr = generic_call(Generic, _, _, _) ->
 		Class = generic(Generic)
 	;
-		error("unexpected goal type in classify_call/2")
+        unexpected(this_file, "unexpected goal type in classify_call/2")
 	).
 
 :- func compute_type_subst(hlds_goal_expr, deep_info) = string.
@@ -1507,6 +1490,7 @@
 	% The maximum value of N for which save_recursion_depth_N,
 	% restore_recursion_depth_exit_N and restore_recursion_depth_fail_N
 	% exist in library/profiling_builtin.m.
+    %
 :- func max_save_restore_vector_size = int.
 
 max_save_restore_vector_size = 9.
@@ -1546,8 +1530,7 @@
 		!DeepInfo),
 	list__condense([CallVars1, ExitVars1, FailVars1], ExtraVars1),
 
-	CallPredName = string__format("save_recursion_depth_%d",
-		[i(Length)]),
+    CallPredName = string__format("save_recursion_depth_%d", [i(Length)]),
 	ExitPredName = string__format("restore_recursion_depth_exit_%d",
 		[i(Length)]),
 	FailPredName = string__format("restore_recursion_depth_fail_%d",
@@ -1572,13 +1555,14 @@
 	deep_info::in, deep_info::out) is det.
 
 generate_depth_var(CSN, DepthVar, !DeepInfo) :-
-	Vars0 = !.DeepInfo ^ vars,
+    VarSet0 = !.DeepInfo ^ vars,
 	VarTypes0 = !.DeepInfo ^ var_types,
 	IntType = int_type,
 	VarName = string__format("Depth%d", [i(CSN)]),
-	varset__new_named_var(Vars0, VarName, DepthVar, Vars),
+    varset__new_named_var(VarSet0, VarName, DepthVar, VarSet),
 	map__set(VarTypes0, DepthVar, IntType, VarTypes),
-	!:DeepInfo = (!.DeepInfo ^ vars := Vars) ^ var_types := VarTypes.
+    !:DeepInfo = !.DeepInfo ^ vars := VarSet,
+    !:DeepInfo = !.DeepInfo ^ var_types := VarTypes.
 
 :- pred generate_csn_vector(int::in, list(int)::in, list(prog_var)::out,
 	list(hlds_goal)::out, prog_var::out,
@@ -1607,15 +1591,16 @@
 	prog_var::out, hlds_goal::out, deep_info::in, deep_info::out) is det.
 
 generate_csn_vector_cell(Length, CSNVars, CellVar, CellGoal, !DeepInfo) :-
-	Vars0 = !.DeepInfo ^ vars,
+    VarSet0 = !.DeepInfo ^ vars,
 	VarTypes0 = !.DeepInfo ^ var_types,
-	varset__new_named_var(Vars0, "CSNCell", CellVar, Vars),
+    varset__new_named_var(VarSet0, "CSNCell", CellVar, VarSet),
 	mercury_profiling_builtin_module(ProfilingBuiltin),
 	CellTypeName = string__format("call_site_nums_%d", [i(Length)]),
 	CellTypeId = qualified(ProfilingBuiltin, CellTypeName) - Length,
 	construct_type(CellTypeId, [], CellType),
 	map__set(VarTypes0, CellVar, CellType, VarTypes),
-	!:DeepInfo = (!.DeepInfo ^ vars := Vars) ^ var_types := VarTypes,
+    !:DeepInfo = !.DeepInfo ^ vars := VarSet,
+    !:DeepInfo = !.DeepInfo ^ var_types := VarTypes,
 	ConsId = cons(qualified(ProfilingBuiltin, CellTypeName), Length),
 	generate_cell_unify(Length, ConsId, CSNVars, CellVar, CellGoal).
 
@@ -1623,12 +1608,13 @@
 	pair(prog_var, hlds_goal)::out, deep_info::in, deep_info::out) is det.
 
 generate_single_csn_unify(CSN, CSNVar - UnifyGoal, !DeepInfo) :-
-	Vars0 = !.DeepInfo ^ vars,
+    VarSet0 = !.DeepInfo ^ vars,
 	VarTypes0 = !.DeepInfo ^ var_types,
 	VarName = string__format("CSN%d", [i(CSN)]),
-	varset__new_named_var(Vars0, VarName, CSNVar, Vars),
+    varset__new_named_var(VarSet0, VarName, CSNVar, VarSet),
 	map__set(VarTypes0, CSNVar, int_type, VarTypes),
-	!:DeepInfo = (!.DeepInfo ^ vars := Vars) ^ var_types := VarTypes,
+    !:DeepInfo = !.DeepInfo ^ vars := VarSet,
+    !:DeepInfo = !.DeepInfo ^ var_types := VarTypes,
 	generate_unify(int_const(CSN), CSNVar, UnifyGoal).
 
 :- pred generate_call(module_info::in, string::in, int::in,
@@ -1665,8 +1651,7 @@
 generate_unify(ConsId, Var, Goal) :-
 	Ground = ground(shared, none),
 	NonLocals = set__make_singleton_set(Var),
-	instmap_delta_from_assoc_list([Var - ground(shared, none)],
-		InstMapDelta),
+    instmap_delta_from_assoc_list([Var - ground(shared, none)], InstMapDelta),
 	Determinism = det,
 	goal_info_init(NonLocals, InstMapDelta, Determinism, pure, GoalInfo),
 	Goal = unify(Var, functor(ConsId, no, []),
@@ -1707,7 +1692,7 @@
 	->
 		(
 			PredIds = [],
-			error("get_deep_profile_builtin_ppid: no pred_id")
+            unexpected(this_file, "get_deep_profile_builtin_ppid: no pred_id")
 		;
 			PredIds = [PredId],
 			predicate_table_get_preds(PredTable, Preds),
@@ -1715,24 +1700,24 @@
 			ProcIds = pred_info_procids(PredInfo),
 			(
 				ProcIds = [],
-				error("get_deep_profile_builtin_ppid: " ++
-					"no proc_id")
+                unexpected(this_file,
+                    "get_deep_profile_builtin_ppid: no proc_id")
 			;
 				ProcIds = [ProcId]
 			;
 				ProcIds = [_, _ | _],
-				error("get_deep_profile_builtin_ppid: " ++
-					"proc_id not unique")
+                unexpected(this_file,
+                    "get_deep_profile_builtin_ppid: proc_id not unique")
 			)
 		;
 			PredIds = [_, _ | _],
-			error("get_deep_profile_builtin_ppid: " ++
-				"pred_id not unique")
+            unexpected(this_file,
+                "get_deep_profile_builtin_ppid: pred_id not unique")
 		)
 	;
 		format("couldn't find pred_id for `%s'/%d",
 			[s(Name), i(Arity)], Msg),
-		error(Msg)
+        unexpected(this_file, Msg)
 	).
 
 %-----------------------------------------------------------------------------%
@@ -1741,9 +1726,8 @@
 	= hlds_goal_info.
 
 impure_init_goal_info(NonLocals, InstMapDelta, Determinism) = GoalInfo :-
-	goal_info_init(NonLocals, InstMapDelta, Determinism, impure,
-		GoalInfo0),
-	goal_info_add_feature(GoalInfo0, not_impure_for_determinism, GoalInfo).
+    goal_info_init(NonLocals, InstMapDelta, Determinism, impure, GoalInfo0),
+    goal_info_add_feature(not_impure_for_determinism, GoalInfo0, GoalInfo).
 
 :- func impure_reachable_init_goal_info(set(prog_var), determinism)
 	= hlds_goal_info.
@@ -1757,18 +1741,17 @@
 
 impure_unreachable_init_goal_info(NonLocals, Determinism) = GoalInfo :-
 	instmap_delta_init_unreachable(InstMapDelta),
-	goal_info_init(NonLocals, InstMapDelta, Determinism, impure,
-		GoalInfo0),
-	goal_info_add_feature(GoalInfo0, not_impure_for_determinism, GoalInfo).
+    goal_info_init(NonLocals, InstMapDelta, Determinism, impure, GoalInfo0),
+    goal_info_add_feature(not_impure_for_determinism, GoalInfo0, GoalInfo).
 
 :- func goal_info_add_nonlocals_make_impure(hlds_goal_info, set(prog_var))
 	= hlds_goal_info.
 
-goal_info_add_nonlocals_make_impure(GoalInfo0, NewNonLocals) = GoalInfo :-
-	goal_info_get_nonlocals(GoalInfo0, NonLocals0),
+goal_info_add_nonlocals_make_impure(!.GoalInfo, NewNonLocals) = !:GoalInfo :-
+    goal_info_get_nonlocals(!.GoalInfo, NonLocals0),
 	NonLocals = set__union(NonLocals0, NewNonLocals),
-	goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo1),
-	make_impure(GoalInfo1, GoalInfo).
+    goal_info_set_nonlocals(NonLocals, !GoalInfo),
+    make_impure(!GoalInfo).
 
 :- func fail_goal_info = hlds_goal_info.
 
@@ -1778,14 +1761,14 @@
 
 :- pred make_impure(hlds_goal_info::in, hlds_goal_info::out) is det.
 
-make_impure(GoalInfo0, GoalInfo) :-
-	( goal_info_has_feature(GoalInfo0, (impure)) ->
+make_impure(!GoalInfo) :-
+    ( goal_info_has_feature(!.GoalInfo, (impure)) ->
 		% We don't add not_impure_for_determinism, since we want to
 		% keep the existing determinism.
-		GoalInfo = GoalInfo0
+        true
 	;
-		goal_info_add_features([impure, not_impure_for_determinism],
-			GoalInfo0, GoalInfo)
+        goal_info_add_feature(impure, !GoalInfo),
+        goal_info_add_feature(not_impure_for_determinism, !GoalInfo)
 	).
 
 :- pred add_impurity_if_needed(bool::in, hlds_goal_info::in,
@@ -1828,5 +1811,11 @@
 	),
 	MaybeDeepInfo = yes(DeepInfo),
 	proc_info_set_maybe_deep_profile_info(MaybeDeepInfo, !ProcInfo).
+
+%-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "deep_profiling.m".
 
 %-----------------------------------------------------------------------------%
Index: compiler/deforest.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/deforest.m,v
retrieving revision 1.49
diff -u -b -r1.49 deforest.m
--- compiler/deforest.m	22 Jul 2005 12:31:53 -0000	1.49
+++ compiler/deforest.m	28 Aug 2005 04:52:54 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1999-2005 University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -38,8 +40,8 @@
 
 :- import_module io.
 
-:- pred deforestation(module_info::in, module_info::out,
-	io::di, io::uo) is det.
+:- pred deforestation(module_info::in, module_info::out, io::di, io::uo)
+    is det.
 
 %-----------------------------------------------------------------------------%
 
@@ -65,6 +67,7 @@
 :- import_module libs__globals.
 :- import_module libs__options.
 :- import_module mdbcomp__prim_data.
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__prog_data.
 :- import_module parse_tree__prog_out.
 :- import_module parse_tree__prog_util.
@@ -93,9 +96,8 @@
 	proc_arg_info_init(ProcArgInfo0),
 	type_to_univ(ProcArgInfo0, UnivProcArgInfo0),
 
-	% Find out which arguments of each procedure are switched on
-	% at the top level or are constructed in a way which is
-	% possibly deforestable.
+    % Find out which arguments of each procedure are switched on at the top
+    % level or are constructed in a way which is possibly deforestable.
 	Task0 = update_module_cookie(deforest__get_branch_vars_proc,
 		UnivProcArgInfo0),
 	process_all_nonimported_procs(Task0, Task, !ModuleInfo, !IO),
@@ -105,7 +107,7 @@
 	->
 		ProcArgInfo = ProcArgInfo1
 	;
-		error("deforestation: passes_aux stuffed up")
+        unexpected(this_file, "deforestation: passes_aux stuffed up")
 	),
 
 	% We process the module bottom-up to make estimation of the
@@ -128,14 +130,12 @@
 		Constraints, !IO),
 	(
 		Constraints = yes,
-		Versions \= []
+        Versions = [_ | _]
 	->
 		% We can sometimes improve efficiency by rerunning determinism
-		% inference on the specialized versions after constraint
-		% propagation, because some nondet predicates will have
-		% become semidet.
-		list__foldl(reset_inferred_proc_determinism, Versions,
-			!ModuleInfo),
+        % inference on the specialized versions after constraint propagation,
+        % because some nondet predicates will have become semidet.
+        list__foldl(reset_inferred_proc_determinism, Versions, !ModuleInfo),
 		module_info_num_errors(!.ModuleInfo, Errors5),
 
 		disable_det_warnings(OptionsToRestore, !IO),
@@ -161,8 +161,7 @@
 		% so resetting the determinism would cause determinism errors.
 		true
 	;
-		proc_info_set_inferred_determinism(erroneous,
-			ProcInfo0, ProcInfo),
+        proc_info_set_inferred_determinism(erroneous, ProcInfo0, ProcInfo),
 		module_info_set_pred_proc_info(PredProcId, PredInfo, ProcInfo,
 			!ModuleInfo)
 	).
@@ -177,14 +176,13 @@
 	module_info::in, module_info::out) is det.
 
 deforest__get_branch_vars_proc(PredId, ProcId, ProcInfo, ProcInfo,
-		UnivProcArgInfo0, UnivProcArgInfo,
-		ModuleInfo0, ModuleInfo) :-
+        UnivProcArgInfo0, UnivProcArgInfo, !ModuleInfo) :-
 	( univ_to_type(UnivProcArgInfo0, ProcArgInfo0) ->
 		pd_util__get_branch_vars_proc(proc(PredId, ProcId), ProcInfo,
-			ProcArgInfo0, ProcArgInfo, ModuleInfo0, ModuleInfo),
+            ProcArgInfo0, ProcArgInfo, !ModuleInfo),
 		type_to_univ(ProcArgInfo, UnivProcArgInfo)
 	;
-		error("deforest__get_branch_vars_proc")
+        unexpected(this_file, "deforest__get_branch_vars_proc")
 	).
 
 :- pred deforest__proc(pred_proc_id::in, pd_info::in, pd_info::out,
@@ -197,46 +195,46 @@
 	pd_info::in, pd_info::out, io::di, io::uo) is det.
 
 deforest__proc(proc(PredId, ProcId), CostDelta, SizeDelta, !PDInfo, !IO) :-
-	pd_info_get_module_info(!.PDInfo, ModuleInfo0),
+    some [!ModuleInfo, !PredInfo, !ProcInfo, !Goal] (
+        pd_info_get_module_info(!.PDInfo, !:ModuleInfo),
 	write_proc_progress_message("% Deforesting ",
-		PredId, ProcId, ModuleInfo0, !IO),
-	module_info_pred_proc_info(ModuleInfo0, PredId, ProcId,
-		PredInfo0, ProcInfo0),
-	pd_info_init_unfold_info(proc(PredId, ProcId), PredInfo0, ProcInfo0,
+            PredId, ProcId, !.ModuleInfo, !IO),
+        module_info_pred_proc_info(!.ModuleInfo, PredId, ProcId,
+            !:PredInfo, !:ProcInfo),
+        pd_info_init_unfold_info(proc(PredId, ProcId), !.PredInfo, !.ProcInfo,
 		!PDInfo),
-	proc_info_goal(ProcInfo0, Goal0),
+        proc_info_goal(!.ProcInfo, !:Goal),
 
 	% Inlining may have created some opportunities for simplification.
 	globals__io_get_globals(Globals, !IO),
 	simplify__find_simplifications(no, Globals, Simplifications),
-	pd_util__simplify_goal(Simplifications, Goal0, Goal1, !PDInfo),
+        pd_util__simplify_goal(Simplifications, !Goal, !PDInfo),
 
-	pd_util__propagate_constraints(Goal1, Goal2, !PDInfo, !IO),
+        pd_util__propagate_constraints(!Goal, !PDInfo, !IO),
 
-	pd_debug__output_goal(!.PDInfo, "after constraints\n", Goal2, !IO),
-	deforest__goal(Goal2, Goal3, !PDInfo, !IO),
+        pd_debug__output_goal(!.PDInfo, "after constraints\n", !.Goal, !IO),
+        deforest__goal(!Goal, !PDInfo, !IO),
 
-	pd_info_get_proc_info(!.PDInfo, ProcInfo1),
-	proc_info_set_goal(Goal3, ProcInfo1, ProcInfo2),
+        pd_info_get_proc_info(!.PDInfo, !:ProcInfo),
+        proc_info_set_goal(!.Goal, !ProcInfo),
 	pd_info_get_changed(!.PDInfo, Changed),
 
 	(
 		Changed = yes,
-		pd_info_get_module_info(!.PDInfo, ModuleInfo2),
-		requantify_proc(ProcInfo2, ProcInfo3),
-		proc_info_goal(ProcInfo3, Goal4),
-		proc_info_get_initial_instmap(ProcInfo3,
-			ModuleInfo2, InstMap0),
-		proc_info_vartypes(ProcInfo3, VarTypes),
-		proc_info_inst_varset(ProcInfo3, InstVarSet),
-		recompute_instmap_delta(yes, Goal4, Goal, VarTypes,
-			InstVarSet, InstMap0, ModuleInfo2, ModuleInfo3),
-		pd_info_set_module_info(ModuleInfo3, !PDInfo),
+            pd_info_get_module_info(!.PDInfo, !:ModuleInfo),
+            requantify_proc(!ProcInfo),
+            proc_info_goal(!.ProcInfo, !:Goal),
+            proc_info_get_initial_instmap(!.ProcInfo, !.ModuleInfo, InstMap0),
+            proc_info_vartypes(!.ProcInfo, VarTypes),
+            proc_info_inst_varset(!.ProcInfo, InstVarSet),
+            recompute_instmap_delta(yes, !Goal, VarTypes,
+                InstVarSet, InstMap0, !ModuleInfo),
+            pd_info_set_module_info(!.ModuleInfo, !PDInfo),
 
-		pd_info_get_pred_info(!.PDInfo, PredInfo),
-		proc_info_set_goal(Goal, ProcInfo3, ProcInfo),
+            pd_info_get_pred_info(!.PDInfo, !:PredInfo),
+            proc_info_set_goal(!.Goal, !ProcInfo),
 		module_info_set_pred_proc_info(PredId, ProcId,
-			PredInfo, ProcInfo, ModuleInfo3, ModuleInfo4),
+                !.PredInfo, !.ProcInfo, !ModuleInfo),
 
 		pd_info_get_rerun_det(!.PDInfo, RerunDet),
 
@@ -246,64 +244,60 @@
 			% then we re-run determinism analysis. As with
 			% inlining.m, this avoids problems with inlining
 			% erroneous procedures.
-			det_infer_proc(PredId, ProcId, ModuleInfo4,
-				ModuleInfo5, Globals, _, _, _)
+                det_infer_proc(PredId, ProcId, !ModuleInfo, Globals, _, _, _)
 		;
-			RerunDet = no,
-			ModuleInfo5 = ModuleInfo4
+                RerunDet = no
 		),
 
 		% Recompute the branch_info for the procedure.
 		pd_info_get_proc_arg_info(!.PDInfo, ProcArgInfo0),
-		pd_util__get_branch_vars_proc(proc(PredId, ProcId), ProcInfo,
-			ProcArgInfo0, ProcArgInfo, ModuleInfo5, ModuleInfo6),
+            pd_util__get_branch_vars_proc(proc(PredId, ProcId), !.ProcInfo,
+                ProcArgInfo0, ProcArgInfo, !ModuleInfo),
 		pd_info_set_proc_arg_info(ProcArgInfo, !PDInfo),
-		pd_info_set_module_info(ModuleInfo6, !PDInfo)
+            pd_info_set_module_info(!.ModuleInfo, !PDInfo)
 	;
 		Changed = no,
-		pd_info_get_module_info(!.PDInfo, ModuleInfo2),
-		pd_info_get_pred_info(!.PDInfo, PredInfo),
+            pd_info_get_module_info(!.PDInfo, !:ModuleInfo),
+            pd_info_get_pred_info(!.PDInfo, !:PredInfo),
 		module_info_set_pred_proc_info(PredId, ProcId,
-			PredInfo, ProcInfo2, ModuleInfo2, ModuleInfo3),
-		pd_info_set_module_info(ModuleInfo3, !PDInfo)
+                !.PredInfo, !.ProcInfo, !ModuleInfo),
+            pd_info_set_module_info(!.ModuleInfo, !PDInfo)
 	),
 
-	pd_info_get_module_info(!.PDInfo, ModuleInfo),
+        pd_info_get_module_info(!.PDInfo, !:ModuleInfo),
 	write_proc_progress_message("% Finished deforesting ",
-		PredId, ProcId, ModuleInfo, !IO),
+            PredId, ProcId, !.ModuleInfo, !IO),
 	pd_info_get_cost_delta(!.PDInfo, CostDelta),
 	pd_info_get_size_delta(!.PDInfo, SizeDelta),
-	pd_info_unset_unfold_info(!PDInfo).
+        pd_info_unset_unfold_info(!PDInfo)
+    ).
 
 :- pred deforest__goal(hlds_goal::in, hlds_goal::out,
 	pd_info::in, pd_info::out, io::di, io::uo) is det.
 
-deforest__goal(conj(Goals0) - Info, conj(Goals) - Info, !PDInfo, !IO) :-
+deforest__goal(conj(!.Goals) - Info, conj(!:Goals) - Info, !PDInfo, !IO) :-
 	pd_info_get_instmap(!.PDInfo, InstMap0),
-	deforest__partially_evaluate_conj_goals(Goals0, [], Goals1, !PDInfo,
+    deforest__partially_evaluate_conj_goals(!.Goals, [], !:Goals, !PDInfo,
 		!IO),
 	pd_info_set_instmap(InstMap0, !PDInfo),
 	goal_info_get_nonlocals(Info, NonLocals),
 	globals__io_lookup_bool_option(deforestation, Deforestation, !IO),
 	(
 		Deforestation = yes,
-		deforest__compute_goal_infos(Goals1, Goals2, !PDInfo),
+        deforest__compute_goal_infos(!Goals, !PDInfo),
 		pd_info_set_instmap(InstMap0, !PDInfo),
-		deforest__conj(Goals2, NonLocals, [], Goals3, !PDInfo, !IO)
+        deforest__conj(!.Goals, NonLocals, [], !:Goals, !PDInfo, !IO)
 	;
-		Deforestation = no,
-		Goals3 = Goals1
+        Deforestation = no
 	),
-	globals__io_lookup_bool_option(constraint_propagation, Constraints,
-		!IO),
+    globals__io_lookup_bool_option(constraint_propagation, Constraints, !IO),
 	pd_info_set_instmap(InstMap0, !PDInfo),
 	(
 		Constraints = yes,
-		deforest__propagate_conj_constraints(Goals3,
-			NonLocals, [], Goals, !PDInfo, !IO)
+        deforest__propagate_conj_constraints(!.Goals, NonLocals, [], !:Goals,
+            !PDInfo, !IO)
 	;
-		Constraints = no,
-		Goals = Goals3
+        Constraints = no
 	),
 	pd_info_set_instmap(InstMap0, !PDInfo).
 
@@ -350,7 +344,7 @@
 
 deforest__goal(shorthand(_) - _, _, !PDInfo, !IO) :-
 	% these should have been expanded out by now
-	error("deforest__goal: unexpected shorthand").
+    unexpected(this_file, "deforest__goal: unexpected shorthand").
 
 %-----------------------------------------------------------------------------%
 
@@ -382,6 +376,7 @@
 %-----------------------------------------------------------------------------%
 
 	% Perform partial evaluation on the goals of a conjunction.
+    %
 :- pred deforest__partially_evaluate_conj_goals(list(hlds_goal)::in,
 	list(hlds_goal)::in, list(hlds_goal)::out,
 	pd_info::in, pd_info::out, io::di, io::uo) is det.
@@ -404,6 +399,7 @@
 %-----------------------------------------------------------------------------%
 
 	% Compute the branch info for each goal in a conjunction.
+    %
 :- pred deforest__compute_goal_infos(list(hlds_goal)::in, annotated_conj::out,
 	pd_info::in, pd_info::out) is det.
 
@@ -415,8 +411,7 @@
 	deforest__compute_goal_infos(Goals0, Goals, !PDInfo).
 
 :- pred deforest__get_branch_vars_goal(hlds_goal::in,
-	maybe(pd_branch_info(prog_var))::out, pd_info::in, pd_info::out)
-	is det.
+    maybe(pd_branch_info(prog_var))::out, pd_info::in, pd_info::out) is det.
 
 deforest__get_branch_vars_goal(Goal, MaybeBranchInfo, !PDInfo) :-
 	Goal = GoalExpr - _,
@@ -424,14 +419,10 @@
 		pd_util__get_branch_vars_goal(Goal, MaybeBranchInfo, !PDInfo)
 	; GoalExpr = call(PredId, ProcId, Args, _, _, _) ->
 		pd_info_get_proc_arg_info(!.PDInfo, ProcBranchInfos),
-		(
-			map__search(ProcBranchInfos, proc(PredId, ProcId),
-				BranchInfo0)
-		->
+        ( map__search(ProcBranchInfos, proc(PredId, ProcId), BranchInfo0) ->
 			% Rename the branch_info for the called procedure
 			% onto the argument variables.
-			pd_util__convert_branch_info(BranchInfo0, Args,
-				BranchInfo),
+            pd_util__convert_branch_info(BranchInfo0, Args, BranchInfo),
 			MaybeBranchInfo = yes(BranchInfo)
 		;
 			MaybeBranchInfo = no
@@ -475,15 +466,13 @@
 			MaybeGoal = yes(Goal),
 			pd_info_set_rerun_det(yes, !PDInfo),
 			pd_info_update_goal(Goal, !PDInfo),
-			deforest__propagate_conj_constraints(Goals1,
-				NonLocals, [Goal | RevGoals0], Goals,
-				!PDInfo, !IO)
+            deforest__propagate_conj_constraints(Goals1, NonLocals,
+                [Goal | RevGoals0], Goals, !PDInfo, !IO)
 		;
 			MaybeGoal = no,
 			pd_info_update_goal(Goal0, !PDInfo),
-			deforest__propagate_conj_constraints(Goals0,
-				NonLocals, [Goal0 | RevGoals0], Goals,
-				!PDInfo, !IO)
+            deforest__propagate_conj_constraints(Goals0, NonLocals,
+                [Goal0 | RevGoals0], Goals, !PDInfo, !IO)
 		)
 	;
 		pd_info_update_goal(Goal0, !PDInfo),
@@ -511,51 +500,52 @@
 			Goals0, Goals1, DeforestInfo)
 	->
 		deforest__handle_deforestation(NonLocals, DeforestInfo,
-			RevGoals0, RevGoals1, Goals1, Goals2, Optimized,
-			!PDInfo, !IO),
-		( Optimized = yes ->
-			deforest__conj(Goals2, NonLocals, RevGoals1, RevGoals,
-				!PDInfo, !IO)
+            RevGoals0, RevGoals1, Goals1, Goals2, Optimized, !PDInfo, !IO),
+        (
+            Optimized = yes,
+            deforest__conj(Goals2, NonLocals, RevGoals1, RevGoals, !PDInfo,
+                !IO)
 		;
+            Optimized = no,
 			pd_info_update_goal(Goal0, !PDInfo),
 			RevGoals2 = [Goal0 | RevGoals0],
-			deforest__conj(Goals0, NonLocals, RevGoals2, RevGoals,
-				!PDInfo, !IO)
+            deforest__conj(Goals0, NonLocals, RevGoals2, RevGoals, !PDInfo,
+                !IO)
 		)
 	;
 		pd_info_update_goal(Goal0, !PDInfo),
 		RevGoals1 = [Goal0 | RevGoals0],
-		deforest__conj(Goals0, NonLocals, RevGoals1, RevGoals,
-			!PDInfo, !IO)
+        deforest__conj(Goals0, NonLocals, RevGoals1, RevGoals, !PDInfo, !IO)
 	).
 
 %-----------------------------------------------------------------------------%
 
-:- type deforest_info --->
-	deforest_info(
+:- type deforest_info
+    --->    deforest_info(
 		hlds_goal,		% earlier goal in conjunction
 		pd_branch_info(prog_var),
-					%branch_info for earlier goal
+                                            % branch_info for earlier goal
 		list(hlds_goal),	% goals in between
 		hlds_goal,		% later goal in conjunction
 		pd_branch_info(prog_var),
 					% branch_info for later goal
 		set(int)		% branches for which there is
-					% extra information about the second
-					% goal, numbering starts at 1.
+                                            % extra information about the
+                                            % second goal, numbering starts
+                                            % at 1.
 	).
 
-	% Search backwards through the conjunction for the last
-	% goal which contains extra information about the variable
-	% being switched on.
+    % Search backwards through the conjunction for the last goal which contains
+    % extra information about the variable being switched on.
+    %
 :- pred deforest__detect_deforestation(hlds_goal::in,
 	pd_branch_info(prog_var)::in, annotated_conj::in,
 	annotated_conj::out, deforest_info::out) is semidet.
 
-deforest__detect_deforestation(EarlierGoal, BranchInfo,
-		Goals0, Goals1, DeforestInfo) :-
-	deforest__search_for_deforest_goal(EarlierGoal, BranchInfo, [],
-		Goals0, Goals1, DeforestInfo).
+deforest__detect_deforestation(EarlierGoal, BranchInfo, !Goals,
+        DeforestInfo) :-
+    deforest__search_for_deforest_goal(EarlierGoal, BranchInfo, [], !Goals,
+        DeforestInfo).
 
 :- pred deforest__search_for_deforest_goal(hlds_goal::in,
 	pd_branch_info(prog_var)::in, annotated_conj::in,
@@ -586,10 +576,10 @@
 			Goals0, Goals, DeforestInfo)
 	).
 
-	% Look for a variable in the second branch_info for which
-	% we have more information in the first than in the instmap.
-	% Get the branches in the first goal which contain this extra
-	% information.
+    % Look for a variable in the second branch_info for which we have more
+    % information in the first than in the instmap. Get the branches in the
+    % first goal which contain this extra information.
+    %
 :- pred deforest__potential_deforestation(pd_branch_info(prog_var)::in,
 	pd_branch_info(prog_var)::in, set(int)::out) is semidet.
 
@@ -702,8 +692,7 @@
 		set__insert(Parents0, proc(PredId, ProcId), Parents),
 		pd_info_set_parents(Parents, !PDInfo),
 		deforest__push_goal_into_goal(ConjNonLocals, DeforestBranches,
-			EarlierGoal, BetweenGoals, LaterGoal, Goal,
-			!PDInfo, !IO),
+            EarlierGoal, BetweenGoals, LaterGoal, Goal, !PDInfo, !IO),
 		Goals = [Goal],
 		Optimized0 = yes
 	;
@@ -718,8 +707,7 @@
 	->
 		pd_debug__message("Pushing goal into goal\n", [], !IO),
 		deforest__push_goal_into_goal(ConjNonLocals, DeforestBranches,
-			EarlierGoal, BetweenGoals, LaterGoal, Goal,
-			!PDInfo, !IO),
+            EarlierGoal, BetweenGoals, LaterGoal, Goal, !PDInfo, !IO),
 		Goals = [Goal],
 		goals_size([EarlierGoal | BetweenGoals], ConjSize1),
 		goal_size(LaterGoal, ConjSize2),
@@ -754,8 +742,7 @@
 
 		% Remove any versions which were created.
 		pd_info_get_created_versions(!.PDInfo, CreatedVersions),
-		set__difference(CreatedVersions,
-			CreatedVersions0, NewVersions0),
+        set__difference(CreatedVersions, CreatedVersions0, NewVersions0),
 		set__to_sorted_list(NewVersions0, NewVersions),
 		list__foldl(pd_info__remove_version, NewVersions, !PDInfo)
 
@@ -767,8 +754,7 @@
 		% the conjunction.
 		list__condense([BeforeIrrelevant, Goals, AfterIrrelevant],
 			GoalsToProcess),
-		deforest__compute_goal_infos(GoalsToProcess, GoalsAndInfo,
-			!PDInfo),
+        deforest__compute_goal_infos(GoalsToProcess, GoalsAndInfo, !PDInfo),
 		list__append(GoalsAndInfo, !AfterGoals),
 		pd_info_set_instmap(InstMap0, !PDInfo),
 		pd_info_set_changed(yes, !PDInfo),
@@ -792,8 +778,7 @@
 		set__member(proc(PredId1, ProcId1) - proc(PredId2, ProcId2),
 			UselessVersions)
 	->
-		pd_debug__message("version tried before, not worthwhile\n",
-			[], !IO),
+        pd_debug__message("version tried before, not worthwhile\n", [], !IO),
 		ShouldTry = no
 	;
 		%
@@ -807,12 +792,10 @@
 		),
 		OpaqueGoal = _ - OpaqueGoalInfo,
 		goal_info_get_nonlocals(OpaqueGoalInfo, OpaqueNonLocals),
-		set__intersect(OpaqueNonLocals, OpaqueVars,
-			UsedOpaqueVars),
+        set__intersect(OpaqueNonLocals, OpaqueVars, UsedOpaqueVars),
 		\+ set__empty(UsedOpaqueVars)
 	->
-		pd_debug__message("later goals depend on opaque vars\n", [],
-			!IO),
+        pd_debug__message("later goals depend on opaque vars\n", [], !IO),
 		ShouldTry = no
 	;
 		ShouldTry = yes
@@ -825,8 +808,7 @@
 deforest__can_optimize_conj(EarlierGoal, BetweenGoals, MaybeLaterGoal,
 		ShouldTry, !PDInfo, !IO) :-
 	pd_info_get_pred_info(!.PDInfo, PredInfo),
-	globals__io_lookup_option(deforestation_depth_limit, DepthLimitOpt,
-		!IO),
+    globals__io_lookup_option(deforestation_depth_limit, DepthLimitOpt, !IO),
 	pd_info_get_depth(!.PDInfo, Depth0),
 	Depth = Depth0 + 1,
 	pd_info_set_depth(Depth, !PDInfo),
@@ -842,8 +824,7 @@
 		% The depth limit was exceeded. This should not
 		% occur too often in practice - the depth limit
 		% is just a safety net.
-		pd_debug__message("\n\n*****Depth limit exceeded*****\n\n",
-			[], !IO),
+        pd_debug__message("\n\n*****Depth limit exceeded*****\n\n", [], !IO),
 		ShouldTry = no
 	;
 		% Check whether either of the goals to be
@@ -870,8 +851,7 @@
 		% Check whether either of the goals to be
 		% deforested can't be inlined.
 		( EarlierGoal = call(PredId, ProcId, _, BuiltinState, _, _) - _
-		; MaybeLaterGoal = yes(
-			call(PredId, ProcId, _, BuiltinState, _, _) - _)
+        ; MaybeLaterGoal = yes(call(PredId, ProcId, _, BuiltinState, _, _) - _)
 		),
 
 		% We don't attempt to deforest predicates which are
@@ -894,8 +874,7 @@
 		%
 		\+ deforest__is_simple_goal_list(BetweenGoals)
 	->
-		pd_debug__message("between goals not simple enough\n", [],
-			!IO),
+        pd_debug__message("between goals not simple enough\n", [], !IO),
 		ShouldTry = no
 	;
 		%
@@ -910,8 +889,7 @@
 		ImpureGoal = _ - ImpureGoalInfo,
 		\+ goal_info_is_pure(ImpureGoalInfo)
 	->
-		pd_debug__message("goal list contains impure goal(s)\n", [],
-			!IO),
+        pd_debug__message("goal list contains impure goal(s)\n", [], !IO),
 		ShouldTry = no
 	;
 		%
@@ -933,10 +911,11 @@
 		ShouldTry = yes
 	).
 
-	% Check that the code size increase is justified by the
-	% estimated performance increase. This should err towards
-	% allowing optimization - without any check at all the
-	% code size of the library only increases ~10%.
+    % Check that the code size increase is justified by the estimated
+    % performance increase. This should err towards allowing optimization
+    % - without any check at all the code size of the library only increases
+    % ~10%.
+    %
 :- pred deforest__check_improvement(bool::in, int::in, int::in, bool::out,
 	pd_info::in, io::di, io::uo) is det.
 
@@ -965,6 +944,7 @@
 %-----------------------------------------------------------------------------%
 
 	% Attempt deforestation on a pair of calls.
+    %
 :- pred deforest__call_call(set(prog_var)::in, hlds_goal::in,
 	list(hlds_goal)::in, maybe(hlds_goal)::in, maybe(hlds_goal)::out,
 	pd_info::in, pd_info::out, io::di, io::uo) is det.
@@ -983,6 +963,7 @@
 	).
 
 	% Attempt deforestation on a pair of calls.
+    %
 :- pred deforest__call_call_2(set(prog_var)::in, hlds_goal::in,
 	list(hlds_goal)::in, maybe(hlds_goal)::in, maybe(hlds_goal)::out,
 	pd_info::in, pd_info::out, io::di, io::uo) is det.
@@ -1027,8 +1008,8 @@
 		pd_info_get_versions(!.PDInfo, Versions),
 		pd_info_get_instmap(!.PDInfo, InstMap),
 		pd_term__global_check(ModuleInfo, EarlierGoal, BetweenGoals,
-			MaybeLaterGoal, InstMap, Versions, TermInfo0,
-			TermInfo, CheckResult),
+            MaybeLaterGoal, InstMap, Versions, TermInfo0, TermInfo,
+            CheckResult),
 		(
 			CheckResult = ok(ProcPair, Size),
 			pd_debug__message(
@@ -1037,27 +1018,22 @@
 			pd_info_set_global_term_info(TermInfo, !PDInfo),
 			RunModes = no,
 			MaybeGeneralised = no,
-			deforest__create_deforest_goal(EarlierGoal,
-				BetweenGoals, MaybeLaterGoal, FoldGoal,
-				ConjNonLocals, RunModes, ProcPair, Size,
-				MaybeGeneralised, MaybeGoal, !PDInfo, !IO)
+            deforest__create_deforest_goal(EarlierGoal, BetweenGoals,
+                MaybeLaterGoal, FoldGoal, ConjNonLocals, RunModes, ProcPair,
+                Size, MaybeGeneralised, MaybeGoal, !PDInfo, !IO)
 		;
 			CheckResult = possible_loop(ProcPair, Size,
 				CoveringPredProcId),
-			% The termination check found the same
-			% pair of end-points with the same length goal.
-			% If the goal matches the goal for the "covering"
-			% predicate, perform a most specific
-			% generalisation on the insts then keep
-			% on going.
-			deforest__try_generalisation(EarlierGoal,
-				BetweenGoals, MaybeLaterGoal, FoldGoal,
-				ConjNonLocals, ProcPair, Size,
+            % The termination check found the same pair of end-points with the
+            % same length goal. If the goal matches the goal for the "covering"
+            % predicate, perform a most specific generalisation on the insts
+            % then keep on going.
+            deforest__try_generalisation(EarlierGoal, BetweenGoals,
+                MaybeLaterGoal, FoldGoal, ConjNonLocals, ProcPair, Size,
 				CoveringPredProcId, MaybeGoal, !PDInfo, !IO)
 		;
 			CheckResult = loop,
-			pd_debug__message("global termination check failed\n",
-				[], !IO),
+            pd_debug__message("global termination check failed\n", [], !IO),
 			MaybeGoal = no
 		),
 		pd_info_set_global_term_info(TermInfo0, !PDInfo)
@@ -1067,6 +1043,7 @@
 
 	% Create a new procedure for a conjunction to be deforested, then
 	% recursively process that procedure.
+    %
 :- pred deforest__create_deforest_goal(hlds_goal::in, hlds_goals::in,
 	maybe(hlds_goal)::in, hlds_goal::in, set(prog_var)::in, bool::in,
 	proc_pair::in, int::in, maybe(pred_proc_id)::in,
@@ -1077,32 +1054,27 @@
 		FoldGoal0, NonLocals, RunModes, ProcPair, Size,
 		MaybeGeneralised, MaybeCallGoal, !PDInfo, !IO) :-
 	pd_info_get_module_info(!.PDInfo, ModuleInfo0),
-	globals__io_lookup_int_option(deforestation_vars_threshold, VarsOpt,
-		!IO),
+    globals__io_lookup_int_option(deforestation_vars_threshold, VarsOpt, !IO),
 	(
 		EarlierGoal = call(PredId1, ProcId1, Args1, _, _, _) - _,
 		(
-				% no threshold set.
+            % No threshold set.
 			VarsOpt = -1
 		;
-			%
-			% Check that we're not creating a procedure
-			% with a massive number of variables. We assume
-			% that all the variables in the first called
-			% goal are present in the final version. If the
-			% number of variables in the first called goal
-			% plus the number of variables in BetweenGoals
-			% is less than --deforestation-vars-threshold, go
-			% ahead and optimize.
-			%
+            % Check that we're not creating a procedure with a massive number
+            % of variables. We assume that all the variables in the first
+            % called goal are present in the final version. If the number
+            % of variables in the first called goal plus the number of
+            % variables in BetweenGoals is less than
+            % --deforestation-vars-threshold, go ahead and optimize.
+
 			module_info_pred_proc_info(ModuleInfo0,
 				PredId1, ProcId1, _, CalledProcInfo1),
 			proc_info_goal(CalledProcInfo1, CalledGoal1),
 			goal_util__goal_vars(CalledGoal1, GoalVars1),
 			set__to_sorted_list(GoalVars1, GoalVarsList1),
 			set__init(GoalVars2),
-			goal_util__goals_goal_vars(BetweenGoals,
-				GoalVars2, GoalVars3),
+            goal_util__goals_goal_vars(BetweenGoals, GoalVars2, GoalVars3),
 			set__to_sorted_list(GoalVars3, GoalVarsList3),
 
 			list__length(GoalVarsList1, NumVars1),
@@ -1131,17 +1103,14 @@
 			RunModes = yes
 		->
 
-			%
-			% If we did a generalisation step when creating this
-			% version, we need to modecheck to propagate through
-			% the new insts. If this causes mode errors, don't
-			% create the new version. This can happen if a
-			% procedure expected an input to be bound to a
-			% particular functor but the extra information
-			% was generalised away.
-			%
-			pd_debug__message("running modes on deforest goal\n",
-				[], !IO),
+            % If we did a generalisation step when creating this version,
+            % we need to modecheck to propagate through the new insts.
+            % If this causes mode errors, don't create the new version.
+            % This can happen if a procedure expected an input to be bound
+            % to a particular functor but the extra information was
+            % generalised away.
+
+            pd_debug__message("running modes on deforest goal\n", [], !IO),
 			pd_util__unique_modecheck_goal(DeforestGoal0,
 				DeforestGoal, Errors1, !PDInfo, !IO),
 			pd_util__unique_modecheck_goal(FoldGoal0, FoldGoal,
@@ -1174,11 +1143,9 @@
 			pd_debug__message("\nCreated predicate %s\n",
 				[s(PredName)], !IO),
 			(
-				MaybeLaterGoal = yes(
-					call(PredId2, ProcId2, _, _, _, _) - _)
+                MaybeLaterGoal = yes(call(PredId2, ProcId2, _, _, _, _) - _)
 			->
-				CalledPreds = [proc(PredId1, ProcId1),
-					proc(PredId2, ProcId2)]
+                CalledPreds = [proc(PredId1, ProcId1), proc(PredId2, ProcId2)]
 			;
 				CalledPreds = [proc(PredId1, ProcId1)]
 			),
@@ -1186,46 +1153,37 @@
 
 			pd_info_get_proc_info(!.PDInfo, ProcInfo1),
 			proc_info_vartypes(ProcInfo1, VarTypes),
-			map__apply_to_list(NonLocalsList,
-				VarTypes, ArgTypes),
-			VersionInfo = version_info(FoldGoal, CalledPreds,
-				NonLocalsList, ArgTypes, InstMap0,
-				0, 0, Parents0, MaybeGeneralised),
+            map__apply_to_list(NonLocalsList, VarTypes, ArgTypes),
+            VersionInfo = version_info(FoldGoal, CalledPreds, NonLocalsList,
+                ArgTypes, InstMap0, 0, 0, Parents0, MaybeGeneralised),
 			pd_info_get_global_term_info(!.PDInfo, TermInfo0),
 			pd_term__update_global_term_info(ProcPair, PredProcId,
 				Size, TermInfo0, TermInfo),
 			pd_info_set_global_term_info(TermInfo, !PDInfo),
-			set__insert_list(Parents0, [PredProcId | CalledPreds],
-				Parents),
+            set__insert_list(Parents0, [PredProcId | CalledPreds], Parents),
 			pd_info_set_parent_versions(Parents, !PDInfo),
-			pd_info__register_version(PredProcId, VersionInfo,
-				!PDInfo, !IO),
+            pd_info__register_version(PredProcId, VersionInfo, !PDInfo, !IO),
 
-			% Run deforestation on the new predicate
-			% to do the folding.
+            % Run deforestation on the new predicate to do the folding.
 			pd_info_get_unfold_info(!.PDInfo, UnfoldInfo),
-			deforest__proc(PredProcId, CostDelta, SizeDelta,
-				!PDInfo, !IO),
+            deforest__proc(PredProcId, CostDelta, SizeDelta, !PDInfo, !IO),
 			pd_info_set_unfold_info(UnfoldInfo, !PDInfo),
 			pd_info_incr_cost_delta(CostDelta, !PDInfo),
 			pd_info_incr_size_delta(SizeDelta, !PDInfo),
 			pd_info_set_parent_versions(Parents0, !PDInfo),
-			pd_info_get_pred_proc_id(!.PDInfo,
-				proc(CurrPredId, CurrProcId)),
+            pd_info_get_pred_proc_id(!.PDInfo, proc(CurrPredId, CurrProcId)),
 			write_proc_progress_message("% Back in ",
 				CurrPredId, CurrProcId, ModuleInfo, !IO),
 			MaybeCallGoal = yes(CallGoal)
 		;
-			pd_debug__message(
-				"Generalisation produced mode errors\n", [],
+            pd_debug__message("Generalisation produced mode errors\n", [],
 				!IO),
 			MaybeCallGoal = no
 		),
 
-		% The varset and vartypes fields were increased when
-		% we unfolded the first call, but all the new variables
-		% are only used in the new version, so it is safe to
-		% reset the proc_info.
+        % The varset and vartypes fields were increased when we unfolded
+        % the first call, but all the new variables are only used in the
+        % new version, so it is safe to reset the proc_info.
 		pd_info_set_proc_info(ProcInfo0, !PDInfo),
 		pd_info_set_instmap(InstMap0, !PDInfo)
 	;
@@ -1236,6 +1194,7 @@
 %-----------------------------------------------------------------------------%
 
 	% Create a goal to call a newly created version.
+    %
 :- pred deforest__create_call_goal(pred_proc_id::in, version_info::in,
 	map(prog_var, prog_var)::in, tsubst::in, hlds_goal::out,
 	pd_info::in, pd_info::out) is det.
@@ -1258,12 +1217,10 @@
 	pred_info_typevarset(PredInfo0, TVarSet0),
 
 		% Rename the argument types using the current pred's tvarset.
-	varset__merge_subst(TVarSet0, CalledTVarSet,
-		TVarSet, TypeRenaming),
+    varset__merge_subst(TVarSet0, CalledTVarSet, TVarSet, TypeRenaming),
 	pred_info_set_typevarset(TVarSet, PredInfo0, PredInfo),
 	pd_info_set_pred_info(PredInfo, !PDInfo),
-	term__apply_substitution_to_list(ArgTypes0,
-		TypeRenaming, ArgTypes1),
+    term__apply_substitution_to_list(ArgTypes0, TypeRenaming, ArgTypes1),
 
 	deforest__create_deforest_call_args(OldArgs, ArgTypes1, Renaming,
 		TypeSubn, Args, VarSet0, VarSet, VarTypes0, VarTypes),
@@ -1273,8 +1230,7 @@
 
 		% Compute a goal_info.
 	proc_info_argmodes(CalledProcInfo, ArgModes),
-	instmap_delta_from_mode_list(Args, ArgModes,
-		ModuleInfo, InstMapDelta),
+    instmap_delta_from_mode_list(Args, ArgModes, ModuleInfo, InstMapDelta),
 	proc_info_interface_determinism(ProcInfo, Detism),
 	set__list_to_set(Args, NonLocals),
 	pred_info_get_purity(CalledPredInfo, Purity),
@@ -1290,46 +1246,42 @@
 	list(prog_var)::out, prog_varset::in, prog_varset::out,
 	map(prog_var, type)::in, map(prog_var, type)::out) is det.
 
-deforest__create_deforest_call_args([], [], _, _, [],
-		VarSet, VarSet, VarTypes, VarTypes).
-deforest__create_deforest_call_args([], [_|_], _, _, _, _, _, _, _) :-
-	error("deforest__create_deforest_call_args: length mismatch").
-deforest__create_deforest_call_args([_|_], [], _, _, _, _, _, _, _) :-
-	error("deforest__create_deforest_call_args: length mismatch").
+deforest__create_deforest_call_args([], [], _, _, [], !VarSet, !VarTypes).
+deforest__create_deforest_call_args([], [_|_], _, _, _, !VarSet, !VarTypes) :-
+    unexpected(this_file, "create_deforest_call_args: length mismatch").
+deforest__create_deforest_call_args([_|_], [], _, _, _, !VarSet, !VarTypes) :-
+    unexpected(this_file, "create_deforest_call_args: length mismatch").
 deforest__create_deforest_call_args([OldArg | OldArgs], [ArgType | ArgTypes],
-		Renaming, TypeSubn, [Arg | Args], VarSet0, VarSet,
-		VarTypes0, VarTypes) :-
+        Renaming, TypeSubn, [Arg | Args], !VarSet, !VarTypes) :-
 	( map__search(Renaming, OldArg, Arg0) ->
-		Arg = Arg0,
-		VarSet1 = VarSet0,
-		VarTypes1 = VarTypes0
+        Arg = Arg0
 	;
 		% The variable is local to the call. Create a fresh variable.
-		varset__new_var(VarSet0, Arg, VarSet1),
-		term__apply_substitution(ArgType, TypeSubn, ArgType1),
-		map__det_insert(VarTypes0, Arg, ArgType1, VarTypes1)
+        varset__new_var(!.VarSet, Arg, !:VarSet),
+        term__apply_substitution(ArgType, TypeSubn, SubnArgType),
+        map__det_insert(!.VarTypes, Arg, SubnArgType, !:VarTypes)
 	),
 	deforest__create_deforest_call_args(OldArgs, ArgTypes, Renaming,
-		TypeSubn, Args, VarSet1, VarSet, VarTypes1, VarTypes).
+        TypeSubn, Args, !VarSet, !VarTypes).
 
 %-----------------------------------------------------------------------------%
 
-	% Combine the two goals to be deforested and the
-	% goals in between into a conjunction.
+    % Combine the two goals to be deforested and the goals in between
+    % into a conjunction.
+    %
 :- pred deforest__create_conj(hlds_goal::in, list(hlds_goal)::in,
 	maybe(hlds_goal)::in, set(prog_var)::in, hlds_goal::out) is det.
 
 deforest__create_conj(EarlierGoal, BetweenGoals, MaybeLaterGoal,
 			NonLocals, FoldGoal) :-
 	( MaybeLaterGoal = yes(LaterGoal) ->
-		list__append([EarlierGoal | BetweenGoals], [LaterGoal],
-			DeforestConj)
+        list__append([EarlierGoal | BetweenGoals], [LaterGoal], DeforestConj)
 	;
 		DeforestConj = [EarlierGoal | BetweenGoals]
 	),
 	goal_list_determinism(DeforestConj, Detism),
 	goal_list_instmap_delta(DeforestConj, InstMapDelta0),
-	instmap_delta_restrict(InstMapDelta0, NonLocals, InstMapDelta),
+    instmap_delta_restrict(NonLocals, InstMapDelta0, InstMapDelta),
 	goal_list_purity(DeforestConj, Purity),
 	goal_info_init(NonLocals, InstMapDelta, Detism, Purity, ConjInfo0),
 
@@ -1337,14 +1289,15 @@
 	% name points to the location of the first goal.
 	EarlierGoal = _ - EarlierGoalInfo,
 	goal_info_get_context(EarlierGoalInfo, EarlierContext),
-	goal_info_set_context(ConjInfo0, EarlierContext, ConjInfo),
+    goal_info_set_context(EarlierContext, ConjInfo0, ConjInfo),
 	FoldGoal = conj(DeforestConj) - ConjInfo.
 
 %-----------------------------------------------------------------------------%
 
-	% "Round-off" some of the extra information that caused the
-	% termination check to fail and/or the insts of the versions
-	% not to match in an attempt to achieve folding.
+    % "Round-off" some of the extra information that caused the termination
+    % check to fail and/or the insts of the versions not to match in an attempt
+    % to achieve folding.
+    %
 :- pred deforest__try_generalisation(hlds_goal::in, list(hlds_goal)::in,
 	maybe(hlds_goal)::in, hlds_goal::in, set(prog_var)::in,
 	proc_pair::in, int::in, pred_proc_id::in, maybe(hlds_goal)::out,
@@ -1366,27 +1319,24 @@
 		pd_util__goals_match(ModuleInfo, VersionGoal, VersionArgs,
 			VersionArgTypes, FoldGoal, VarTypes, Renaming, _)
 	->
-		deforest__do_generalisation(VersionArgs, Renaming,
-			VersionInstMap, EarlierGoal, BetweenGoals,
-			MaybeLaterGoal, FoldGoal, ConjNonLocals, ProcPair,
-			Size, CoveringPredProcId, MaybeGoal, !PDInfo, !IO)
-	;
-		% If the earlier goal is a generalisation of another
-		% version, try matching against that. This happens
-		% when attempting two deforestations in a row and
-		% the first deforestation required generalisation.
+        deforest__do_generalisation(VersionArgs, Renaming, VersionInstMap,
+            EarlierGoal, BetweenGoals, MaybeLaterGoal, FoldGoal, ConjNonLocals,
+            ProcPair, Size, CoveringPredProcId, MaybeGoal, !PDInfo, !IO)
+    ;
+        % If the earlier goal is a generalisation of another version, try
+        % matching against that. This happens when attempting two
+        % deforestations in a row and the first deforestation required
+        % generalisation.
 		proc_info_varset(ProcInfo, VarSet),
-		deforest__match_generalised_version(ModuleInfo,
-			VersionGoal, VersionArgs, VersionArgTypes,
-			EarlierGoal, BetweenGoals, MaybeLaterGoal,
-			ConjNonLocals, VarSet, VarTypes, Versions, Renaming)
-	->
-		pd_debug__message("matched with generalised version\n", [],
-			!IO),
-		deforest__do_generalisation(VersionArgs, Renaming,
-			VersionInstMap, EarlierGoal, BetweenGoals,
-			MaybeLaterGoal, FoldGoal, ConjNonLocals, ProcPair,
-			Size, CoveringPredProcId, MaybeGoal, !PDInfo, !IO)
+        deforest__match_generalised_version(ModuleInfo, VersionGoal,
+            VersionArgs, VersionArgTypes, EarlierGoal, BetweenGoals,
+            MaybeLaterGoal, ConjNonLocals, VarSet, VarTypes, Versions,
+            Renaming)
+    ->
+        pd_debug__message("matched with generalised version\n", [], !IO),
+        deforest__do_generalisation(VersionArgs, Renaming, VersionInstMap,
+            EarlierGoal, BetweenGoals, MaybeLaterGoal, FoldGoal, ConjNonLocals,
+            ProcPair, Size, CoveringPredProcId, MaybeGoal, !PDInfo, !IO)
 	;
 		pd_debug__message("goals don't match\n", [], !IO),
 		MaybeGoal = no
@@ -1405,20 +1355,16 @@
 	pd_debug__message("goals match, trying MSG\n", [], !IO),
 	pd_info_get_module_info(!.PDInfo, ModuleInfo),
 	pd_info_get_instmap(!.PDInfo, InstMap0),
-	instmap__lookup_vars(VersionArgs, VersionInstMap,
-		VersionInsts),
-	pd_util__inst_list_size(ModuleInfo, VersionInsts,
-		VersionInstSizes),
+    instmap__lookup_vars(VersionArgs, VersionInstMap, VersionInsts),
+    pd_util__inst_list_size(ModuleInfo, VersionInsts, VersionInstSizes),
 	set__to_sorted_list(ConjNonLocals, ConjNonLocalsList),
 	(
-		% Check whether we can do a most specific
-		% generalisation of insts of the non-locals.
-		deforest__try_MSG(ModuleInfo, VersionInstMap,
-			VersionArgs, Renaming, InstMap0, InstMap),
-		instmap__lookup_vars(ConjNonLocalsList, InstMap,
-			ArgInsts),
-		pd_util__inst_list_size(ModuleInfo, ArgInsts,
-			NewInstSizes),
+        % Check whether we can do a most specific generalisation of insts
+        % of the non-locals.
+        deforest__try_MSG(ModuleInfo, VersionInstMap, VersionArgs, Renaming,
+            InstMap0, InstMap),
+        instmap__lookup_vars(ConjNonLocalsList, InstMap, ArgInsts),
+        pd_util__inst_list_size(ModuleInfo, ArgInsts, NewInstSizes),
 		NewInstSizes < VersionInstSizes
 	->
 		pd_debug__message("MSG succeeded", [], !IO),
@@ -1444,7 +1390,7 @@
 		instmap__lookup_var(!.InstMap, Arg, VarInst),
 		inst_MSG(VersionInst, VarInst, ModuleInfo, Inst)
 	->
-		instmap__set(!.InstMap, Arg, Inst, !:InstMap)
+        instmap__set(Arg, Inst, !InstMap)
 	;
 		true
 	),
@@ -1464,6 +1410,7 @@
 	% reapplied to the entire conjunction.
 	%
 	% XXX this only undoes one level of generalisation.
+    %
 :- pred deforest__match_generalised_version(module_info::in,
 	hlds_goal::in, list(prog_var)::in, list(type)::in,
 	hlds_goal::in, list(hlds_goal)::in, maybe(hlds_goal)::in,
@@ -1472,20 +1419,16 @@
 
 deforest__match_generalised_version(ModuleInfo, VersionGoal, VersionArgs,
 		VersionArgTypes, FirstGoal, BetweenGoals, MaybeLastGoal,
-		ConjNonLocals, VarSet0, VarTypes0, Versions, Renaming) :-
+        ConjNonLocals, !.VarSet, !.VarTypes, Versions, Renaming) :-
 
 	FirstGoal = call(FirstPredId, FirstProcId, FirstArgs, _, _, _) - _,
 
-	%
 	% Look up the version which the first goal calls.
-	%
-	map__search(Versions, proc(FirstPredId, FirstProcId),
-		FirstVersionInfo),
+    map__search(Versions, proc(FirstPredId, FirstProcId), FirstVersionInfo),
 	FirstVersionInfo = version_info(FirstVersionGoal, _, FirstVersionArgs,
-			_,_,_,_,_, MaybeNonGeneralisedVersion),
+        _, _, _, _, _, MaybeNonGeneralisedVersion),
 	MaybeNonGeneralisedVersion = yes(NonGeneralisedPredProcId),
-	map__from_corresponding_lists(FirstVersionArgs,
-		FirstArgs, FirstRenaming0),
+    map__from_corresponding_lists(FirstVersionArgs, FirstArgs, FirstRenaming0),
 
 	goal_util__goal_vars(FirstVersionGoal, FirstVersionVars0),
 	set__to_sorted_list(FirstVersionVars0, FirstVersionVars),
@@ -1497,10 +1440,9 @@
 
 	goal_util__create_variables(FirstVersionVars,
 		FirstVersionVarSet, FirstVersionVarTypes,
-		VarSet0, VarSet, VarTypes0, VarTypes,
-		FirstRenaming0, FirstRenaming),
-	goal_util__must_rename_vars_in_goal(FirstVersionGoal, FirstRenaming,
-		RenamedFirstVersionGoal),
+        !VarSet, !VarTypes, FirstRenaming0, FirstRenaming),
+    goal_util__must_rename_vars_in_goal(FirstRenaming,
+        FirstVersionGoal, RenamedFirstVersionGoal),
 
 	%
 	% Look up the version which was generalised to create the version
@@ -1522,21 +1464,19 @@
 		NonGeneralisedArgs, NonGeneralisedArgTypes,_,_,_,_,_),
 	pd_util__goals_match(ModuleInfo, NonGeneralisedGoal,
 		NonGeneralisedArgs, NonGeneralisedArgTypes,
-		RenamedFirstVersionGoal, VarTypes, GeneralRenaming,
-		TypeRenaming),
+        RenamedFirstVersionGoal, !.VarTypes, GeneralRenaming, TypeRenaming),
 
 	module_info_pred_info(ModuleInfo, NonGeneralisedPredId,
 		NonGeneralisedPredInfo),
 	pred_info_arg_types(NonGeneralisedPredInfo, NonGeneralisedArgTypes),
 	deforest__create_deforest_call_args(NonGeneralisedArgs,
-		NonGeneralisedArgTypes, GeneralRenaming, TypeRenaming,
-		NewArgs, VarSet, _, VarTypes, _),
+        NonGeneralisedArgTypes, GeneralRenaming, TypeRenaming, NewArgs,
+        !.VarSet, _, !.VarTypes, _),
 
 	% Only fill in as much as pd_util__goals_match actually looks at.
 	goal_info_init(GoalInfo),
-	NonGeneralFirstGoal = call(NonGeneralisedPredId,
-		NonGeneralisedProcId, NewArgs, not_builtin,
-		no, unqualified("")) - GoalInfo,
+    NonGeneralFirstGoal = call(NonGeneralisedPredId, NonGeneralisedProcId,
+        NewArgs, not_builtin, no, unqualified("")) - GoalInfo,
 	deforest__create_conj(NonGeneralFirstGoal, BetweenGoals, MaybeLastGoal,
 		ConjNonLocals, GoalToMatch),
 
@@ -1544,15 +1484,15 @@
 	% Check whether the entire conjunction matches.
 	%
 	pd_util__goals_match(ModuleInfo, VersionGoal, VersionArgs,
-		VersionArgTypes, GoalToMatch, VarTypes, Renaming, _).
+        VersionArgTypes, GoalToMatch, !.VarTypes, Renaming, _).
 
 %-----------------------------------------------------------------------------%
 
-	% Work out the nonlocals of a sub-conjunction from the non-locals of
-	% the entire conjunction and the goals before and after the
-	% sub-conjunction. This is needed to ensure that the temporary
-	% list in double_append is found to be local to the conjunction
-	% and can be removed.
+    % Work out the nonlocals of a sub-conjunction from the non-locals of the
+    % entire conjunction and the goals before and after the sub-conjunction.
+    % This is needed to ensure that the temporary list in double_append is
+    % found to be local to the conjunction and can be removed.
+    %
 :- pred deforest__get_sub_conj_nonlocals(set(prog_var)::in, deforest_info::in,
 	list(hlds_goal)::in, list(hlds_goal)::in, list(hlds_goal)::in,
 	annotated_conj::in, set(prog_var)::out) is det.
@@ -1572,38 +1512,35 @@
 	list(hlds_goal)::in, maybe(hlds_goal)::in, list(hlds_goal)::in,
 	list(hlds_goal)::in, set(prog_var)::out) is det.
 
-deforest__get_sub_conj_nonlocals(NonLocals0, RevBeforeGoals, BeforeIrrelevant,
+deforest__get_sub_conj_nonlocals(!.NonLocals, RevBeforeGoals, BeforeIrrelevant,
 		EarlierGoal, BetweenGoals, MaybeLaterGoal,
-		AfterIrrelevant, AfterGoals, SubConjNonLocals) :-
+        AfterIrrelevant, AfterGoals, !:SubConjNonLocals) :-
 	AddGoalNonLocals = (pred(Goal::in, Vars0::in, Vars::out) is det :-
 		Goal = _ - GoalInfo,
 		goal_info_get_nonlocals(GoalInfo, GoalNonLocals),
 		set__union(Vars0, GoalNonLocals, Vars)
 	),
-	list__foldl(AddGoalNonLocals, RevBeforeGoals, NonLocals0, NonLocals1),
-	list__foldl(AddGoalNonLocals, BeforeIrrelevant,
-		NonLocals1, NonLocals2),
-	list__foldl(AddGoalNonLocals, AfterIrrelevant, NonLocals2, NonLocals3),
-	list__foldl(AddGoalNonLocals, AfterGoals, NonLocals3, NonLocals),
+    list__foldl(AddGoalNonLocals, RevBeforeGoals, !NonLocals),
+    list__foldl(AddGoalNonLocals, BeforeIrrelevant, !NonLocals),
+    list__foldl(AddGoalNonLocals, AfterIrrelevant, !NonLocals),
+    list__foldl(AddGoalNonLocals, AfterGoals, !NonLocals),
 
-	set__init(SubConjNonLocals0),
 	list__foldl(AddGoalNonLocals, [EarlierGoal | BetweenGoals],
-		SubConjNonLocals0, SubConjNonLocals1),
+        set__init, !:SubConjNonLocals),
 	( MaybeLaterGoal = yes(LaterGoal) ->
-		call(AddGoalNonLocals, LaterGoal, SubConjNonLocals1,
-			SubConjNonLocals2)
+        call(AddGoalNonLocals, LaterGoal, !SubConjNonLocals)
 	;
-		SubConjNonLocals2 = SubConjNonLocals1
+        true
 	),
-	set__intersect(NonLocals, SubConjNonLocals2, SubConjNonLocals).
+    set__intersect(!.NonLocals, !SubConjNonLocals).
 
 %-----------------------------------------------------------------------------%
 
-	% Attempt to move irrelevant goals out of the conjunction.
-	% This does a safe re-ordering that is guaranteed not to require
-	% rescheduling of the conjunction, since it does not reorder goals
-	% that depend on each other.
+    % Attempt to move irrelevant goals out of the conjunction. This does a safe
+    % re-ordering that is guaranteed not to require rescheduling of the
+    % conjunction, since it does not reorder goals that depend on each other.
 	% We favor moving goals backward to avoid removing tail recursion.
+    %
 :- pred deforest__reorder_conj(deforest_info::in, deforest_info::out,
 	list(hlds_goal)::out, list(hlds_goal)::out, pd_info::in,
 	io::di, io::uo) is det.
@@ -1650,11 +1587,11 @@
 :- type can_move == pred(module_info, bool, hlds_goal, hlds_goals).
 :- mode can_move == (pred(in, in, in, in) is semidet).
 
-	% Check all goals occurring later in the conjunction to
-	% see if they depend on the current goal. A goal
-	% depends on the current goal if any of the non-locals
-	% of the later goal have their instantiatedness changed
+    % Check all goals occurring later in the conjunction to see if they depend
+    % on the current goal. A goal depends on the current goal if any of the
+    % non-locals of the later goal have their instantiatedness changed
 	% by the current goal.
+    %
 :- pred deforest__can_move_goal_forward(module_info::in, bool::in,
 	hlds_goal::in, list(hlds_goal)::in) is semidet.
 
@@ -1665,8 +1602,9 @@
 			ThisGoal, LaterGoal)
 	).
 
-	% Check all goals occurring earlier in the conjunction to
-	% see if the current goal depends on them.
+    % Check all goals occurring earlier in the conjunction to see
+    % if the current goal depends on them.
+    %
 :- pred deforest__can_move_goal_backward(module_info::in, bool::in,
 	hlds_goal::in, list(hlds_goal)::in) is semidet.
 
@@ -1679,9 +1617,10 @@
 
 %-----------------------------------------------------------------------------%
 
-	% Tack the second goal and the goals in between onto the end
-	% of each branch of the first goal, unfolding the second goal
-	% in the branches which have extra information about the arguments.
+    % Tack the second goal and the goals in between onto the end of each branch
+    % of the first goal, unfolding the second goal in the branches which have
+    % extra information about the arguments.
+    %
 :- pred deforest__push_goal_into_goal(set(prog_var)::in, set(int)::in,
 	hlds_goal::in, hlds_goals::in, hlds_goal::in, hlds_goal::out,
 	pd_info::in, pd_info::out, io::di, io::uo) is det.
@@ -1693,8 +1632,7 @@
 	( EarlierGoalExpr = switch(Var1, CanFail1, Cases1) ->
 		set__insert(NonLocals, Var1, CaseNonLocals),
 		deforest__append_goal_to_cases(Var1, BetweenGoals, LaterGoal,
-			CaseNonLocals, 1, DeforestInfo, Cases1, Cases,
-			!PDInfo, !IO),
+            CaseNonLocals, 1, DeforestInfo, Cases1, Cases, !PDInfo, !IO),
 		GoalExpr = switch(Var1, CanFail1, Cases)
 	; EarlierGoalExpr = if_then_else(Vars, Cond, Then0, Else0) ->
 		pd_info_update_goal(Cond, !PDInfo),
@@ -1709,18 +1647,17 @@
 		GoalExpr = if_then_else(Vars, Cond, Then, Else)
 	; EarlierGoalExpr = disj(Disjuncts0) ->
 		deforest__append_goal_to_disjuncts(BetweenGoals, LaterGoal,
-			NonLocals, 1, DeforestInfo, Disjuncts0, Disjuncts,
-			!PDInfo, !IO),
+            NonLocals, 1, DeforestInfo, Disjuncts0, Disjuncts, !PDInfo, !IO),
 		GoalExpr = disj(Disjuncts)
 	;
-		error("deforest__push_goal_into_goal")
+        unexpected(this_file, "deforest__push_goal_into_goal")
 	),
 	pd_info_set_instmap(InstMap0, !PDInfo),
 	goal_list_instmap_delta([EarlierGoal | BetweenGoals], Delta0),
 	LaterGoal = _ - LaterInfo,
 	goal_info_get_instmap_delta(LaterInfo, Delta1),
 	instmap_delta_apply_instmap_delta(Delta0, Delta1, test_size, Delta2),
-	instmap_delta_restrict(Delta2, NonLocals, Delta),
+    instmap_delta_restrict(NonLocals, Delta2, Delta),
 	goal_list_determinism([EarlierGoal | BetweenGoals], Detism0),
 	goal_info_get_determinism(LaterInfo, Detism1),
 	det_conjunction_detism(Detism0, Detism1, Detism),
@@ -1802,7 +1739,7 @@
 	goal_list_nonlocals(Goals, SubNonLocals),
 	set__intersect(NonLocals0, SubNonLocals, NonLocals),
 	goal_list_instmap_delta(Goals, Delta0),
-	instmap_delta_restrict(Delta0, NonLocals, Delta),
+    instmap_delta_restrict(NonLocals, Delta0, Delta),
 	goal_list_determinism(Goals, Detism),
 	goal_list_purity(Goals, Purity),
 	goal_info_init(NonLocals, Delta, Detism, Purity, GoalInfo),
@@ -1833,8 +1770,7 @@
 	pred_info_get_markers(PredInfo, CallerMarkers),
 	(
 		% Check for extra information to the call.
-		map__search(ProcArgInfos, proc(PredId, ProcId),
-			ProcArgInfo),
+        map__search(ProcArgInfos, proc(PredId, ProcId), ProcArgInfo),
 		ProcArgInfo = pd_branch_info(_, LeftArgs, _),
 		set__member(LeftArg, LeftArgs),
 		list__index1_det(Args, LeftArg, Arg),
@@ -1867,9 +1803,7 @@
 			pd_term__local_check(ModuleInfo, Goal0, InstMap,
 				LocalTermInfo0, LocalTermInfo)
 		->
-			pd_debug__message(
-				"Local termination check succeeded\n", [],
-				!IO),
+            pd_debug__message("Local termination check succeeded\n", [], !IO),
 			pd_info_set_local_term_info(LocalTermInfo, !PDInfo),
 			deforest__unfold_call(yes, yes, PredId, ProcId,
 				Args, Goal0, Goal1, Optimized, !PDInfo, !IO),
@@ -1880,13 +1814,11 @@
 			),
 			pd_info_set_local_term_info(LocalTermInfo0, !PDInfo)
 		;
-			pd_debug__message("Local termination check failed\n",
-				[], !IO),
+            pd_debug__message("Local termination check failed\n", [], !IO),
 			Goal = GoalExpr0 - GoalInfo0
 		)
 	;
-		pd_debug__message(Context,
-			"No extra information for call to %s/%i\n",
+        pd_debug__message(Context, "No extra information for call to %s/%i\n",
 			[s(Name), i(Arity)], !IO),
 		Goal = Goal0
 	).
@@ -1897,16 +1829,13 @@
 
 deforest__unfold_call(CheckImprovement, CheckVars, PredId, ProcId, Args,
 		Goal0, Goal, Optimized, !PDInfo, !IO) :-
-	globals__io_lookup_int_option(deforestation_vars_threshold, VarsOpt,
-		!IO),
+    globals__io_lookup_int_option(deforestation_vars_threshold, VarsOpt, !IO),
 	pd_info_get_proc_info(!.PDInfo, ProcInfo0),
 	proc_info_varset(ProcInfo0, VarSet0),
 	varset__vars(VarSet0, Vars),
 	list__length(Vars, NumVars),
 	(
-		%
 		% Check that we haven't already got too many variables.
-		%
 		(
 			CheckVars = no
 		;
@@ -1926,8 +1855,7 @@
 		proc_info_rtti_varmaps(ProcInfo0, RttiVarMaps0),
 		inlining__do_inline_call(UnivQVars, Args, CalledPredInfo,
 			CalledProcInfo, VarSet0, VarSet, VarTypes0, VarTypes,
-			TypeVarSet0, TypeVarSet, RttiVarMaps0, RttiVarMaps,
-			Goal1),
+            TypeVarSet0, TypeVarSet, RttiVarMaps0, RttiVarMaps, Goal1),
 		pred_info_set_typevarset(TypeVarSet, PredInfo0, PredInfo),
 		proc_info_set_varset(VarSet, ProcInfo0, ProcInfo1),
 		proc_info_set_vartypes(VarTypes, ProcInfo1, ProcInfo2),
@@ -1940,20 +1868,17 @@
 		pd_info_get_size_delta(!.PDInfo, SizeDelta0),
 		pd_info_get_changed(!.PDInfo, Changed0),
 
-			% update the quantification if not all the output
-			% arguments are used.
+        % Update the quantification if not all the output arguments are used.
 		Goal1 = _ - GoalInfo1,
 		goal_info_get_nonlocals(GoalInfo1, NonLocals1),
 		set__list_to_set(Args, NonLocals),
 		( \+ set__equal(NonLocals1, NonLocals) ->
-			pd_util__requantify_goal(NonLocals, Goal1, Goal2,
-				!PDInfo)
+            pd_util__requantify_goal(NonLocals, Goal1, Goal2, !PDInfo)
 		;
 			Goal2 = Goal1
 		),
 
-			% Push the extra information from the call
-			% through the goal.
+        % Push the extra information from the call through the goal.
 		pd_debug__message("Running unique modes\n", [], !IO),
 		proc_info_arglives(CalledProcInfo, ModuleInfo0, ArgLives),
 		get_live_vars(Args, ArgLives, LiveVars0),
@@ -1962,12 +1887,13 @@
 		pd_util__unique_modecheck_goal(LiveVars, Goal2, Goal3, Errors,
 			!PDInfo, !IO),
 
-		( Errors = [] ->
+        (
+            Errors = [],
 			Optimized0 = yes
 		;
-			% This can happen because common.m does not
-			% maintain unique mode correctness. This should
-			% eventually be fixed.
+            Errors = [_ | _],
+            % This can happen because common.m does not maintain unique mode
+            % correctness. This should eventually be fixed.
 			Optimized0 = no
 		),
 
@@ -1982,8 +1908,7 @@
 		goal_size(Goal4, GoalSize),
 		pd_cost__call(CallCost),
 		SizeDelta = GoalSize - CallCost,
-		globals__io_lookup_int_option(deforestation_cost_factor,
-			Factor, !IO),
+        globals__io_lookup_int_option(deforestation_cost_factor, Factor, !IO),
 		(
 			Optimized0 = yes,
 			(
@@ -1994,8 +1919,7 @@
 				( deforest__is_simple_goal(Goal3) ->
 					true
 				;
-					deforest__check_improvement(Factor,
-						GoalSize, OriginalCost,
+                    deforest__check_improvement(Factor, GoalSize, OriginalCost,
 						CostDelta)
 				)
 			)
@@ -2010,9 +1934,8 @@
 			Goal = _ - GoalInfo,
 			goal_info_get_determinism(GoalInfo, Det),
 
-			% Rerun determinism analysis later if
-			% the determinism of any of the sub-goals
-			% changes - this avoids problems with inlining
+            % Rerun determinism analysis later if the determinism of any of
+            % the sub-goals changes - this avoids problems with inlining
 			% erroneous predicates.
 			( Det = Det0 ->
 				true
@@ -2034,8 +1957,7 @@
 			Optimized = no
 		)
 	;
-		pd_debug__message("too many variables - not inlining\n", [],
-			!IO),
+        pd_debug__message("too many variables - not inlining\n", [], !IO),
 		Goal = Goal0,
 		Optimized = no
 	).
@@ -2065,14 +1987,13 @@
 
 	% Very rough heuristics for checking improvement. This should lean
 	% towards allowing optimizations.
-
+    %
 :- pred deforest__check_improvement(int::in, int::in, int::in, int::in)
 	is semidet.
 
 deforest__check_improvement(_Factor, Size, OriginalCost, CostDelta) :-
 	( Size =< 5 ->
-			% For small increases in size,
-			% accept any amount of optimization.
+        % For small increases in size, accept any amount of optimization.
 		CostDelta > 0
 	;
 		PercentChange = CostDelta * 100 // OriginalCost,
@@ -2084,14 +2005,12 @@
 
 deforest__check_deforestation_improvement(Factor, CostDelta, SizeChange) :-
 	( SizeChange =< 5 ->
-			% For small increases in size,
-			% accept any amount of optimization.
+        % For small increases in size, accept any amount of optimization.
 		CostDelta > 0
 	;
-			% Accept the optimization if we save the equivalent
-			% of a heap increment per 3 extra atomic goals.
-			% Note that folding is heavily rewarded by pd_cost.m,
-			% so this isn't very restrictive if a fold occurs.
+        % Accept the optimization if we save the equivalent of a heap increment
+        % per 3 extra atomic goals. Note that folding is heavily rewarded by
+        % pd_cost.m, so this isn't very restrictive if a fold occurs.
 		pd_cost__heap_incr(HeapCost),
 		ExpectedCostDelta = 1000 * HeapCost * SizeChange // 3,
 		FudgedCostDelta = CostDelta * Factor,
@@ -2099,4 +2018,9 @@
 	).
 
 %-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "deforest.m".
+
 %-----------------------------------------------------------------------------%
Index: compiler/det_analysis.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/det_analysis.m,v
retrieving revision 1.177
diff -u -b -r1.177 det_analysis.m
--- compiler/det_analysis.m	19 Aug 2005 08:35:56 -0000	1.177
+++ compiler/det_analysis.m	27 Aug 2005 13:55:04 -0000
@@ -417,7 +417,7 @@
         Solns = InternalSolns
     ),
     determinism_components(Detism, InternalCanFail, Solns),
-    goal_info_set_determinism(GoalInfo0, Detism, GoalInfo),
+    goal_info_set_determinism(Detism, GoalInfo0, GoalInfo),
 
     % The code generators assume that conjunctions containing multi or nondet
     % goals and if-then-elses containing multi or nondet conditions can only
@@ -474,7 +474,7 @@
     ->
         % A commit is needed - we must introduce an explicit `commit' so that
         % the code generator knows to insert the appropriate code for pruning.
-        goal_info_set_determinism(GoalInfo0, FinalInternalDetism, InnerInfo),
+        goal_info_set_determinism(FinalInternalDetism, GoalInfo0, InnerInfo),
         Goal = scope(commit(dont_force_pruning), Goal1 - InnerInfo)
     ;
         % Either no commit is needed, or a `scope' is already present.
Index: compiler/det_report.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/det_report.m,v
retrieving revision 1.103
diff -u -b -r1.103 det_report.m
--- compiler/det_report.m	22 Aug 2005 03:55:10 -0000	1.103
+++ compiler/det_report.m	28 Aug 2005 08:36:04 -0000
@@ -1187,10 +1187,8 @@
 det_report_msg(duplicate_call(SeenCall, PrevContext, Context), ModuleInfo,
         !IO) :-
     CallPieces = det_report_seen_call_id(ModuleInfo, SeenCall),
-    CurPieces = [words("Warning: redundant") |
-        append_punctuation(CallPieces, '.')],
-    PrevPieces = [words("Here is the previous") |
-        append_punctuation(CallPieces, '.')],
+    CurPieces = [words("Warning: redundant") | CallPieces] ++ [suffix(".")],
+    PrevPieces = [words("Here is the previous") | CallPieces] ++ [suffix(".")],
     write_error_pieces(Context, 0, CurPieces, !IO),
     write_error_pieces(PrevContext, 0, PrevPieces, !IO).
 det_report_msg(cc_unify_can_fail(GoalInfo, Var, Type, VarSet, GoalContext),
@@ -1199,8 +1197,7 @@
     (
         GoalContext = switch,
         VarStr = mercury_var_to_string(Var, VarSet, no),
-        Pieces0 = [words("In switch on variable `" ++ VarStr ++ "':"),
-            nl]
+        Pieces0 = [words("In switch on variable `" ++ VarStr ++ "':"), nl]
     ;
         GoalContext = unify(UnifyContext),
         hlds_out__unify_context_to_pieces(UnifyContext, [], Pieces0)
Index: compiler/disj_gen.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/disj_gen.m,v
retrieving revision 1.83
diff -u -b -r1.83 disj_gen.m
--- compiler/disj_gen.m	10 Jun 2005 06:48:13 -0000	1.83
+++ compiler/disj_gen.m	27 Aug 2005 17:16:55 -0000
@@ -194,7 +194,7 @@
             % The pre_goal_update sanity check insists on
             % no_resume_point, to make sure that all resume
             % points have been handled by surrounding code.
-        goal_info_set_resume_point(GoalInfo0, no_resume_point, GoalInfo),
+        goal_info_set_resume_point(no_resume_point, GoalInfo0, GoalInfo),
         Goal = GoalExpr0 - GoalInfo,
 
             % Save hp if it needs to be saved and hasn't been
Index: compiler/equiv_type.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/equiv_type.m,v
retrieving revision 1.46
diff -u -b -r1.46 equiv_type.m
--- compiler/equiv_type.m	20 Apr 2005 12:57:09 -0000	1.46
+++ compiler/equiv_type.m	28 Aug 2005 05:43:53 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1996-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -42,6 +44,7 @@
 	% For items not defined in the current module, the items expanded
 	% while processing each item are recorded in the recompilation_info,
 	% for use by smart recompilation.
+    %
 :- pred equiv_type__expand_eqv_types(module_name::in,
 	list(item_and_context)::in, list(item_and_context)::out,
 	bool::out, eqv_map::out,
@@ -50,6 +53,7 @@
 
 	% Replace equivalence types in a given type.
 	% The bool output is `yes' if anything changed.
+    %
 :- pred equiv_type__replace_in_type(eqv_map::in, (type)::in, (type)::out,
 	bool::out, tvarset::in, tvarset::out,
 	equiv_type_info::in, equiv_type_info::out) is det.
@@ -81,10 +85,12 @@
 	% For smart recompilation we need to record which items were
 	% expanded in each declaration.  Any items which depend on
 	% that declaration also depend on the expanded items.
+    %
 :- pred equiv_type__maybe_record_expanded_items(module_name::in, sym_name::in,
 	maybe(recompilation_info)::in, equiv_type_info::out) is det.
 
 	% Record all the expanded items in the recompilation_info.
+    %
 :- pred equiv_type__finish_recording_expanded_items(item_id::in,
 	equiv_type_info::in, maybe(recompilation_info)::in,
 	maybe(recompilation_info)::out) is det.
@@ -107,6 +113,7 @@
 :- import_module require.
 :- import_module set.
 :- import_module std_util.
+:- import_module svmap.
 :- import_module term.
 :- import_module varset.
 
@@ -114,9 +121,8 @@
 %-----------------------------------------------------------------------------%
 
 	% First we build up a mapping which records the equivalence type
-	% definitions.  Then we go through the item list and replace
-	% them.
-
+    % definitions.  Then we go through the item list and replace them.
+    %
 equiv_type__expand_eqv_types(ModuleName, Items0, Items, Error, EqvMap,
 		!Info, !IO) :-
 	map__init(EqvMap0),
@@ -127,12 +133,11 @@
 		EqvInstMap, [], RevItems, [], ErrorList, !Info),
 	list__reverse(RevItems, Items),
 	(
-		ErrorList = []
-	->
+        ErrorList = [],
 		Error = no
 	;
-		list__foldl(equiv_type__report_error,
-			list__reverse(ErrorList), !IO),
+        ErrorList = [_ | _],
+        list__foldl(equiv_type__report_error, list__reverse(ErrorList), !IO),
 		Error = yes,
 		io__set_exit_status(1, !IO)
 	).
@@ -165,13 +170,12 @@
 	; Item = type_defn(VarSet, Name, Args, eqv_type(Body), _Cond) ->
 		Items = Items0,
 		list__length(Args, Arity),
-		map__set(!.EqvMap, Name - Arity,
-			eqv_type_body(VarSet, Args, Body), !:EqvMap)
+        svmap__set(Name - Arity, eqv_type_body(VarSet, Args, Body), !EqvMap)
 	; Item = inst_defn(VarSet, Name, Args, eqv_inst(Body), _) ->
 		Items = Items0,
 		list__length(Args, Arity),
-		map__set(!.EqvInstMap, Name - Arity,
-			eqv_inst_body(VarSet, Args, Body), !:EqvInstMap)
+        svmap__set(Name - Arity, eqv_inst_body(VarSet, Args, Body),
+            !EqvInstMap)
 	;
 		Items = Items0
 	),
@@ -215,7 +219,7 @@
 	% performs substititution of equivalence types on a list
 	% of items.  Similarly the replace_in_<foo> predicates that
 	% follow perform substitution of equivalence types on <foo>s.
-
+    %
 :- pred equiv_type__replace_in_item_list(module_name::in,
 	list(item_and_context)::in, eqv_map::in, eqv_inst_map::in,
 	list(item_and_context)::in, list(item_and_context)::out,
@@ -233,10 +237,11 @@
 		ItemAndContext = Item - Context,
 
 		% Discard the item if there were any errors.
-		( NewErrors = [] ->
+        (
+            NewErrors = [],
 			!:ReplItems = [ItemAndContext | !.ReplItems]
 		;
-			true
+            NewErrors = [_ | _]
 		),
 		!:Errors = NewErrors ++ !.Errors
 	;
@@ -249,8 +254,7 @@
 :- pred equiv_type__replace_in_item(module_name::in, item::in,
 	prog_context::in, eqv_map::in, eqv_inst_map::in, item::out,
 	list(eqv_error)::out,
-	maybe(recompilation_info)::in, maybe(recompilation_info)::out)
-	is semidet.
+    maybe(recompilation_info)::in, maybe(recompilation_info)::out) is semidet.
 
 equiv_type__replace_in_item(ModuleName,
 		type_defn(VarSet0, Name, TArgs, TypeDefn0, Cond) @ Item,
@@ -263,9 +267,11 @@
 	equiv_type__replace_in_type_defn(EqvMap, Name - Arity, TypeDefn0,
 		TypeDefn, ContainsCirc, VarSet0, VarSet,
 		UsedTypeCtors0, UsedTypeCtors),
-	( ContainsCirc = yes ->
+    (
+        ContainsCirc = yes,
 		Error = [circular_equivalence(Item) - Context]
 	;
+        ContainsCirc = no,
 		Error = []
 	),
 	equiv_type__finish_recording_expanded_items(
@@ -293,8 +299,7 @@
 	list__length(TypesAndModes, Arity),
 	adjust_func_arity(PredOrFunc, OrigArity, Arity),
 	equiv_type__finish_recording_expanded_items(
-		item_id(ItemType, PredName - OrigArity),
-		ExpandedItems, !Info).
+        item_id(ItemType, PredName - OrigArity), ExpandedItems, !Info).
 
 equiv_type__replace_in_item(ModuleName,
 		pred_or_func_mode(InstVarSet, MaybePredOrFunc0, PredName,
@@ -310,21 +315,23 @@
 		mode_decl, EqvInstMap, MaybePredOrFunc0, MaybePredOrFunc,
 		ExtraModes, WithInst0, WithInst, Det0, Det,
 		ExpandedItems0, ExpandedItems, Errors),
-	( ExtraModes = [] ->
+    (
+        ExtraModes = [],
 		Modes = Modes0
 	;
+        ExtraModes = [_ | _],
 		Modes = Modes0 ++ ExtraModes
 	),
 
-	( MaybePredOrFunc = yes(PredOrFunc) ->
+    (
+        MaybePredOrFunc = yes(PredOrFunc),
 		ItemType = pred_or_func_to_item_type(PredOrFunc),
 		list__length(Modes, Arity),
 		adjust_func_arity(PredOrFunc, OrigArity, Arity),
 		equiv_type__finish_recording_expanded_items(
-			item_id(ItemType, PredName - OrigArity),
-			ExpandedItems, !Info)
+            item_id(ItemType, PredName - OrigArity), ExpandedItems, !Info)
 	;
-		true
+        MaybePredOrFunc = no
 	).
 
 equiv_type__replace_in_item(ModuleName,
@@ -347,14 +354,12 @@
 		Errors = []
 	;
 		ClassInterface0 = concrete(Methods0),
-		equiv_type__replace_in_class_interface(Methods0,
-			EqvMap, EqvInstMap, Methods, [], Errors,
-			ExpandedItems1, ExpandedItems),
+        equiv_type__replace_in_class_interface(Methods0, EqvMap, EqvInstMap,
+            Methods, [], Errors, ExpandedItems1, ExpandedItems),
 		ClassInterface = concrete(Methods)
 	),
 	equiv_type__finish_recording_expanded_items(
-		item_id(typeclass, ClassName - Arity),
-		ExpandedItems, !Info).
+        item_id(typeclass, ClassName - Arity), ExpandedItems, !Info).
 
 equiv_type__replace_in_item(ModuleName,
 		instance(Constraints0, ClassName, Ts0, InstanceBody,
@@ -363,7 +368,11 @@
 		instance(Constraints, ClassName, Ts, InstanceBody,
 			VarSet, ModName),
 		[], !Info) :-
-	( ( !.Info = no ; ModName = ModuleName ) ->
+    (
+        ( !.Info = no
+        ; ModName = ModuleName
+        )
+    ->
 		UsedTypeCtors0 = no
 	;
 		UsedTypeCtors0 = yes(ModuleName - set__init)
@@ -375,8 +384,7 @@
 		VarSet1, VarSet, UsedTypeCtors1, UsedTypeCtors),
 	list__length(Ts0, Arity),
 	equiv_type__finish_recording_expanded_items(
-		item_id(typeclass, ClassName - Arity),
-		UsedTypeCtors, !Info).
+        item_id(typeclass, ClassName - Arity), UsedTypeCtors, !Info).
 
 equiv_type__replace_in_item(ModuleName,
 		pragma(type_spec(PredName, B, Arity, D, E,
@@ -385,7 +393,11 @@
 		pragma(type_spec(PredName, B, Arity, D, E,
 			Subst, VarSet, ItemIds)),
 		[], !Info) :-
-	( ( !.Info = no ; PredName = qualified(ModuleName, _) ) ->
+    (
+        ( !.Info = no
+        ; PredName = qualified(ModuleName, _)
+        )
+    ->
 		ExpandedItems0 = no
 	;
 		ExpandedItems0 = yes(ModuleName - ItemIds0)
@@ -460,8 +472,7 @@
 
 equiv_type__replace_in_class_interface(ClassInterface0, EqvMap, EqvInstMap,
 		ClassInterface, !Errors, !Info) :-
-	list__map_foldl2(
-		equiv_type__replace_in_class_method(EqvMap, EqvInstMap),
+    list__map_foldl2(equiv_type__replace_in_class_method(EqvMap, EqvInstMap),
 		ClassInterface0, ClassInterface, !Errors, !Info).
 
 :- pred equiv_type__replace_in_class_method(eqv_map::in, eqv_inst_map::in,
@@ -480,8 +491,7 @@
 	equiv_type__replace_in_pred_type(PredName, PredOrFunc, Context, EqvMap,
 		EqvInstMap, ClassContext0, ClassContext,
 		TypesAndModes0, TypesAndModes, TypeVarSet0, TypeVarSet,
-		WithType0, WithType, WithInst0, WithInst, Det0, Det,
-		!Info, NewErrors),
+        WithType0, WithType, WithInst0, WithInst, Det0, Det, !Info, NewErrors),
 	!:Errors = NewErrors ++ !.Errors.
 
 equiv_type__replace_in_class_method(_, EqvInstMap,
@@ -492,11 +502,12 @@
 		!Errors, !Info) :-
 	equiv_type__replace_in_pred_mode(PredName, length(Modes0), Context,
 		mode_decl, EqvInstMap, MaybePredOrFunc0, MaybePredOrFunc,
-		ExtraModes, WithInst0, WithInst, Det0, Det, !Info,
-		NewErrors),
-	( ExtraModes = [] ->
+        ExtraModes, WithInst0, WithInst, Det0, Det, !Info, NewErrors),
+    (
+        ExtraModes = [],
 		Modes = Modes0
 	;
+        ExtraModes = [_ | _],
 		Modes = Modes0 ++ ExtraModes
 	),
 	!:Errors = NewErrors ++ !.Errors.
@@ -545,8 +556,8 @@
 
 equiv_type__replace_in_type_list(EqvMap, !Ts, Changed, ContainsCirc,
 		!VarSet, !Info) :-
-	equiv_type__replace_in_type_list_2(EqvMap, [], !Ts,
-		Changed, no, ContainsCirc, !VarSet, !Info).
+    equiv_type__replace_in_type_list_2(EqvMap, [], !Ts, Changed, no,
+        ContainsCirc, !VarSet, !Info).
 
 :- pred equiv_type__replace_in_type_list_2(eqv_map::in, list(type_ctor)::in,
 	list(type)::in, list(type)::out, bool::out, bool::in, bool::out,
@@ -562,7 +573,11 @@
 	!:Circ = ContainsCirc `or` !.Circ,
 	equiv_type__replace_in_type_list_2(EqvMap, Seen, Ts0, Ts,
 		Changed1, !Circ, !VarSet, !Info),
-	( ( Changed0 = yes ; Changed1 = yes ) ->
+    (
+        ( Changed0 = yes
+        ; Changed1 = yes
+        )
+    ->
 		Changed = yes,
 		List = [T | Ts]
 	;
@@ -606,6 +621,7 @@
 
 	% Replace all equivalence types in a given type, detecting
 	% any circularities.
+    %
 :- pred equiv_type__replace_in_type_2(eqv_map::in, list(type_ctor)::in,
 	(type)::in, (type)::out, bool::out, bool::out,
 	tvarset::in, tvarset::out, equiv_type_info::in, equiv_type_info::out)
@@ -630,15 +646,12 @@
 			map__search(EqvMap, EqvTypeCtor,
 				eqv_type_body(EqvVarSet, Args0, Body0)),
 			%
-			% Don't merge in the variable names from the
-			% type declaration to avoid creating multiple
-			% variables with the same name so that
-			% `varset__create_name_var_map' can be used
-			% on the resulting tvarset.
-			% make_hlds.m uses `varset__create_name_var_map' to
-			% match up type variables in `:- pragma type_spec'
-			% declarations and explicit type qualifications
-			% with the type variables in the predicate's
+            % Don't merge in the variable names from the type declaration
+            % to avoid creating multiple variables with the same name so that
+            % `varset__create_name_var_map' can be used on the resulting
+            % tvarset. make_hlds uses `varset__create_name_var_map' to match up
+            % type variables in `:- pragma type_spec' declarations and explicit
+            % type qualifications with the type variables in the predicate's
 			% declaration.
 			%
 			varset__merge_without_names(!.VarSet, EqvVarSet,
@@ -647,11 +660,10 @@
 			Circ1 = no
 		->
 			Changed = yes,
-			equiv_type__record_expanded_item(
-				item_id(type, EqvTypeCtor), !Info),
+            equiv_type__record_expanded_item(item_id(type, EqvTypeCtor),
+                !Info),
 			term__term_list_to_var_list(Args, ArgVars),
-			term__substitute_corresponding(ArgVars, TArgs1,
-							Body, Type1),
+            term__substitute_corresponding(ArgVars, TArgs1, Body, Type1),
 			equiv_type__replace_in_type_2(EqvMap,
 				[EqvTypeCtor | TypeCtorsAlreadyExpanded],
 				Type1, Type, _, Circ, !VarSet, !Info)
@@ -685,9 +697,7 @@
 
 equiv_type__replace_in_inst(Inst0, EqvInstMap, ExpandedInstIds,
 		Inst, !Info) :-
-	(
-		Inst0 = defined_inst(user_inst(SymName, ArgInsts))
-	->
+    ( Inst0 = defined_inst(user_inst(SymName, ArgInsts)) ->
 		InstId = SymName - length(ArgInsts),
 		(
 			set__member(InstId, ExpandedInstIds)
@@ -697,13 +707,10 @@
 			map__search(EqvInstMap, InstId,
 				eqv_inst_body(_, EqvInstParams, EqvInst))
 		->
-			inst_substitute_arg_list(EqvInst, EqvInstParams,
-				ArgInsts, Inst1),
-			equiv_type__record_expanded_item(item_id(inst, InstId),
-				!Info),
+            inst_substitute_arg_list(EqvInst, EqvInstParams, ArgInsts, Inst1),
+            equiv_type__record_expanded_item(item_id(inst, InstId), !Info),
 			equiv_type__replace_in_inst(Inst1, EqvInstMap,
-				set__insert(ExpandedInstIds, InstId), Inst,
-				!Info)
+                set__insert(ExpandedInstIds, InstId), Inst, !Info)
 		;
 			Inst = Inst0
 		)
@@ -720,8 +727,7 @@
 	tvarset::in, tvarset::out,
 	maybe(type)::in, maybe(type)::out, maybe(inst)::in, maybe(inst)::out,
 	maybe(determinism)::in, maybe(determinism)::out,
-	equiv_type_info::in, equiv_type_info::out, list(eqv_error)::out)
-	is det.
+    equiv_type_info::in, equiv_type_info::out, list(eqv_error)::out) is det.
 
 equiv_type__replace_in_pred_type(PredName, PredOrFunc, Context, EqvMap,
 		EqvInstMap, ClassContext0, ClassContext,
@@ -732,7 +738,6 @@
 		ClassContext0, ClassContext, !TypeVarSet, !Info),
 	equiv_type__replace_in_tms(EqvMap, TypesAndModes0,
 		TypesAndModes1, !TypeVarSet, !Info),
-
 	(
 		MaybeWithType0 = yes(WithType0),
 		equiv_type__replace_in_type(EqvMap, WithType0, WithType,
@@ -745,8 +750,7 @@
 			Errors0 = []
 		;
 			ExtraTypes = [],
-			Errors0 = [invalid_with_type(PredName, PredOrFunc)
-					- Context]
+            Errors0 = [invalid_with_type(PredName, PredOrFunc) - Context]
 		)
 	;
 		MaybeWithType0 = no,
@@ -759,7 +763,7 @@
 		MaybeWithInst0, _, Det0, Det, !Info, ModeErrors),
 	Errors1 = Errors0 ++ ModeErrors,
 
-	( Errors1 \= [] ->
+    ( Errors1 = [_ | _] ->
 		Errors = Errors1,
 		ExtraTypesAndModes = []
 	; ExtraModes = [] ->
@@ -768,30 +772,34 @@
 					ExtraTypes)
 	; length(ExtraTypes) `with_type` int = length(ExtraModes) ->
 		Errors = Errors1,
-		assoc_list__from_corresponding_lists(ExtraTypes,
-				ExtraModes, ExtraTypesModes),
+        assoc_list__from_corresponding_lists(ExtraTypes, ExtraModes,
+            ExtraTypesModes),
 		ExtraTypesAndModes = list__map(
 			(func(Type - Mode) = type_and_mode(Type, Mode)),
 			ExtraTypesModes)
 	;
-		Errors = [non_matching_with_type_with_inst(PredName,
-				PredOrFunc) - Context | Errors1],
+        Errors = [non_matching_with_type_with_inst(PredName, PredOrFunc)
+            - Context | Errors1],
 		ExtraTypesAndModes = []
 	),
 
-	( Errors = [] ->
+    (
+        Errors = [],
 		MaybeWithType = no,
 		MaybeWithInst = no
 	;
+        Errors = [_ | _],
 		% Leave the `with_type` and `with_inst` fields so
 		% that make_hlds knows to discard this declaration.
 		MaybeWithType = MaybeWithType0,
 		MaybeWithInst = MaybeWithInst0
 	),
 
-	( ExtraTypesAndModes = [] ->
+    (
+        ExtraTypesAndModes = [],
 		TypesAndModes = TypesAndModes1
 	;
+        ExtraTypesAndModes = [_ | _],
 		OrigItemId = item_id(pred_or_func_to_item_type(PredOrFunc),
 				PredName - list__length(TypesAndModes0)),
 		equiv_type__record_expanded_item(OrigItemId, !Info),
@@ -803,17 +811,14 @@
 	maybe(pred_or_func)::in, maybe(pred_or_func)::out,
 	list(mode)::out, maybe(inst)::in, maybe(inst)::out,
 	maybe(determinism)::in, maybe(determinism)::out,
-	equiv_type_info::in, equiv_type_info::out, list(eqv_error)::out)
-	is det.
+    equiv_type_info::in, equiv_type_info::out, list(eqv_error)::out) is det.
 
 equiv_type__replace_in_pred_mode(PredName, OrigArity, Context, DeclType,
 		EqvInstMap, MaybePredOrFunc0, MaybePredOrFunc, ExtraModes,
-		MaybeWithInst0, MaybeWithInst, Det0, Det,
-		!Info, Errors) :-
+        MaybeWithInst0, MaybeWithInst, Det0, Det, !Info, Errors) :-
 	(
 		MaybeWithInst0 = yes(WithInst0),
-		equiv_type__replace_in_inst(WithInst0, EqvInstMap, WithInst,
-			!Info),
+        equiv_type__replace_in_inst(WithInst0, EqvInstMap, WithInst, !Info),
 		(
 			WithInst = ground(_, higher_order(pred_inst_info(
 				PredOrFunc, ExtraModes0, DetPrime))),
@@ -832,8 +837,7 @@
 			;
 				MaybePredOrFunc0 = yes(RecordedPredOrFunc)
 			),
-			OrigItemId = item_id(
-				pred_or_func_to_item_type(RecordedPredOrFunc),
+            OrigItemId = item_id(pred_or_func_to_item_type(RecordedPredOrFunc),
 				PredName - OrigArity),
 			equiv_type__record_expanded_item(OrigItemId, !Info)
 		;
@@ -843,8 +847,8 @@
 			% knows to discard this declaration.
 			MaybeWithInst = MaybeWithInst0,
 			Det = Det0,
-			Errors = [invalid_with_inst(DeclType, PredName,
-					MaybePredOrFunc0) - Context]
+            Errors = [invalid_with_inst(DeclType, PredName, MaybePredOrFunc0)
+                - Context]
 		)
 	;
 		MaybeWithInst0 = no,
@@ -861,8 +865,7 @@
 	is det.
 
 equiv_type__replace_in_tms(EqvMap, !TMs, !VarSet, !Info) :-
-	list__map_foldl2(equiv_type__replace_in_tm(EqvMap),
-		!TMs, !VarSet, !Info).
+    list__map_foldl2(equiv_type__replace_in_tm(EqvMap), !TMs, !VarSet, !Info).
 
 :- pred equiv_type__replace_in_tm(eqv_map::in,
 	type_and_mode::in, type_and_mode::out, tvarset::in, tvarset::out,
@@ -881,8 +884,8 @@
 :- type expanded_item_set == pair(module_name, set(item_id)).
 
 equiv_type__maybe_record_expanded_items(_, _, no, no).
-equiv_type__maybe_record_expanded_items(ModuleName, SymName,
-		yes(_), MaybeInfo) :-
+equiv_type__maybe_record_expanded_items(ModuleName, SymName, yes(_),
+        MaybeInfo) :-
 	( SymName = qualified(ModuleName, _) ->
 		MaybeInfo = no
 	;
@@ -927,25 +930,23 @@
 		Item = type_defn(_, SymName, Params, TypeDefn, _),
 		TypeDefn = eqv_type(_)
 	->
-		Pieces = append_punctuation([
-			words("Error: circular equivalence type"),
-			fixed(error_util__describe_sym_name_and_arity(
-				SymName / length(Params)))
-			], '.'),
-		error_util__write_error_pieces(Context, 0, Pieces, !IO)
+        Pieces = [words("Error: circular equivalence type"),
+            fixed(describe_sym_name_and_arity(SymName / length(Params))),
+            suffix(".")],
+        write_error_pieces(Context, 0, Pieces, !IO)
 	;
-		error("equiv_type__report_error: invalid item")
+        unexpected(this_file, "equiv_type__report_error: invalid item")
 	).
 equiv_type__report_error(invalid_with_type(SymName, PredOrFunc) - Context,
 		!IO) :-
-	FirstLine = append_punctuation([words("In type declaration for"),
+    Pieces = [words("In type declaration for"),
 			words(error_util__pred_or_func_to_string(PredOrFunc)),
-			fixed(error_util__describe_sym_name(SymName))
-		], ':'),
-	Rest = [nl, words("error: expected higher order"),
+        fixed(error_util__describe_sym_name(SymName)),
+        suffix(":"), nl,
+        words("error: expected higher order"),
 			words(error_util__pred_or_func_to_string(PredOrFunc)),
 			words("type after `with_type`.")],
-	error_util__write_error_pieces(Context, 0, FirstLine ++ Rest, !IO).
+    write_error_pieces(Context, 0, Pieces, !IO).
 equiv_type__report_error(invalid_with_inst(DeclType, SymName, MaybePredOrFunc)
 		- Context, !IO) :-
 	( DeclType = type_decl, DeclStr = "declaration"
@@ -957,25 +958,26 @@
 		MaybePredOrFunc = yes(PredOrFunc),
 		PredOrFuncStr = error_util__pred_or_func_to_string(PredOrFunc)
 	),
-	FirstLine = append_punctuation([words("In"), words(DeclStr),
-			words("for"),
-			words(PredOrFuncStr),
-			fixed(error_util__describe_sym_name(SymName))
-		], ':'),
-	Rest = [nl, words("error: expected higher order "),
+    Pieces = [words("In"), words(DeclStr), words("for"),
 		words(PredOrFuncStr),
+        fixed(error_util__describe_sym_name(SymName)), suffix(":"), nl,
+        words("error: expected higher order "), words(PredOrFuncStr),
 		words("inst after `with_inst`.")],
-	error_util__write_error_pieces(Context, 0, FirstLine ++ Rest, !IO).
+    write_error_pieces(Context, 0, Pieces, !IO).
 equiv_type__report_error(non_matching_with_type_with_inst(SymName, PredOrFunc)
 		- Context, !IO) :-
-	FirstLine = append_punctuation([words("In type declaration for"),
+    Pieces = [words("In type declaration for"),
 			words(error_util__pred_or_func_to_string(PredOrFunc)),
-			fixed(error_util__describe_sym_name(SymName))
-		], ':'),
-	Rest = [nl,
+        fixed(error_util__describe_sym_name(SymName)),
+        suffix(":"), nl,
 		words("error: the `with_type` and `with_inst`"),
 		words("annotations are incompatible.")],
-	error_util__write_error_pieces(Context, 0, FirstLine ++ Rest, !IO).
+    write_error_pieces(Context, 0, Pieces, !IO).
 
 %-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "equiv_type.m".
+
 %-----------------------------------------------------------------------------%
Index: compiler/equiv_type_hlds.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/equiv_type_hlds.m,v
retrieving revision 1.16
diff -u -b -r1.16 equiv_type_hlds.m
--- compiler/equiv_type_hlds.m	16 Aug 2005 15:36:15 -0000	1.16
+++ compiler/equiv_type_hlds.m	28 Aug 2005 01:58:52 -0000
@@ -637,7 +637,7 @@
     (
         Changed = yes,
         !:Info = (!.Info ^ tvarset := TVarSet) ^ inst_cache := Cache,
-        goal_info_set_instmap_delta(GoalInfo0, InstMapDelta, GoalInfo),
+        goal_info_set_instmap_delta(InstMapDelta, GoalInfo0, GoalInfo),
         Goal = GoalExpr - GoalInfo
     ;
         Changed = no,
@@ -768,8 +768,8 @@
             ^ module_info := ModuleInfo)
             ^ tvarset := TVarSet,
 
-        goal_util__rename_vars_in_goals(Goals0, no,
-            map__from_assoc_list([TypeInfoVar - Var]), Goals),
+        goal_util__rename_vars_in_goals(no,
+            map__from_assoc_list([TypeInfoVar - Var]), Goals0, Goals),
         ( Goals = [Goal1 - _] ->
             Goal = Goal1
         ;
Index: compiler/error_util.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/error_util.m,v
retrieving revision 1.42
diff -u -b -r1.42 error_util.m
--- compiler/error_util.m	22 Aug 2005 03:55:10 -0000	1.42
+++ compiler/error_util.m	28 Aug 2005 13:19:27 -0000
@@ -41,7 +41,6 @@
 :- import_module parse_tree__prog_data.
 
 :- import_module bool.
-:- import_module char.
 :- import_module io.
 :- import_module list.
 :- import_module std_util.
@@ -212,12 +211,6 @@
 
 :- func pred_or_func_to_string(pred_or_func) = string.
 
-    % Append a punctuation character to a message, avoiding unwanted
-    % line splitting between the message and the punctuation.
-    %
-:- func append_punctuation(list(format_component), char) =
-    list(format_component).
-
     % Put `' quotes around the given string.
     %
 :- func add_quotes(string) = string.
@@ -326,28 +319,25 @@
     [fixed(Elem1 ++ ",") | list_to_pieces([Elem2, Elem3 | Elems])].
 
 component_lists_to_pieces([]) = [].
-component_lists_to_pieces([Components]) = Components.
-component_lists_to_pieces([Components1, Components2]) =
-        list__condense([Components1, [words("and")], Components2]).
-component_lists_to_pieces(
-        [Components1, Components2, Components3 | Components]) =
-    list__append(append_punctuation(Components1, ','),
-        component_lists_to_pieces([Components2, Components3 | Components])).
+component_lists_to_pieces([Comps]) = Comps.
+component_lists_to_pieces([Comps1, Comps2]) =
+    Comps1 ++ [words("and")] ++ Comps2.
+component_lists_to_pieces([Comps1, Comps2, Comps3 | Comps]) =
+    Comps1 ++ [suffix(",")]
+    ++ component_lists_to_pieces([Comps2, Comps3 | Comps]).
 
 component_list_to_pieces([]) = [].
-component_list_to_pieces([Component]) = [Component].
-component_list_to_pieces([Component1, Component2]) =
-        [Component1, words("and"), Component2].
-component_list_to_pieces(
-        [Component1, Component2, Component3 | Components]) =
-    list__append(append_punctuation([Component1], ','),
-        component_list_to_pieces([Component2, Component3 | Components])).
+component_list_to_pieces([Comp]) = [Comp].
+component_list_to_pieces([Comp1, Comp2]) = [Comp1, words("and"), Comp2].
+component_list_to_pieces([Comp1, Comp2, Comp3 | Comps]) =
+    [Comp1, suffix(",")]
+    ++ component_list_to_pieces([Comp2, Comp3 | Comps]).
 
 component_list_to_line_pieces([]) = [].
-component_list_to_line_pieces([Components]) = Components ++ [nl].
-component_list_to_line_pieces([Components1, Components2 | ComponentLists]) =
-    list__append(Components1 ++ [suffix(","), nl],
-        component_list_to_line_pieces([Components2 | ComponentLists])).
+component_list_to_line_pieces([Comps]) = Comps ++ [nl].
+component_list_to_line_pieces([Comps1, Comps2 | CompLists]) =
+    Comps1 ++ [suffix(","), nl]
+    ++ component_list_to_line_pieces([Comps2 | CompLists]).
 
 choose_number([], _Singular, Plural) = Plural.
 choose_number([_], Singular, _Plural) = Singular.
@@ -648,9 +638,8 @@
 :- func sym_name_and_arity_to_word(sym_name_and_arity) = string.
 
 sym_name_and_arity_to_word(SymName / Arity) =
-        "`" ++ SymStr ++ "'/" ++ ArityStr :-
-    sym_name_to_string(SymName, SymStr),
-    string__int_to_string(Arity, ArityStr).
+        "`" ++ sym_name_to_string(SymName) ++ "'"
+        ++ "/" ++ int_to_string(Arity).
 
 :- pred break_into_words(string::in, list(word)::in, list(word)::out) is det.
 
@@ -798,50 +787,6 @@
 
 pred_or_func_to_string(predicate) = "predicate".
 pred_or_func_to_string(function) = "function".
-
-append_punctuation([], _) = _ :-
-    error("append_punctuation: appending punctuation after nothing").
-append_punctuation([Piece0], Punc) = [Piece] :-
-    % Avoid unwanted line splitting between the message and the punctuation.
-    (
-        Piece0 = words(String),
-        Piece = words(string__append(String, char_to_string(Punc)))
-    ;
-        Piece0 = fixed(String),
-        Piece = fixed(string__append(String, char_to_string(Punc)))
-    ;
-        Piece0 = prefix(Prefix),
-        Piece = prefix(string__append(Prefix, char_to_string(Punc)))
-    ;
-        Piece0 = suffix(Suffix),
-        Piece = suffix(string__append(Suffix, char_to_string(Punc)))
-    ;
-        Piece0 = sym_name(SymName),
-        String = sym_name_to_word(SymName),
-        Piece = fixed(string__append(String, char_to_string(Punc)))
-    ;
-        Piece0 = sym_name_and_arity(SymNameAndArity),
-        String = sym_name_and_arity_to_word(SymNameAndArity),
-        Piece = fixed(string__append(String, char_to_string(Punc)))
-    ;
-        Piece0 = pred_or_func(PredOrFunc),
-        String = pred_or_func_to_string(PredOrFunc),
-        Piece = fixed(string__append(String, char_to_string(Punc)))
-    ;
-        Piece0 = simple_call_id(SimpleCallId),
-        String = simple_call_id_to_string(SimpleCallId),
-        Piece = words(string__append(String, char_to_string(Punc)))
-    ;
-        Piece0 = nl,
-        unexpected(this_file,
-            "append_punctutation: appending punctuation after nl")
-    ;
-        Piece0 = nl_indent_delta(_),
-        unexpected(this_file,
-            "append_punctutation: appending punctuation after nl_indent_delta")
-    ).
-append_punctuation([Piece1, Piece2 | Pieces], Punc) =
-    [Piece1 | append_punctuation([Piece2 | Pieces], Punc)].
 
 add_quotes(Str) = "`" ++ Str ++ "'".
 
Index: compiler/follow_vars.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/follow_vars.m,v
retrieving revision 1.72
diff -u -b -r1.72 follow_vars.m
--- compiler/follow_vars.m	12 Aug 2005 05:14:09 -0000	1.72
+++ compiler/follow_vars.m	28 Aug 2005 05:17:49 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1994-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -65,14 +67,14 @@
 :- import_module require.
 :- import_module set.
 :- import_module std_util.
+:- import_module svmap.
 
 %-----------------------------------------------------------------------------%
 
 find_final_follow_vars(ProcInfo, FollowVarsMap, NextNonReserved) :-
 	proc_info_arg_info(ProcInfo, ArgInfo),
 	proc_info_headvars(ProcInfo, HeadVars),
-	assoc_list__from_corresponding_lists(ArgInfo, HeadVars,
-		ArgInfoHeadVars),
+    assoc_list__from_corresponding_lists(ArgInfo, HeadVars, ArgInfoHeadVars),
 	map__init(FollowVarsMap0),
 	find_final_follow_vars_2(ArgInfoHeadVars,
 		FollowVarsMap0, FollowVarsMap, 1, NextNonReserved).
@@ -86,13 +88,12 @@
 		!FollowVarsMap, !NextNonReserved) :-
 	( Mode = top_out ->
 		Locn = abs_reg(RegNum),
-		map__det_insert(!.FollowVarsMap, Var, Locn, !:FollowVarsMap),
+        svmap__det_insert(Var, Locn, !FollowVarsMap),
 		int__max(RegNum + 1, !NextNonReserved)
 	;
 		true
 	),
-	find_final_follow_vars_2(ArgInfoVars, !FollowVarsMap,
-		!NextNonReserved).
+    find_final_follow_vars_2(ArgInfoVars, !FollowVarsMap, !NextNonReserved).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
@@ -129,7 +130,7 @@
 
 find_follow_vars_in_goal_expr(disj(Goals0), disj(Goals), GoalInfo0, GoalInfo,
 		VarTypes, ModuleInfo, !FollowVarsMap, !NextNonReserved) :-
-	goal_info_set_store_map(GoalInfo0, !.FollowVarsMap, GoalInfo),
+    goal_info_set_store_map(!.FollowVarsMap, GoalInfo0, GoalInfo),
 	find_follow_vars_in_disj(Goals0, Goals, VarTypes, ModuleInfo,
 		!FollowVarsMap, !NextNonReserved).
 
@@ -146,7 +147,7 @@
 		switch(Var, Det, Cases), GoalInfo0, GoalInfo,
 		VarTypes, ModuleInfo,
 		!FollowVarsMap, !NextNonReserved) :-
-	goal_info_set_store_map(GoalInfo0, !.FollowVarsMap, GoalInfo),
+    goal_info_set_store_map(!.FollowVarsMap, GoalInfo0, GoalInfo),
 	find_follow_vars_in_cases(Cases0, Cases, VarTypes, ModuleInfo,
 		!FollowVarsMap, !NextNonReserved).
 
@@ -178,23 +179,23 @@
 		NextNonReserved0, NextNonReservedThen),
 	FollowVarsThen =
 		abs_follow_vars(FollowVarsMapThen, NextNonReservedThen),
-	goal_set_follow_vars(Then1, yes(FollowVarsThen), Then),
+    goal_set_follow_vars(yes(FollowVarsThen), Then1, Then),
 
 	find_follow_vars_in_goal(Cond0, Cond1, VarTypes, ModuleInfo,
 		FollowVarsMapThen, FollowVarsMapCond,
 		NextNonReservedThen, NextNonReservedCond),
 	FollowVarsCond =
 		abs_follow_vars(FollowVarsMapCond, NextNonReservedCond),
-	goal_set_follow_vars(Cond1, yes(FollowVarsCond), Cond),
+    goal_set_follow_vars(yes(FollowVarsCond), Cond1, Cond),
 
 	find_follow_vars_in_goal(Else0, Else1, VarTypes, ModuleInfo,
 		FollowVarsMap0, FollowVarsMapElse,
 		NextNonReserved0, NextNonReservedElse),
 	FollowVarsElse =
 		abs_follow_vars(FollowVarsMapElse, NextNonReservedElse),
-	goal_set_follow_vars(Else1, yes(FollowVarsElse), Else),
+    goal_set_follow_vars(yes(FollowVarsElse), Else1, Else),
 
-	goal_info_set_store_map(GoalInfo0, FollowVarsMap0, GoalInfo).
+    goal_info_set_store_map(FollowVarsMap0, GoalInfo0, GoalInfo).
 
 find_follow_vars_in_goal_expr(scope(Reason, Goal0), scope(Reason, Goal),
 		GoalInfo, GoalInfo, VarTypes, ModuleInfo,
@@ -209,7 +210,7 @@
 		Unify = assign(LVar, RVar),
 		map__search(!.FollowVarsMap, LVar, DesiredLoc)
 	->
-		map__set(!.FollowVarsMap, RVar, DesiredLoc, !:FollowVarsMap)
+        svmap__set(RVar, DesiredLoc, !FollowVarsMap)
 	;
 		true
 	).
@@ -276,10 +277,7 @@
 		!FollowVarsMap, !NextNonReserved) :-
 	( Mode = top_in ->
 		Locn = abs_reg(RegNum),
-		(
-			map__insert(!.FollowVarsMap, ArgVar, Locn,
-				!:FollowVarsMap)
-		->
+        ( svmap__insert(ArgVar, Locn, !FollowVarsMap) ->
 			true	% FollowVarsMap is updated
 		;
 			% The call is not in superhomogeneous form: this
@@ -355,7 +353,7 @@
 		FollowVarsMap0, FollowVarsMap,
 		NextNonReserved0, NextNonReserved),
 	FollowVars = abs_follow_vars(FollowVarsMap, NextNonReserved),
-	goal_set_follow_vars(Goal1, yes(FollowVars), Goal),
+    goal_set_follow_vars(yes(FollowVars), Goal1, Goal),
 	find_follow_vars_in_disj(Goals0, Goals, VarTypes, ModuleInfo,
 		FollowVarsMap0, _FollowVarsMap,
 		NextNonReserved0, _NextNonReserved).
@@ -387,7 +385,7 @@
 		FollowVarsMap0, FollowVarsMap,
 		NextNonReserved0, NextNonReserved),
 	FollowVars = abs_follow_vars(FollowVarsMap, NextNonReserved),
-	goal_set_follow_vars(Goal1, yes(FollowVars), Goal),
+    goal_set_follow_vars(yes(FollowVars), Goal1, Goal),
 	find_follow_vars_in_cases(Goals0, Goals, VarTypes, ModuleInfo,
 		FollowVarsMap0, _FollowVarsMap,
 		NextNonReserved, _NextNonReserved).
@@ -404,9 +402,8 @@
 
 find_follow_vars_in_conj([], [], _, _ModuleInfo, _AttachToFirst,
 		!FollowVarsMap, !NextNonReserved).
-find_follow_vars_in_conj([Goal0 | Goals0], [Goal | Goals],
-		VarTypes, ModuleInfo, AttachToFirst,
-		!FollowVarsMap, !NextNonReserved) :-
+find_follow_vars_in_conj([Goal0 | Goals0], [Goal | Goals], VarTypes,
+        ModuleInfo, AttachToFirst, !FollowVarsMap, !NextNonReserved) :-
 	(
 		Goal0 = GoalExpr0 - _,
 		(
@@ -427,9 +424,8 @@
 		!FollowVarsMap, !NextNonReserved),
 	(
 		AttachToFirst = yes,
-		FollowVars =
-			abs_follow_vars(!.FollowVarsMap, !.NextNonReserved),
-		goal_set_follow_vars(Goal1, yes(FollowVars), Goal)
+        FollowVars = abs_follow_vars(!.FollowVarsMap, !.NextNonReserved),
+        goal_set_follow_vars(yes(FollowVars), Goal1, Goal)
 	;
 		AttachToFirst = no,
 		Goal = Goal1
Index: compiler/goal_path.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/goal_path.m,v
retrieving revision 1.25
diff -u -b -r1.25 goal_path.m
--- compiler/goal_path.m	23 May 2005 03:15:34 -0000	1.25
+++ compiler/goal_path.m	27 Aug 2005 16:56:32 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1997-2005 University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -24,7 +26,7 @@
 	% and the polymorphism pass.  For this reason, goal paths should not
 	% be recalculated anywhere between these two passes.  See the XXX
 	% comment near the declaration of constraint_id.
-
+    %
 :- pred goal_path__fill_slots(module_info::in, proc_info::in, proc_info::out)
 	is det.
 
@@ -36,7 +38,7 @@
 	% mode analysis where the instantiatedness of a variable at such a goal
 	% path is always equivalent to its instantiatedness at the parent goal
 	% path.
-
+    %
 :- pred goal_path__fill_slots_in_clauses(module_info::in, bool::in,
 	pred_info::in, pred_info::out) is det.
 
@@ -48,6 +50,7 @@
 :- import_module check_hlds__type_util.
 :- import_module hlds__hlds_data.
 :- import_module hlds__hlds_goal.
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__prog_data.
 
 :- import_module char.
@@ -75,8 +78,7 @@
 	clauses_info_clauses_only(ClausesInfo0, Clauses0),
 	clauses_info_vartypes(ClausesInfo0, VarTypes),
 	SlotInfo = slot_info(VarTypes, ModuleInfo, OmitModeEquivPrefix),
-	list__map_foldl(fill_slots_in_clause(SlotInfo), Clauses0, Clauses,
-		1, _),
+    list__map_foldl(fill_slots_in_clause(SlotInfo), Clauses0, Clauses, 1, _),
 	clauses_info_set_clauses(Clauses, ClausesInfo0, ClausesInfo),
 	pred_info_set_clauses_info(ClausesInfo, !PredInfo).
 
@@ -85,17 +87,17 @@
 
 fill_slots_in_clause(SlotInfo, Clause0, Clause, ClauseNum, ClauseNum + 1) :-
 	Clause0 = clause(ProcIds, Goal0, Lang, Context),
-	fill_goal_slots(Goal0, [disj(ClauseNum)], SlotInfo, Goal),
+    fill_goal_slots([disj(ClauseNum)], SlotInfo, Goal0, Goal),
 	Clause = clause(ProcIds, Goal, Lang, Context).
 
 goal_path__fill_slots_in_goal(Goal0, VarTypes, ModuleInfo, Goal) :-
 	SlotInfo = slot_info(VarTypes, ModuleInfo, no),
-	fill_goal_slots(Goal0, [], SlotInfo, Goal).
+    fill_goal_slots([], SlotInfo, Goal0, Goal).
 
-:- pred fill_goal_slots(hlds_goal::in, goal_path::in, slot_info::in,
-	hlds_goal::out) is det.
+:- pred fill_goal_slots(goal_path::in, slot_info::in,
+    hlds_goal::in, hlds_goal::out) is det.
 
-fill_goal_slots(Expr0 - Info0, Path0, SlotInfo, Expr - Info) :-
+fill_goal_slots(Path0, SlotInfo, Expr0 - Info0, Expr - Info) :-
 	OmitModeEquivPrefix = SlotInfo ^ omit_mode_equiv_prefix,
 	(
 		OmitModeEquivPrefix = yes,
@@ -104,8 +106,8 @@
 		OmitModeEquivPrefix = no,
 		Path = Path0
 	),
-	goal_info_set_goal_path(Info0, Path, Info),
-	fill_expr_slots(Expr0, Info, Path0, SlotInfo, Expr).
+    goal_info_set_goal_path(Path, Info0, Info),
+    fill_expr_slots(Info, Path0, SlotInfo, Expr0, Expr).
 
 :- pred mode_equiv_step(goal_path_step::in) is semidet.
 
@@ -116,89 +118,115 @@
 	; Step = ite_else
 	).
 
-:- pred fill_expr_slots(hlds_goal_expr::in, hlds_goal_info::in, goal_path::in,
-	slot_info::in, hlds_goal_expr::out) is det.
+:- pred fill_expr_slots(hlds_goal_info::in, goal_path::in, slot_info::in,
+    hlds_goal_expr::in, hlds_goal_expr::out) is det.
 
-fill_expr_slots(conj(Goals0), _, Path0, SlotInfo, conj(Goals)) :-
-	fill_conj_slots(Goals0, Path0, 0, SlotInfo, Goals).
-fill_expr_slots(par_conj(Goals0), _, Path0, SlotInfo,
-		par_conj(Goals)) :-
-	fill_conj_slots(Goals0, Path0, 0, SlotInfo, Goals).
-fill_expr_slots(disj(Goals0), _, Path0, SlotInfo, disj(Goals)) :-
-	fill_disj_slots(Goals0, Path0, 0, SlotInfo, Goals).
-fill_expr_slots(switch(Var, B, Cases0), _, Path0, SlotInfo,
-		switch(Var, B, Cases)) :-
+fill_expr_slots(GoalInfo, Path0, SlotInfo, Goal0, Goal) :-
+    (
+        Goal0 = conj(Goals0),
+        fill_conj_slots(Path0, 0, SlotInfo, Goals0, Goals),
+        Goal = conj(Goals)
+    ;
+        Goal0 = par_conj(Goals0),
+        fill_conj_slots(Path0, 0, SlotInfo, Goals0, Goals),
+        Goal = par_conj(Goals)
+    ;
+        Goal0 = disj(Goals0),
+        fill_disj_slots(Path0, 0, SlotInfo, Goals0, Goals),
+        Goal = disj(Goals)
+    ;
+        Goal0 = switch(Var, CanFail, Cases0),
 	VarTypes = SlotInfo ^ vartypes,
 	ModuleInfo = SlotInfo ^ module_info,
 	map__lookup(VarTypes, Var, Type),
-	(
-		type_util__switch_type_num_functors(ModuleInfo, Type,
-			NumFunctors)
-	->
+        ( switch_type_num_functors(ModuleInfo, Type, NumFunctors) ->
 		NumCases = NumFunctors
 	;
 		NumCases = -1
 	),
-	fill_switch_slots(Cases0, Path0, 0, NumCases, SlotInfo, Cases).
-fill_expr_slots(not(Goal0), _, Path0, SlotInfo, not(Goal)) :-
-	fill_goal_slots(Goal0, [neg | Path0], SlotInfo, Goal).
-fill_expr_slots(scope(Reason, Goal0), OuterInfo, Path0, SlotInfo,
-		scope(Reason, Goal)) :-
-	Goal0 = _ - InnerInfo,
-	goal_info_get_determinism(OuterInfo, OuterDetism),
+        fill_switch_slots(Path0, 0, NumCases, SlotInfo, Cases0, Cases),
+        Goal = switch(Var, CanFail, Cases)
+    ;
+        Goal0 = not(SubGoal0),
+        fill_goal_slots([neg | Path0], SlotInfo, SubGoal0, SubGoal),
+        Goal = not(SubGoal)
+    ;
+        Goal0 = scope(Reason, SubGoal0),
+        SubGoal0 = _ - InnerInfo,
+        goal_info_get_determinism(GoalInfo, OuterDetism),
 	goal_info_get_determinism(InnerInfo, InnerDetism),
 	( InnerDetism = OuterDetism ->
 		MaybeCut = no_cut
 	;
 		MaybeCut = cut
 	),
-	fill_goal_slots(Goal0, [scope(MaybeCut) | Path0], SlotInfo, Goal).
-fill_expr_slots(if_then_else(A, Cond0, Then0, Else0), _, Path0, SlotInfo,
-		if_then_else(A, Cond, Then, Else)) :-
-	fill_goal_slots(Cond0, [ite_cond | Path0], SlotInfo, Cond),
-	fill_goal_slots(Then0, [ite_then | Path0], SlotInfo, Then),
-	fill_goal_slots(Else0, [ite_else | Path0], SlotInfo, Else).
-fill_expr_slots(unify(LHS, RHS0, Mode, Kind, Context), _, Path0, SlotInfo,
-		unify(LHS, RHS,  Mode, Kind, Context)) :-
+        fill_goal_slots([scope(MaybeCut) | Path0], SlotInfo,
+            SubGoal0, SubGoal),
+        Goal = scope(Reason, SubGoal)
+    ;
+        Goal0 = if_then_else(A, Cond0, Then0, Else0),
+        fill_goal_slots([ite_cond | Path0], SlotInfo, Cond0, Cond),
+        fill_goal_slots([ite_then | Path0], SlotInfo, Then0, Then),
+        fill_goal_slots([ite_else | Path0], SlotInfo, Else0, Else),
+        Goal = if_then_else(A, Cond, Then, Else)
+    ;
+        Goal0 = unify(LHS, RHS0, Mode, Kind, Context),
 	(
 		RHS0 = lambda_goal(A, B, C, D, E, F, G, H, LambdaGoal0)
 	->
-		fill_goal_slots(LambdaGoal0, Path0, SlotInfo, LambdaGoal),
+            fill_goal_slots(Path0, SlotInfo, LambdaGoal0, LambdaGoal),
 		RHS = lambda_goal(A, B, C, D, E, F, G, H, LambdaGoal)
 	;
 		RHS = RHS0
+        ),
+        Goal = unify(LHS, RHS,  Mode, Kind, Context)
+    ;
+        Goal0 = call(_, _, _, _, _, _),
+        Goal = Goal0
+    ;
+        Goal0 = generic_call(_, _, _, _),
+        Goal = Goal0
+    ;
+        Goal0 = foreign_proc(_, _, _, _, _, _),
+        Goal = Goal0
+    ;
+        Goal0 = shorthand(_),
+        % These should have been expanded out by now.
+        unexpected(this_file, "fill_expr_slots: unexpected shorthand")
 	).
-fill_expr_slots(Goal @ call(_, _, _, _, _, _), _, _, _, Goal).
-fill_expr_slots(Goal @ generic_call(_, _, _, _), _, _, _, Goal).
-fill_expr_slots(Goal @ foreign_proc(_, _, _, _, _, _), _, _, _, Goal).
-fill_expr_slots(shorthand(_), _, _, _, _) :-
-	% these should have been expanded out by now
-	error("fill_expr_slots: unexpected shorthand").
 
-:- pred fill_conj_slots(list(hlds_goal)::in, goal_path::in, int::in,
-	slot_info::in, list(hlds_goal)::out) is det.
+:- pred fill_conj_slots(goal_path::in, int::in, slot_info::in,
+    list(hlds_goal)::in, list(hlds_goal)::out) is det.
 
-fill_conj_slots([], _, _, _, []).
-fill_conj_slots([Goal0 | Goals0], Path0, N0, SlotInfo, [Goal | Goals]) :-
+fill_conj_slots(_, _, _, [], []).
+fill_conj_slots(Path0, N0, SlotInfo, [Goal0 | Goals0], [Goal | Goals]) :-
 	N1 = N0 + 1,
-	fill_goal_slots(Goal0, [conj(N1) | Path0], SlotInfo, Goal),
-	fill_conj_slots(Goals0, Path0, N1, SlotInfo, Goals).
+    fill_goal_slots([conj(N1) | Path0], SlotInfo, Goal0, Goal),
+    fill_conj_slots(Path0, N1, SlotInfo, Goals0, Goals).
 
-:- pred fill_disj_slots(list(hlds_goal)::in, goal_path::in, int::in,
-	slot_info::in, list(hlds_goal)::out) is det.
+:- pred fill_disj_slots(goal_path::in, int::in, slot_info::in,
+    list(hlds_goal)::in, list(hlds_goal)::out) is det.
 
-fill_disj_slots([], _, _, _, []).
-fill_disj_slots([Goal0 | Goals0], Path0, N0, SlotInfo, [Goal | Goals]) :-
+fill_disj_slots(_, _, _, [], []).
+fill_disj_slots(Path0, N0, SlotInfo, [Goal0 | Goals0], [Goal | Goals]) :-
 	N1 = N0 + 1,
-	fill_goal_slots(Goal0, [disj(N1) | Path0], SlotInfo, Goal),
-	fill_disj_slots(Goals0, Path0, N1, SlotInfo, Goals).
+    fill_goal_slots([disj(N1) | Path0], SlotInfo, Goal0, Goal),
+    fill_disj_slots(Path0, N1, SlotInfo, Goals0, Goals).
 
-:- pred fill_switch_slots(list(case)::in, goal_path::in, int::in, int::in,
-	slot_info::in, list(case)::out) is det.
+:- pred fill_switch_slots(goal_path::in, int::in, int::in, slot_info::in,
+    list(case)::in, list(case)::out) is det.
 
-fill_switch_slots([], _, _, _, _, []).
-fill_switch_slots([case(A, Goal0) | Cases0], Path0, N0, NumCases, SlotInfo,
-		[case(A, Goal) | Cases]) :-
+fill_switch_slots(_, _, _, _, [], []).
+fill_switch_slots(Path0, N0, NumCases, SlotInfo,
+        [case(A, Goal0) | Cases0], [case(A, Goal) | Cases]) :-
 	N1 = N0 + 1,
-	fill_goal_slots(Goal0, [switch(N1, NumCases) | Path0], SlotInfo, Goal),
-	fill_switch_slots(Cases0, Path0, N1, NumCases, SlotInfo, Cases).
+    fill_goal_slots([switch(N1, NumCases) | Path0], SlotInfo, Goal0, Goal),
+    fill_switch_slots(Path0, N1, NumCases, SlotInfo, Cases0, Cases).
+
+%-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "goal_path.m".
+
+%-----------------------------------------------------------------------------%
Index: compiler/goal_util.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/goal_util.m,v
retrieving revision 1.111
diff -u -b -r1.111 goal_util.m
--- compiler/goal_util.m	16 Aug 2005 15:36:15 -0000	1.111
+++ compiler/goal_util.m	28 Aug 2005 05:18:51 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1995-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -28,6 +30,8 @@
 :- import_module set.
 :- import_module term.
 
+:- type prog_var_renaming == map(prog_var, prog_var).
+
 	% create_renaming(OutputVars, InstMapDelta, !VarTypes, !VarSet,
 	%	UnifyGoals, NewVars, Renaming):
 	%
@@ -39,11 +43,11 @@
 	% VarTypes and Varset are updated for the new variables. The final
 	% insts of NewVar are taken from the insts of the corresponding
 	% OutputVar in InstMapDelta (the initial inst is free).
-
+    %
 :- pred create_renaming(list(prog_var)::in, instmap_delta::in,
 	vartypes::in, vartypes::out, prog_varset::in, prog_varset::out,
 	list(hlds_goal)::out, list(prog_var)::out,
-	map(prog_var, prog_var)::out) is det.
+    prog_var_renaming::out) is det.
 
 % The predicates rename_var* take a structure and a mapping from var -> var
 % and apply that translation. If a var in the input structure does not
@@ -51,98 +55,105 @@
 
 	% goal_util__rename_vars_in_goals(GoalList, MustRename, Substitution,
 	%	NewGoalList).
-:- pred goal_util__rename_vars_in_goals(list(hlds_goal)::in, bool::in,
-	map(prog_var, prog_var)::in, list(hlds_goal)::out) is det.
+:- pred goal_util__rename_vars_in_goals(bool::in, prog_var_renaming::in,
+    list(hlds_goal)::in, list(hlds_goal)::out) is det.
 
-:- pred goal_util__rename_vars_in_goal(hlds_goal::in,
-	map(prog_var, prog_var)::in, hlds_goal::out) is det.
+:- pred goal_util__rename_vars_in_goal(prog_var_renaming::in,
+    hlds_goal::in, hlds_goal::out) is det.
 
-:- pred goal_util__must_rename_vars_in_goal(hlds_goal::in,
-	map(prog_var, prog_var)::in, hlds_goal::out) is det.
+:- pred goal_util__must_rename_vars_in_goal(prog_var_renaming::in,
+    hlds_goal::in, hlds_goal::out) is det.
 
-:- pred goal_util__rename_vars_in_var_set(set(prog_var)::in, bool::in,
-	map(prog_var, prog_var)::in, set(prog_var)::out) is det.
-
-:- pred goal_util__rename_var_list(list(var(T))::in, bool::in,
-	map(var(T), var(T))::in, list(var(T))::out) is det.
-
-:- pred goal_util__rename_var(var(V)::in, bool::in, map(var(V), var(V))::in,
-	var(V)::out) is det.
-
-% goal_util__create_variables takes a list of variables, a varset, and map
-% from vars to types and an initial substitution, and creates new instances
-% of each of the source variables in the substitution, adding each new
-% variable to the varset and the var types map. The name and type of each new
-% variable is found by looking up
-% in the type map given in the 5th argument - the last input.
-% (This interface will not easily admit uniqueness in the type map for this
-% reason - such is the sacrifice for generality.)
+:- pred goal_util__rename_vars_in_var_set(bool::in, prog_var_renaming::in,
+    set(prog_var)::in, set(prog_var)::out) is det.
+
+:- pred goal_util__rename_var_list(bool::in, map(var(T), var(T))::in,
+    list(var(T))::in, list(var(T))::out) is det.
+
+:- pred goal_util__rename_var(bool::in, map(var(V), var(V))::in,
+    var(V)::in, var(V)::out) is det.
 
 	% goal_util__create_variables(OldVariables, OldVarset, InitialVarTypes,
 	%	InitialSubstitution, OldVarTypes, OldVarNames,  NewVarset,
-	%	NewVarTypes, NewSubstitution)
+    %   NewVarTypes, NewSubstitution):
+    %
+    % goal_util__create_variables takes a list of variables, a varset, and map
+    % from vars to types and an initial substitution, and creates new instances
+    % of each of the source variables in the substitution, adding each new
+    % variable to the varset and the var types map. The name and type of each
+    % new variable is found by looking up in the type map given in the 5th
+    % argument - the last input. (This interface will not easily admit
+    % uniqueness in the type map for this reason - such is the sacrifice
+    % for generality.)
+    %
 :- pred goal_util__create_variables(list(prog_var)::in, prog_varset::in,
 	map(prog_var, type)::in, prog_varset::in, prog_varset::out,
 	map(prog_var, type)::in, map(prog_var, type)::out,
-	map(prog_var, prog_var)::in, map(prog_var, prog_var)::out) is det.
+    prog_var_renaming::in, prog_var_renaming::out) is det.
 
 	% Return all the variables in the goal.
-	% Unlike quantification:goal_vars, this predicate returns
+    % Unlike quantification.goal_vars, this predicate returns
 	% even the explicitly quantified variables.
+    %
 :- pred goal_util__goal_vars(hlds_goal::in, set(prog_var)::out) is det.
 
 	% Return all the variables in the list of goals.
-	% Unlike quantification:goal_vars, this predicate returns
+    % Unlike quantification.goal_vars, this predicate returns
 	% even the explicitly quantified variables.
+    %
 :- pred goal_util__goals_goal_vars(list(hlds_goal)::in, set(prog_var)::in,
 	set(prog_var)::out) is det.
 
 	% Return all the variables in a generic call.
+    %
 :- pred goal_util__generic_call_vars(generic_call::in, list(prog_var)::out)
 	is det.
 
-	% Attach the given goal features to the given goal and all its
-	% subgoals.
+    % Attach the given goal features to the given goal and all its subgoals.
+    %
 :- pred goal_util__attach_features_to_all_goals(list(goal_feature)::in,
 	hlds_goal::in, hlds_goal::out) is det.
 
-	%
 	% goal_util__extra_nonlocal_typeinfos(TypeInfoMap, TypeClassInfoMap,
 	%		VarTypes, ExistQVars, NonLocals, NonLocalTypeInfos):
-	% compute which type-info and type-class-info variables
-	% may need to be non-local to a goal.
 	%
-	% A type-info variable may be non-local to a goal if any of
-	% the ordinary non-local variables for that goal are
-	% polymorphically typed with a type that depends on that
-	% type-info variable, or if the type-info is for an
+    % Compute which type-info and type-class-info variables may need to be
+    % non-local to a goal.
+    %
+    % A type-info variable may be non-local to a goal if any of the ordinary
+    % non-local variables for that goal are polymorphically typed with a type
+    % that depends on that type-info variable, or if the type-info is for an
 	% existentially quantified type variable.
 	%
-	% In addition, a typeclass-info may be non-local to a goal if
-	% any of the non-local variables for that goal are
-	% polymorphically typed and are constrained by the typeclass
-	% constraints for that typeclass-info variable,
-	% or if the the type-class-info is for an existential constraint,
-	% i.e. a constraint which contrains an existentially quantified
-	% type variable.
+    % In addition, a typeclass-info may be non-local to a goal if any of the
+    % non-local variables for that goal are polymorphically typed and are
+    % constrained by the typeclass constraints for that typeclass-info
+    % variable, or if the the type-class-info is for an existential constraint,
+    % i.e. a constraint which contrains an existentially quantified type
+    % variable.
 	%
 :- pred goal_util__extra_nonlocal_typeinfos(rtti_varmaps::in,
 	map(prog_var, type)::in, existq_tvars::in,
 	set(prog_var)::in, set(prog_var)::out) is det.
 
 	% See whether the goal is a branched structure.
+    %
 :- pred goal_util__goal_is_branched(hlds_goal_expr::in) is semidet.
 
 	% Return an indication of the size of the goal.
+    %
 :- pred goal_size(hlds_goal::in, int::out) is det.
 
 	% Return an indication of the size of the list of goals.
+    %
 :- pred goals_size(list(hlds_goal)::in, int::out) is det.
 
 	% Return an indication of the size of the list of clauses.
+    %
 :- pred clause_list_size(list(clause)::in, int::out) is det.
 
 	% Test whether the goal calls the given procedure.
+    %
 :- pred goal_calls(hlds_goal, pred_proc_id).
 :- mode goal_calls(in, in) is semidet.
 :- mode goal_calls(in, out) is nondet.
@@ -150,12 +161,14 @@
 	% Test whether the goal calls the given predicate.
 	% This is useful before mode analysis when the proc_ids
 	% have not been determined.
+    %
 :- pred goal_calls_pred_id(hlds_goal, pred_id).
 :- mode goal_calls_pred_id(in, in) is semidet.
 :- mode goal_calls_pred_id(in, out) is nondet.
 
 	% Test whether the goal contains a reconstruction
 	% (a construction where the `cell_to_reuse' field is `yes(_)').
+    %
 :- pred goal_contains_reconstruction(hlds_goal::in) is semidet.
 
 	% goal_contains_goal(Goal, SubGoal) is true iff Goal contains SubGoal,
@@ -169,10 +182,12 @@
 	%
 :- pred direct_subgoal(hlds_goal_expr::in, hlds_goal::out) is nondet.
 
-	% returns all the predids that are used within a goal
+    % Returns all the predids that are used within a goal.
+    %
 :- pred predids_from_goal(hlds_goal::in, list(pred_id)::out) is det.
 
-	% returns all the predids that are used in a list of goals
+    % Returns all the predids that are used in a list of goals.
+    %
 :- pred predids_from_goals(list(hlds_goal)::in, list(pred_id)::out) is det.
 
 %-----------------------------------------------------------------------------%
@@ -180,6 +195,7 @@
 	% Convert a switch back into a disjunction. This is needed
 	% for the magic set transformation.
 	% This aborts if any of the constructors are existentially typed.
+    %
 :- pred goal_util__switch_to_disjunction(prog_var::in, list(case)::in,
 	instmap::in, list(hlds_goal)::out, prog_varset::in, prog_varset::out,
 	map(prog_var, type)::in, map(prog_var, type)::out,
@@ -188,6 +204,7 @@
 	% Convert a case into a conjunction by adding a tag test
 	% (deconstruction unification) to the case goal.
 	% This aborts if the constructor is existentially typed.
+    %
 :- pred goal_util__case_to_disjunct(prog_var::in, cons_id::in, hlds_goal::in,
 	instmap::in, hlds_goal::out, prog_varset::in, prog_varset::out,
 	map(prog_var, type)::in, map(prog_var, type)::out,
@@ -195,6 +212,7 @@
 
 	% Transform an if-then-else into ( Cond, Then ; \+ Cond, Else ),
 	% since magic.m and rl_gen.m don't handle if-then-elses.
+    %
 :- pred goal_util__if_then_else_to_disjunction(hlds_goal::in, hlds_goal::in,
 	hlds_goal::in, hlds_goal_info::in, hlds_goal_expr::out) is det.
 
@@ -287,6 +305,7 @@
 :- import_module hlds__goal_form.
 :- import_module hlds__hlds_data.
 :- import_module hlds__hlds_llds.
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__prog_data.
 :- import_module parse_tree__prog_mode.
 :- import_module parse_tree__prog_util.
@@ -295,6 +314,7 @@
 :- import_module require.
 :- import_module std_util.
 :- import_module string.
+:- import_module svmap.
 :- import_module varset.
 
 %-----------------------------------------------------------------------------%
@@ -310,7 +330,7 @@
 	vartypes::in, vartypes::out, prog_varset::in, prog_varset::out,
 	list(hlds_goal)::in, list(hlds_goal)::out,
 	list(prog_var)::in, list(prog_var)::out,
-	map(prog_var, prog_var)::in, map(prog_var, prog_var)::out) is det.
+    prog_var_renaming::in, prog_var_renaming::out) is det.
 
 create_renaming_2([], _, !VarTypes, !VarSet, !RevUnifies, !RevNewVars,
 		!Renaming).
@@ -318,11 +338,11 @@
 		!RevUnifies, !RevNewVars, !Renaming) :-
 	varset__new_var(!.VarSet, NewVar, !:VarSet),
 	map__lookup(!.VarTypes, OrigVar, Type),
-	map__det_insert(!.VarTypes, NewVar, Type, !:VarTypes),
+    svmap__det_insert(NewVar, Type, !VarTypes),
 	( instmap_delta_search_var(InstMapDelta, OrigVar, DeltaInst) ->
 		NewInst = DeltaInst
 	;
-		error("create_renaming_2: cannot get new inst")
+        unexpected(this_file, "create_renaming_2: cannot get new inst")
 	),
 	Mode = ((NewInst -> NewInst) - (free -> NewInst)),
 	UnifyInfo = assign(OrigVar, NewVar),
@@ -334,7 +354,7 @@
 		term__context_init, GoalInfo),
 	Goal = GoalExpr - GoalInfo,
 	!:RevUnifies = [Goal | !.RevUnifies],
-	map__det_insert(!.Renaming, OrigVar, NewVar, !:Renaming),
+    svmap__det_insert(OrigVar, NewVar, !Renaming),
 	!:RevNewVars = [NewVar | !.RevNewVars],
 	create_renaming_2(OrigVars, InstMapDelta, !VarTypes, !VarSet,
 		!RevUnifies, !RevNewVars, !Renaming).
@@ -354,9 +374,9 @@
 		;
 			true
 		),
-		map__det_insert(!.Subn, V, NV, !:Subn),
+        svmap__det_insert(V, NV, !Subn),
 		( map__search(OldVarTypes, V, VT) ->
-			map__set(!.VarTypes, NV, VT, !:VarTypes)
+            svmap__set(NV, VT, !VarTypes)
 		;
 			true
 		)
@@ -367,29 +387,29 @@
 %-----------------------------------------------------------------------------%
 
 :- pred goal_util__init_subn(assoc_list(prog_var, prog_var)::in,
-	map(prog_var, prog_var)::in, map(prog_var, prog_var)::out) is det.
+    prog_var_renaming::in, prog_var_renaming::out) is det.
 
 goal_util__init_subn([], !Subn).
 goal_util__init_subn([A - H | Vs], !Subn) :-
-	map__set(!.Subn, H, A, !:Subn),
+    svmap__set(H, A, !Subn),
 	goal_util__init_subn(Vs, !Subn).
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_util__rename_var_pair_list(assoc_list(prog_var, T)::in, bool::in,
-	map(prog_var, prog_var)::in, list(pair(prog_var, T))::out) is det.
+:- pred goal_util__rename_var_pair_list(bool::in, prog_var_renaming::in,
+    assoc_list(prog_var, T)::in, list(pair(prog_var, T))::out) is det.
 
-goal_util__rename_var_pair_list([], _Must, _Subn, []).
-goal_util__rename_var_pair_list([V - D | VDs], Must, Subn, [N - D | NDs]) :-
-	goal_util__rename_var(V, Must, Subn, N),
-	goal_util__rename_var_pair_list(VDs, Must, Subn, NDs).
-
-goal_util__rename_var_list([], _Must, _Subn, []).
-goal_util__rename_var_list([V | Vs], Must, Subn, [N | Ns]) :-
-	goal_util__rename_var(V, Must, Subn, N),
-	goal_util__rename_var_list(Vs, Must, Subn, Ns).
+goal_util__rename_var_pair_list(_Must, _Subn, [], []).
+goal_util__rename_var_pair_list(Must, Subn, [V - D | VDs], [N - D | NDs]) :-
+    goal_util__rename_var(Must, Subn, V, N),
+    goal_util__rename_var_pair_list(Must, Subn, VDs, NDs).
+
+goal_util__rename_var_list(_Must, _Subn, [], []).
+goal_util__rename_var_list(Must, Subn, [V | Vs], [N | Ns]) :-
+    goal_util__rename_var(Must, Subn, V, N),
+    goal_util__rename_var_list(Must, Subn, Vs, Ns).
 
-goal_util__rename_var(V, Must, Subn, N) :-
+goal_util__rename_var(Must, Subn, V, N) :-
 	( map__search(Subn, V, N0) ->
 		N = N0
 	;
@@ -407,69 +427,70 @@
 
 %-----------------------------------------------------------------------------%
 
-goal_util__rename_vars_in_goal(Goal0, Subn, Goal) :-
-	goal_util__rename_vars_in_goal(Goal0, no, Subn, Goal).
+goal_util__rename_vars_in_goal(Subn, Goal0, Goal) :-
+    goal_util__rename_vars_in_goal(no, Subn, Goal0, Goal).
 
-goal_util__must_rename_vars_in_goal(Goal0, Subn, Goal) :-
-	goal_util__rename_vars_in_goal(Goal0, yes, Subn, Goal).
+goal_util__must_rename_vars_in_goal(Subn, Goal0, Goal) :-
+    goal_util__rename_vars_in_goal(yes, Subn, Goal0, Goal).
 
 %-----------------------------------------------------------------------------%
 
-goal_util__rename_vars_in_goals([], _, _, []).
-goal_util__rename_vars_in_goals([Goal0 | Goals0], Must, Subn, [Goal | Goals]) :-
-	goal_util__rename_vars_in_goal(Goal0, Must, Subn, Goal),
-	goal_util__rename_vars_in_goals(Goals0, Must, Subn, Goals).
+goal_util__rename_vars_in_goals(_, _, [], []).
+goal_util__rename_vars_in_goals(Must, Subn, [Goal0 | Goals0], [Goal | Goals]) :-
+    goal_util__rename_vars_in_goal(Must, Subn, Goal0, Goal),
+    goal_util__rename_vars_in_goals(Must, Subn, Goals0, Goals).
 
-:- pred goal_util__rename_vars_in_goal(hlds_goal::in, bool::in,
-	map(prog_var, prog_var)::in, hlds_goal::out) is det.
+:- pred goal_util__rename_vars_in_goal(bool::in, prog_var_renaming::in,
+    hlds_goal::in, hlds_goal::out) is det.
 
-goal_util__rename_vars_in_goal(Goal0 - GoalInfo0, Must, Subn,
-		Goal - GoalInfo) :-
-	goal_util__rename_vars_in_goal_expr(Goal0, Must, Subn, Goal),
-	goal_util__rename_vars_in_goal_info(GoalInfo0, Must, Subn, GoalInfo).
+goal_util__rename_vars_in_goal(Must, Subn,
+        Goal0 - GoalInfo0, Goal - GoalInfo) :-
+    goal_util__rename_vars_in_goal_expr(Must, Subn, Goal0, Goal),
+    goal_util__rename_vars_in_goal_info(Must, Subn, GoalInfo0, GoalInfo).
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_util__rename_vars_in_goal_expr(hlds_goal_expr::in, bool::in,
-	map(prog_var, prog_var)::in, hlds_goal_expr::out) is det.
-
-goal_util__rename_vars_in_goal_expr(conj(Goals0), Must, Subn, conj(Goals)) :-
-	goal_util__rename_vars_in_goals(Goals0, Must, Subn, Goals).
-
-goal_util__rename_vars_in_goal_expr(par_conj(Goals0), Must, Subn,
-		par_conj(Goals)) :-
-	goal_util__rename_vars_in_goals(Goals0, Must, Subn, Goals).
-
-goal_util__rename_vars_in_goal_expr(disj(Goals0), Must, Subn, disj(Goals)) :-
-	goal_util__rename_vars_in_goals(Goals0, Must, Subn, Goals).
+:- pred goal_util__rename_vars_in_goal_expr(bool::in, prog_var_renaming::in,
+    hlds_goal_expr::in, hlds_goal_expr::out) is det.
 
-goal_util__rename_vars_in_goal_expr(switch(Var0, Det, Cases0), Must, Subn,
-		switch(Var, Det, Cases)) :-
-	goal_util__rename_var(Var0, Must, Subn, Var),
-	goal_util__rename_vars_in_cases(Cases0, Must, Subn, Cases).
+goal_util__rename_vars_in_goal_expr(Must, Subn, conj(Goals0), conj(Goals)) :-
+    goal_util__rename_vars_in_goals(Must, Subn, Goals0, Goals).
 
-goal_util__rename_vars_in_goal_expr(if_then_else(Vars0, Cond0, Then0, Else0),
-		Must, Subn, if_then_else(Vars, Cond, Then, Else)) :-
-	goal_util__rename_var_list(Vars0, Must, Subn, Vars),
-	goal_util__rename_vars_in_goal(Cond0, Must, Subn, Cond),
-	goal_util__rename_vars_in_goal(Then0, Must, Subn, Then),
-	goal_util__rename_vars_in_goal(Else0, Must, Subn, Else).
+goal_util__rename_vars_in_goal_expr(Must, Subn,
+        par_conj(Goals0), par_conj(Goals)) :-
+    goal_util__rename_vars_in_goals(Must, Subn, Goals0, Goals).
+
+goal_util__rename_vars_in_goal_expr(Must, Subn, disj(Goals0), disj(Goals)) :-
+    goal_util__rename_vars_in_goals(Must, Subn, Goals0, Goals).
+
+goal_util__rename_vars_in_goal_expr(Must, Subn,
+        switch(Var0, Det, Cases0), switch(Var, Det, Cases)) :-
+    goal_util__rename_var(Must, Subn, Var0, Var),
+    goal_util__rename_vars_in_cases(Must, Subn, Cases0, Cases).
+
+goal_util__rename_vars_in_goal_expr(Must, Subn,
+        if_then_else(Vars0, Cond0, Then0, Else0),
+        if_then_else(Vars, Cond, Then, Else)) :-
+    goal_util__rename_var_list(Must, Subn, Vars0, Vars),
+    goal_util__rename_vars_in_goal(Must, Subn, Cond0, Cond),
+    goal_util__rename_vars_in_goal(Must, Subn, Then0, Then),
+    goal_util__rename_vars_in_goal(Must, Subn, Else0, Else).
 
-goal_util__rename_vars_in_goal_expr(not(Goal0), Must, Subn, not(Goal)) :-
-	goal_util__rename_vars_in_goal(Goal0, Must, Subn, Goal).
+goal_util__rename_vars_in_goal_expr(Must, Subn, not(Goal0), not(Goal)) :-
+    goal_util__rename_vars_in_goal(Must, Subn, Goal0, Goal).
 
-goal_util__rename_vars_in_goal_expr(scope(Reason0, Goal0), Must, Subn,
-		scope(Reason, Goal)) :-
+goal_util__rename_vars_in_goal_expr(Must, Subn,
+        scope(Reason0, Goal0), scope(Reason, Goal)) :-
 	(
 		Reason0 = exist_quant(Vars0),
-		goal_util__rename_var_list(Vars0, Must, Subn, Vars),
+        goal_util__rename_var_list(Must, Subn, Vars0, Vars),
 		Reason = exist_quant(Vars)
 	;
 		Reason0 = promise_purity(_, _),
 		Reason = Reason0
 	;
 		Reason0 = promise_equivalent_solutions(Vars0),
-		goal_util__rename_var_list(Vars0, Must, Subn, Vars),
+        goal_util__rename_var_list(Must, Subn, Vars0, Vars),
 		Reason = promise_equivalent_solutions(Vars)
 	;
 		Reason0 = barrier(_),
@@ -479,110 +500,108 @@
 		Reason = Reason0
 	;
 		Reason0 = from_ground_term(Var0),
-		goal_util__rename_var(Var0, Must, Subn, Var),
+        goal_util__rename_var(Must, Subn, Var0, Var),
 		Reason = from_ground_term(Var)
 	),
-	goal_util__rename_vars_in_goal(Goal0, Must, Subn, Goal).
+    goal_util__rename_vars_in_goal(Must, Subn, Goal0, Goal).
 
-goal_util__rename_vars_in_goal_expr(
+goal_util__rename_vars_in_goal_expr(Must, Subn,
 		generic_call(GenericCall0, Args0, Modes, Det),
-		Must, Subn,
 		generic_call(GenericCall, Args, Modes, Det)) :-
-	goal_util__rename_generic_call(GenericCall0, Must, Subn, GenericCall),
-	goal_util__rename_var_list(Args0, Must, Subn, Args).
+    goal_util__rename_generic_call(Must, Subn, GenericCall0, GenericCall),
+    goal_util__rename_var_list(Must, Subn, Args0, Args).
 
-goal_util__rename_vars_in_goal_expr(
+goal_util__rename_vars_in_goal_expr(Must, Subn,
 		call(PredId, ProcId, Args0, Builtin, Context, Sym),
-		Must, Subn,
 		call(PredId, ProcId, Args, Builtin, Context, Sym)) :-
-	goal_util__rename_var_list(Args0, Must, Subn, Args).
+    goal_util__rename_var_list(Must, Subn, Args0, Args).
 
-goal_util__rename_vars_in_goal_expr(unify(LHS0, RHS0, Mode, Unify0, Context),
-		Must, Subn, unify(LHS, RHS, Mode, Unify, Context)) :-
-	goal_util__rename_var(LHS0, Must, Subn, LHS),
-	goal_util__rename_unify_rhs(RHS0, Must, Subn, RHS),
-	goal_util__rename_unify(Unify0, Must, Subn, Unify).
+goal_util__rename_vars_in_goal_expr(Must, Subn,
+        unify(LHS0, RHS0, Mode, Unify0, Context),
+        unify(LHS, RHS, Mode, Unify, Context)) :-
+    goal_util__rename_var(Must, Subn, LHS0, LHS),
+    goal_util__rename_unify_rhs(Must, Subn, RHS0, RHS),
+    goal_util__rename_unify(Must, Subn, Unify0, Unify).
 
-goal_util__rename_vars_in_goal_expr(foreign_proc(A,B,C,Args0,Extra0,F),
-		Must, Subn, foreign_proc(A,B,C,Args,Extra,F)) :-
-	goal_util__rename_arg_list(Args0, Must, Subn, Args),
-	goal_util__rename_arg_list(Extra0, Must, Subn, Extra).
+goal_util__rename_vars_in_goal_expr(Must, Subn,
+        foreign_proc(A, B, C, Args0, Extra0, F),
+        foreign_proc(A, B, C, Args, Extra, F)) :-
+    goal_util__rename_arg_list(Must, Subn, Args0, Args),
+    goal_util__rename_arg_list(Must, Subn, Extra0, Extra).
 
-goal_util__rename_vars_in_goal_expr(shorthand(ShorthandGoal0), Must, Subn,
-		shorthand(ShrothandGoal)) :-
-	goal_util__rename_vars_in_shorthand(ShorthandGoal0, Must, Subn,
-		ShrothandGoal).
+goal_util__rename_vars_in_goal_expr(Must, Subn,
+        shorthand(ShorthandGoal0), shorthand(ShrothandGoal)) :-
+    goal_util__rename_vars_in_shorthand(Must, Subn,
+        ShorthandGoal0, ShrothandGoal).
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_util__rename_vars_in_shorthand(shorthand_goal_expr::in, bool::in,
-	map(prog_var, prog_var)::in, shorthand_goal_expr::out) is det.
+:- pred goal_util__rename_vars_in_shorthand(bool::in, prog_var_renaming::in,
+    shorthand_goal_expr::in, shorthand_goal_expr::out) is det.
 
-goal_util__rename_vars_in_shorthand(bi_implication(LHS0, RHS0), Must, Subn,
-		bi_implication(LHS, RHS)) :-
-	goal_util__rename_vars_in_goal(LHS0, Must, Subn, LHS),
-	goal_util__rename_vars_in_goal(RHS0, Must, Subn, RHS).
+goal_util__rename_vars_in_shorthand(Must, Subn,
+        bi_implication(LHS0, RHS0), bi_implication(LHS, RHS)) :-
+    goal_util__rename_vars_in_goal(Must, Subn, LHS0, LHS),
+    goal_util__rename_vars_in_goal(Must, Subn, RHS0, RHS).
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_util__rename_arg_list(list(foreign_arg)::in, bool::in,
-	map(prog_var, prog_var)::in, list(foreign_arg)::out) is det.
+:- pred goal_util__rename_arg_list(bool::in, prog_var_renaming::in,
+    list(foreign_arg)::in, list(foreign_arg)::out) is det.
 
-goal_util__rename_arg_list([], _Must, _Subn, []).
-goal_util__rename_arg_list([Arg0 | Args0], Must, Subn, [Arg | Args]) :-
-	goal_util__rename_arg(Arg0, Must, Subn, Arg),
-	goal_util__rename_arg_list(Args0, Must, Subn, Args).
+goal_util__rename_arg_list(_Must, _Subn, [], []).
+goal_util__rename_arg_list(Must, Subn, [Arg0 | Args0], [Arg | Args]) :-
+    goal_util__rename_arg(Must, Subn, Arg0, Arg),
+    goal_util__rename_arg_list(Must, Subn, Args0, Args).
 
-:- pred goal_util__rename_arg(foreign_arg::in, bool::in,
-	map(prog_var, prog_var)::in, foreign_arg::out) is det.
+:- pred goal_util__rename_arg(bool::in, prog_var_renaming::in,
+    foreign_arg::in, foreign_arg::out) is det.
 
-goal_util__rename_arg(foreign_arg(Var0, B, C), Must, Subn,
-		foreign_arg(Var, B, C)) :-
-	goal_util__rename_var(Var0, Must, Subn, Var).
+goal_util__rename_arg(Must, Subn,
+        foreign_arg(Var0, B, C), foreign_arg(Var, B, C)) :-
+    goal_util__rename_var(Must, Subn, Var0, Var).
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_util__rename_vars_in_cases(list(case)::in, bool::in,
-	map(prog_var, prog_var)::in, list(case)::out) is det.
+:- pred goal_util__rename_vars_in_cases(bool::in, prog_var_renaming::in,
+    list(case)::in, list(case)::out) is det.
 
-goal_util__rename_vars_in_cases([], _Must, _Subn, []).
-goal_util__rename_vars_in_cases([case(Cons, G0) | Gs0], Must, Subn,
-		[case(Cons, G) | Gs]) :-
-	goal_util__rename_vars_in_goal(G0, Must, Subn, G),
-	goal_util__rename_vars_in_cases(Gs0, Must, Subn, Gs).
+goal_util__rename_vars_in_cases(_Must, _Subn, [], []).
+goal_util__rename_vars_in_cases(Must, Subn,
+        [case(Cons, G0) | Gs0], [case(Cons, G) | Gs]) :-
+    goal_util__rename_vars_in_goal(Must, Subn, G0, G),
+    goal_util__rename_vars_in_cases(Must, Subn, Gs0, Gs).
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_util__rename_unify_rhs(unify_rhs::in, bool::in,
-	map(prog_var, prog_var)::in, unify_rhs::out) is det.
+:- pred goal_util__rename_unify_rhs(bool::in, prog_var_renaming::in,
+    unify_rhs::in, unify_rhs::out) is det.
 
-goal_util__rename_unify_rhs(var(Var0), Must, Subn, var(Var)) :-
-	goal_util__rename_var(Var0, Must, Subn, Var).
-goal_util__rename_unify_rhs(functor(Functor, E, ArgVars0), Must, Subn,
-		functor(Functor, E, ArgVars)) :-
-	goal_util__rename_var_list(ArgVars0, Must, Subn, ArgVars).
-goal_util__rename_unify_rhs(
+goal_util__rename_unify_rhs(Must, Subn, var(Var0), var(Var)) :-
+    goal_util__rename_var(Must, Subn, Var0, Var).
+goal_util__rename_unify_rhs(Must, Subn,
+        functor(Functor, E, ArgVars0), functor(Functor, E, ArgVars)) :-
+    goal_util__rename_var_list(Must, Subn, ArgVars0, ArgVars).
+goal_util__rename_unify_rhs(Must, Subn,
 		lambda_goal(Purity, PredOrFunc, EvalMethod, FixModes,
 			NonLocals0, Vars0, Modes, Det, Goal0),
-		Must, Subn,
 		lambda_goal(Purity, PredOrFunc, EvalMethod, FixModes,
 			NonLocals, Vars, Modes, Det, Goal)) :-
-	goal_util__rename_var_list(NonLocals0, Must, Subn, NonLocals),
-	goal_util__rename_var_list(Vars0, Must, Subn, Vars),
-	goal_util__rename_vars_in_goal(Goal0, Must, Subn, Goal).
+    goal_util__rename_var_list(Must, Subn, NonLocals0, NonLocals),
+    goal_util__rename_var_list(Must, Subn, Vars0, Vars),
+    goal_util__rename_vars_in_goal(Must, Subn, Goal0, Goal).
 
-:- pred goal_util__rename_unify(unification::in, bool::in,
-	map(prog_var, prog_var)::in, unification::out) is det.
+:- pred goal_util__rename_unify(bool::in, prog_var_renaming::in,
+    unification::in, unification::out) is det.
 
-goal_util__rename_unify(
+goal_util__rename_unify(Must, Subn,
 		construct(Var0, ConsId, Vars0, Modes, How0, Uniq, MaybeSize0),
-		Must, Subn,
 		construct(Var, ConsId, Vars, Modes, How, Uniq, MaybeSize)) :-
-	goal_util__rename_var(Var0, Must, Subn, Var),
-	goal_util__rename_var_list(Vars0, Must, Subn, Vars),
+    goal_util__rename_var(Must, Subn, Var0, Var),
+    goal_util__rename_var_list(Must, Subn, Vars0, Vars),
 	(
 		How0 = reuse_cell(cell_to_reuse(ReuseVar0, B, C)),
-		goal_util__rename_var(ReuseVar0, Must, Subn, ReuseVar),
+        goal_util__rename_var(Must, Subn, ReuseVar0, ReuseVar),
 		How = reuse_cell(cell_to_reuse(ReuseVar, B, C))
 	;
 		How0 = construct_dynamically,
@@ -601,98 +620,100 @@
 			Size = Size0
 		;
 			Size0 = dynamic_size(SizeVar0),
-			goal_util__rename_var(SizeVar0, Must, Subn, SizeVar),
+            goal_util__rename_var(Must, Subn, SizeVar0, SizeVar),
 			Size = dynamic_size(SizeVar)
 		),
 		MaybeSize = yes(Size)
 	).
-goal_util__rename_unify(deconstruct(Var0, ConsId, Vars0, Modes, Cat, CanCGC),
-		Must, Subn,
+goal_util__rename_unify(Must, Subn,
+        deconstruct(Var0, ConsId, Vars0, Modes, Cat, CanCGC),
 		deconstruct(Var, ConsId, Vars, Modes, Cat, CanCGC)) :-
-	goal_util__rename_var(Var0, Must, Subn, Var),
-	goal_util__rename_var_list(Vars0, Must, Subn, Vars).
-goal_util__rename_unify(assign(L0, R0), Must, Subn, assign(L, R)) :-
-	goal_util__rename_var(L0, Must, Subn, L),
-	goal_util__rename_var(R0, Must, Subn, R).
-goal_util__rename_unify(simple_test(L0, R0), Must, Subn, simple_test(L, R)) :-
-	goal_util__rename_var(L0, Must, Subn, L),
-	goal_util__rename_var(R0, Must, Subn, R).
-goal_util__rename_unify(complicated_unify(Modes, Cat, TypeInfoVars),
-		_Must, _Subn,
+    goal_util__rename_var(Must, Subn, Var0, Var),
+    goal_util__rename_var_list(Must, Subn, Vars0, Vars).
+goal_util__rename_unify(Must, Subn, assign(L0, R0), assign(L, R)) :-
+    goal_util__rename_var(Must, Subn, L0, L),
+    goal_util__rename_var(Must, Subn, R0, R).
+goal_util__rename_unify(Must, Subn, simple_test(L0, R0), simple_test(L, R)) :-
+    goal_util__rename_var(Must, Subn, L0, L),
+    goal_util__rename_var(Must, Subn, R0, R).
+goal_util__rename_unify(_Must, _Subn,
+        complicated_unify(Modes, Cat, TypeInfoVars),
 		complicated_unify(Modes, Cat, TypeInfoVars)).
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_util__rename_generic_call(generic_call::in, bool::in,
-	map(prog_var, prog_var)::in, generic_call::out) is det.
+:- pred goal_util__rename_generic_call(bool::in, prog_var_renaming::in,
+    generic_call::in, generic_call::out) is det.
 
-goal_util__rename_generic_call(higher_order(Var0, Purity, PredOrFunc, Arity),
-		Must, Subn, higher_order(Var, Purity, PredOrFunc, Arity)) :-
-	goal_util__rename_var(Var0, Must, Subn, Var).
-goal_util__rename_generic_call(class_method(Var0, Method, ClassId, MethodId),
-		Must, Subn, class_method(Var, Method, ClassId, MethodId)) :-
-	goal_util__rename_var(Var0, Must, Subn, Var).
-goal_util__rename_generic_call(cast(CastType), _, _, cast(CastType)).
-goal_util__rename_generic_call(aditi_builtin(Builtin, PredCallId),
-		_Must, _Subn, aditi_builtin(Builtin, PredCallId)).
+goal_util__rename_generic_call(Must, Subn,
+        higher_order(Var0, Purity, PredOrFunc, Arity),
+        higher_order(Var, Purity, PredOrFunc, Arity)) :-
+    goal_util__rename_var(Must, Subn, Var0, Var).
+goal_util__rename_generic_call(Must, Subn,
+        class_method(Var0, Method, ClassId, MethodId),
+        class_method(Var, Method, ClassId, MethodId)) :-
+    goal_util__rename_var(Must, Subn, Var0, Var).
+goal_util__rename_generic_call(_, _, cast(CastType), cast(CastType)).
+goal_util__rename_generic_call(_Must, _Subn,
+        aditi_builtin(Builtin, PredCallId),
+        aditi_builtin(Builtin, PredCallId)).
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_util__rename_var_maps(map(prog_var, T)::in, bool::in,
-	map(prog_var, prog_var)::in, map(prog_var, T)::out) is det.
+:- pred goal_util__rename_var_maps(bool::in, prog_var_renaming::in,
+    map(prog_var, T)::in, map(prog_var, T)::out) is det.
 
-goal_util__rename_var_maps(Map0, Must, Subn, Map) :-
+goal_util__rename_var_maps(Must, Subn, Map0, Map) :-
 	map__to_assoc_list(Map0, AssocList0),
-	goal_util__rename_var_maps_2(AssocList0, Must, Subn, AssocList),
+    goal_util__rename_var_maps_2(Must, Subn, AssocList0, AssocList),
 	map__from_assoc_list(AssocList, Map).
 
-:- pred goal_util__rename_var_maps_2(assoc_list(var(V), T)::in,
-	bool::in, map(var(V), var(V))::in, assoc_list(var(V), T)::out) is det.
+:- pred goal_util__rename_var_maps_2(bool::in, map(var(V), var(V))::in,
+    assoc_list(var(V), T)::in, assoc_list(var(V), T)::out) is det.
 
-goal_util__rename_var_maps_2([], _Must, _Subn, []).
-goal_util__rename_var_maps_2([V - L | Vs], Must, Subn, [N - L | Ns]) :-
-	goal_util__rename_var(V, Must, Subn, N),
-	goal_util__rename_var_maps_2(Vs, Must, Subn, Ns).
+goal_util__rename_var_maps_2(_Must, _Subn, [], []).
+goal_util__rename_var_maps_2(Must, Subn, [V - L | Vs], [N - L | Ns]) :-
+    goal_util__rename_var(Must, Subn, V, N),
+    goal_util__rename_var_maps_2(Must, Subn, Vs, Ns).
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_util__rename_vars_in_goal_info(hlds_goal_info::in,
-	bool::in, map(prog_var, prog_var)::in, hlds_goal_info::out) is det.
+:- pred goal_util__rename_vars_in_goal_info(bool::in, prog_var_renaming::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-goal_util__rename_vars_in_goal_info(GoalInfo0, Must, Subn, GoalInfo) :-
-	goal_info_get_nonlocals(GoalInfo0, NonLocals0),
-	goal_util__rename_vars_in_var_set(NonLocals0, Must, Subn, NonLocals),
-	goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo1),
+goal_util__rename_vars_in_goal_info(Must, Subn, !GoalInfo) :-
+    goal_info_get_nonlocals(!.GoalInfo, NonLocals0),
+    goal_util__rename_vars_in_var_set(Must, Subn, NonLocals0, NonLocals),
+    goal_info_set_nonlocals(NonLocals, !GoalInfo),
 
-	goal_info_get_instmap_delta(GoalInfo1, InstMap0),
-	instmap_delta_apply_sub(InstMap0, Must, Subn, InstMap),
-	goal_info_set_instmap_delta(GoalInfo1, InstMap, GoalInfo2),
+    goal_info_get_instmap_delta(!.GoalInfo, InstMap0),
+    instmap_delta_apply_sub(Must, Subn, InstMap0, InstMap),
+    goal_info_set_instmap_delta(InstMap, !GoalInfo),
 
-	goal_info_get_code_gen_info(GoalInfo2, CodeGenInfo0),
-	goal_util__rename_vars_in_code_gen_info(CodeGenInfo0, Must, Subn,
-		CodeGenInfo),
-	goal_info_set_code_gen_info(GoalInfo2, CodeGenInfo, GoalInfo).
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
+    goal_util__rename_vars_in_code_gen_info(Must, Subn,
+        CodeGenInfo0, CodeGenInfo),
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
 %-----------------------------------------------------------------------------%
 
-goal_util__rename_vars_in_var_set(Vars0, Must, Subn, Vars) :-
+goal_util__rename_vars_in_var_set(Must, Subn, Vars0, Vars) :-
 	set__to_sorted_list(Vars0, VarsList0),
-	goal_util__rename_var_list(VarsList0, Must, Subn, VarsList),
+    goal_util__rename_var_list(Must, Subn, VarsList0, VarsList),
 	set__list_to_set(VarsList, Vars).
 
-:- pred goal_util__rename_vars_in_code_gen_info(hlds_goal_code_gen_info::in,
-	bool::in, map(prog_var, prog_var)::in, hlds_goal_code_gen_info::out)
-	is det.
+:- pred goal_util__rename_vars_in_code_gen_info(bool::in,
+    prog_var_renaming::in,
+    hlds_goal_code_gen_info::in, hlds_goal_code_gen_info::out) is det.
 
-goal_util__rename_vars_in_code_gen_info(CodeGenInfo0, Must, Subn,
-		CodeGenInfo) :-
+goal_util__rename_vars_in_code_gen_info(Must, Subn,
+        CodeGenInfo0, CodeGenInfo) :-
 	(
 		CodeGenInfo0 = no_code_gen_info,
 		CodeGenInfo = no_code_gen_info
 	;
 		CodeGenInfo0 = llds_code_gen_info(LldsInfo0),
-		rename_vars_in_llds_code_gen_info(LldsInfo0, Must, Subn,
-			LldsInfo),
+        rename_vars_in_llds_code_gen_info(Must, Subn, LldsInfo0, LldsInfo),
 		CodeGenInfo = llds_code_gen_info(LldsInfo)
 	).
 
@@ -819,7 +840,7 @@
 attach_features_to_all_goals(Features, Goal0, Goal) :-
 	Goal0 = GoalExpr0 - GoalInfo0,
 	attach_features_goal_expr(Features, GoalExpr0, GoalExpr),
-	goal_info_add_features(Features, GoalInfo0, GoalInfo),
+    list__foldl(goal_info_add_feature, Features, GoalInfo0, GoalInfo),
 	Goal = GoalExpr - GoalInfo.
 
 :- pred attach_features_to_case(list(goal_feature)::in,
@@ -914,8 +935,7 @@
 	solutions_set((pred(Var::out) is nondet :-
 			% Search through all arguments of all constraints
 			% that the goal could have used.
-			rtti_varmaps_reusable_constraints(RttiVarMaps,
-				Constraints),
+            rtti_varmaps_reusable_constraints(RttiVarMaps, Constraints),
 			list__member(Constraint, Constraints),
 			Constraint = constraint(_Name, ArgTypes),
 			term__contains_var_list(ArgTypes, TypeVar),
@@ -923,10 +943,8 @@
 
 			% We found a constraint that is non-local.  Include
 			% the variable holding its typeclass_info.
-			rtti_lookup_typeclass_info_var(RttiVarMaps, Constraint,
-				Var)
+            rtti_lookup_typeclass_info_var(RttiVarMaps, Constraint, Var)
 		), NonLocalTypeClassInfoVars),
-	
 	NonLocalTypeInfos = set__union(NonLocalTypeInfoVars,
 		NonLocalTypeClassInfoVars).
 
@@ -1213,8 +1231,7 @@
 	map__lookup(!.VarTypes, Var, VarType),
 	type_util__get_cons_id_arg_types(!.ModuleInfo,
 		VarType, ConsId, ArgTypes),
-	map__det_insert_from_corresponding_lists(!.VarTypes, ArgVars,
-		ArgTypes, !:VarTypes),
+    svmap__det_insert_from_corresponding_lists(ArgVars, ArgTypes, !VarTypes),
 	instmap__lookup_var(InstMap, Var, Inst0),
 	(
 		inst_expand(!.ModuleInfo, Inst0, Inst1),
@@ -1277,7 +1294,7 @@
 	( CondMaxSoln0 = at_most_many ->
 		CondMaxSoln = at_most_one,
 		determinism_components(CondDetism, CondCanFail0, CondMaxSoln),
-		goal_info_set_determinism(CondInfo0, CondDetism, CondInfo),
+        goal_info_set_determinism(CondDetism, CondInfo0, CondInfo),
 		Cond = scope(commit(dont_force_pruning), Cond0) - CondInfo
 	;
 		CondDetism = CondDetism0,
@@ -1327,7 +1344,7 @@
 	goal_info_get_instmap_delta(GoalInfo2, Delta2),
 	instmap_delta_apply_instmap_delta(Delta1, Delta2, test_size,
 		CombinedDelta0),
-	instmap_delta_restrict(CombinedDelta0, OuterNonLocals, CombinedDelta),
+    instmap_delta_restrict(OuterNonLocals, CombinedDelta0, CombinedDelta),
 
 	goal_info_get_determinism(GoalInfo1, Detism1),
 	goal_info_get_determinism(GoalInfo2, Detism2),
@@ -1454,7 +1471,7 @@
 	pred_info_get_purity(PredInfo, Purity),
 	goal_info_init(NonLocals, InstMapDelta, Detism, Purity, Context,
 		GoalInfo0),
-	goal_info_add_features(Features, GoalInfo0, GoalInfo),
+    list__foldl(goal_info_add_feature, Features, GoalInfo0, GoalInfo),
 	Goal = GoalExpr - GoalInfo.
 
 goal_util__generate_foreign_proc(ModuleName, ProcName, PredOrFunc, ModeNo,
@@ -1481,7 +1498,7 @@
 	pred_info_get_purity(PredInfo, Purity),
 	goal_info_init(NonLocals, InstMapDelta, Detism, Purity, Context,
 		GoalInfo0),
-	goal_info_add_features(Features, GoalInfo0, GoalInfo),
+    list__foldl(goal_info_add_feature, Features, GoalInfo0, GoalInfo),
 	Goal = GoalExpr - GoalInfo.
 
 goal_util__generate_cast(CastType, InArg, OutArg, Context, Goal) :-
@@ -1515,5 +1532,11 @@
 		% goal_calls_pred_id has multiple modes.
 	P = (pred(PredId::out) is nondet :- goal_calls_pred_id(Goal, PredId)),
 	solutions(P, PredIds).
+
+%-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "goal_util.m".
 
 %-----------------------------------------------------------------------------%
Index: compiler/hhf.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/hhf.m,v
retrieving revision 1.7
diff -u -b -r1.7 hhf.m
--- compiler/hhf.m	23 May 2005 03:15:34 -0000	1.7
+++ compiler/hhf.m	27 Aug 2005 14:08:58 -0000
@@ -270,7 +270,7 @@
 	),
 	goal_info_get_nonlocals(GoalInfo0, GINonlocals0),
 	GINonlocals = GINonlocals0 `set__union` list_to_set(Args),
-	goal_info_set_nonlocals(GoalInfo0, GINonlocals, GoalInfo),
+	goal_info_set_nonlocals(GINonlocals, GoalInfo0, GoalInfo),
 	UnifyGoal = unify(X, functor(ConsId, IsExistConstruct, Args),
 		Mode, Unif, Context) - GoalInfo,
 	GoalExpr = conj([UnifyGoal | Unifications]).
@@ -288,7 +288,7 @@
 		[unify(A, var(B), M, U, C) - GI | Us]) :-
 	goal_info_get_nonlocals(GI0, GINonlocals0),
 	GINonlocals = GINonlocals0 `set__insert` A `set__insert` B,
-	goal_info_set_nonlocals(GI0, GINonlocals, GI),
+	goal_info_set_nonlocals(GINonlocals, GI0, GI),
 	hhf__make_unifications(As, Bs, GI0, M, U, C, Us).
 
 :- pred hhf__add_unifications(list(prog_var)::in, set(prog_var)::in,
@@ -322,7 +322,7 @@
 		!:HI = !.HI ^ inst_graph := InstGraph,
 		goal_info_get_nonlocals(GI0, GINonlocals0),
 		GINonlocals = GINonlocals0 `set__insert` V,
-		goal_info_set_nonlocals(GI0, GINonlocals, GI),
+		goal_info_set_nonlocals(GINonlocals, GI0, GI),
 		Goals = [unify(A, var(V), M, U, C) - GI | Goals0]
 	;
 		V = A,
Index: compiler/higher_order.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/higher_order.m,v
retrieving revision 1.133
diff -u -b -r1.133 higher_order.m
--- compiler/higher_order.m	27 Aug 2005 09:41:54 -0000	1.133
+++ compiler/higher_order.m	28 Aug 2005 01:59:06 -0000
@@ -1039,8 +1039,8 @@
 
     set.list_to_set(CallArgs, NonLocals),
     instmap_delta_init_reachable(InstMapDelta0),
-    instmap_delta_insert(InstMapDelta0, ResultVar,
-        ground(shared, none), InstMapDelta),
+    instmap_delta_insert(ResultVar, ground(shared, none),
+        InstMapDelta0, InstMapDelta),
     goal_info_init(NonLocals, InstMapDelta, det, pure, GoalInfo),
     CallGoal = call(PredId, ProcId, CallArgs, not_builtin,
         MaybeContext, SymName) - GoalInfo,
Index: compiler/hlds_goal.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/hlds_goal.m,v
retrieving revision 1.135
diff -u -b -r1.135 hlds_goal.m
--- compiler/hlds_goal.m	27 Aug 2005 09:41:54 -0000	1.135
+++ compiler/hlds_goal.m	27 Aug 2005 14:09:39 -0000
@@ -806,22 +806,22 @@
     hlds_goal_code_gen_info::out) is det.
 :- func goal_info_get_extra_info(hlds_goal_info) = hlds_goal_extra_info.
 
-:- pred goal_info_set_determinism(hlds_goal_info::in, determinism::in,
-    hlds_goal_info::out) is det.
-:- pred goal_info_set_instmap_delta(hlds_goal_info::in, instmap_delta::in,
-    hlds_goal_info::out) is det.
-:- pred goal_info_set_context(hlds_goal_info::in, prog_context::in,
-    hlds_goal_info::out) is det.
-:- pred goal_info_set_nonlocals(hlds_goal_info::in, set(prog_var)::in,
-    hlds_goal_info::out) is det.
-:- pred goal_info_set_code_gen_nonlocals(hlds_goal_info::in, set(prog_var)::in,
-    hlds_goal_info::out) is det.
-:- pred goal_info_set_features(hlds_goal_info::in, set(goal_feature)::in,
-    hlds_goal_info::out) is det.
-:- pred goal_info_set_goal_path(hlds_goal_info::in, goal_path::in,
-    hlds_goal_info::out) is det.
-:- pred goal_info_set_code_gen_info(hlds_goal_info::in,
-    hlds_goal_code_gen_info::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_determinism(determinism::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_instmap_delta(instmap_delta::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_context(prog_context::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_nonlocals(set(prog_var)::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_code_gen_nonlocals(set(prog_var)::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_features(set(goal_feature)::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_goal_path(goal_path::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_code_gen_info(hlds_goal_code_gen_info::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 :- pred goal_info_set_extra_info(hlds_goal_extra_info::in, hlds_goal_info::in,
     hlds_goal_info::out) is det.
 
@@ -861,27 +861,22 @@
 
 :- pred goal_get_nonlocals(hlds_goal::in, set(prog_var)::out) is det.
 
-:- pred goal_info_add_features(list(goal_feature)::in,
+:- pred goal_info_add_feature(goal_feature::in,
     hlds_goal_info::in, hlds_goal_info::out) is det.
-:- pred goal_info_remove_features(list(goal_feature)::in,
+:- pred goal_info_remove_feature(goal_feature::in,
     hlds_goal_info::in, hlds_goal_info::out) is det.
-
-:- pred goal_info_add_feature(hlds_goal_info::in, goal_feature::in,
-    hlds_goal_info::out) is det.
-:- pred goal_info_remove_feature(hlds_goal_info::in, goal_feature::in,
-    hlds_goal_info::out) is det.
 :- pred goal_info_has_feature(hlds_goal_info::in, goal_feature::in) is semidet.
 
-:- pred goal_add_feature(hlds_goal::in, goal_feature::in, hlds_goal::out)
+:- pred goal_add_feature(goal_feature::in, hlds_goal::in, hlds_goal::out)
     is det.
-:- pred goal_remove_feature(hlds_goal::in, goal_feature::in, hlds_goal::out)
+:- pred goal_remove_feature(goal_feature::in, hlds_goal::in, hlds_goal::out)
     is det.
 :- pred goal_has_feature(hlds_goal::in, goal_feature::in) is semidet.
 
     % Update a goal info to reflect the specified purity.
     %
-:- pred add_goal_info_purity_feature(hlds_goal_info::in, purity::in,
-    hlds_goal_info::out) is det.
+:- pred add_goal_info_purity_feature(purity::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
     % Determine the purity of a goal from its hlds_goal_info.
     %
@@ -1592,18 +1587,18 @@
         NeedVisibleVars = set__init
     ).
 
-goal_info_set_determinism(GoalInfo0, Determinism,
-        GoalInfo0 ^ determinism := Determinism).
-goal_info_set_instmap_delta(GoalInfo0, InstMapDelta,
-        GoalInfo0 ^ instmap_delta := InstMapDelta).
-goal_info_set_context(GoalInfo0, Context, GoalInfo0 ^ context := Context).
-goal_info_set_nonlocals(GoalInfo0, NonLocals,
-        GoalInfo0 ^ nonlocals := NonLocals).
-goal_info_set_features(GoalInfo0, Features, GoalInfo0 ^ features := Features).
-goal_info_set_goal_path(GoalInfo0, GoalPath,
-        GoalInfo0 ^ goal_path := GoalPath).
-goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo,
-        GoalInfo0 ^ code_gen_info := CodeGenInfo).
+goal_info_set_determinism(Determinism, GoalInfo,
+        GoalInfo ^ determinism := Determinism).
+goal_info_set_instmap_delta(InstMapDelta, GoalInfo,
+        GoalInfo ^ instmap_delta := InstMapDelta).
+goal_info_set_context(Context, GoalInfo, GoalInfo ^ context := Context).
+goal_info_set_nonlocals(NonLocals, GoalInfo,
+        GoalInfo ^ nonlocals := NonLocals).
+goal_info_set_features(Features, GoalInfo, GoalInfo ^ features := Features).
+goal_info_set_goal_path(GoalPath, GoalInfo,
+        GoalInfo ^ goal_path := GoalPath).
+goal_info_set_code_gen_info(CodeGenInfo, GoalInfo,
+        GoalInfo ^ code_gen_info := CodeGenInfo).
 goal_info_set_extra_info(ExtraInfo, GoalInfo,
     GoalInfo ^ extra_goal_info := ExtraInfo).
 
@@ -1613,8 +1608,8 @@
     goal_info_get_nonlocals(GoalInfo, NonLocals).
     % The code-gen non-locals are always the same as the
     % non-locals when structure reuse is not being performed.
-goal_info_set_code_gen_nonlocals(GoalInfo0, NonLocals, GoalInfo) :-
-    goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo).
+goal_info_set_code_gen_nonlocals(NonLocals, !GoalInfo) :-
+    goal_info_set_nonlocals(NonLocals, !GoalInfo).
 
 goal_info_set_occurring_vars(OccurringVars, !GoalInfo) :-
     MMCI0 = !.GoalInfo ^ maybe_mode_constraint_info,
@@ -1722,16 +1717,16 @@
 
 %-----------------------------------------------------------------------------%
 
-add_goal_info_purity_feature(GoalInfo0, Purity, GoalInfo) :-
-    infer_goal_info_purity(GoalInfo0, Purity0),
+add_goal_info_purity_feature(Purity, !GoalInfo) :-
+    infer_goal_info_purity(!.GoalInfo, Purity0),
     ( Purity = Purity0 ->
-        GoalInfo = GoalInfo0
+        true
     ;
         purity_features(Purity, FeaturesToRemove, FeaturesToAdd),
-        goal_info_get_features(GoalInfo0, Features0),
+        goal_info_get_features(!.GoalInfo, Features0),
         Features = set__union(list_to_set(FeaturesToAdd),
             set__difference(Features0, list_to_set(FeaturesToRemove))),
-        goal_info_set_features(GoalInfo0, Features, GoalInfo)
+        goal_info_set_features(Features, !GoalInfo)
     ).
 
 :- pred purity_features(purity::in, list(goal_feature)::out,
@@ -1759,25 +1754,15 @@
 
 %-----------------------------------------------------------------------------%
 
-goal_info_add_features([], GoalInfo, GoalInfo).
-goal_info_add_features([Feature | Features], GoalInfo0, GoalInfo) :-
-    goal_info_add_feature(GoalInfo0, Feature, GoalInfo1),
-    goal_info_add_features(Features, GoalInfo1, GoalInfo).
-
-goal_info_remove_features([], GoalInfo, GoalInfo).
-goal_info_remove_features([Feature | Features], GoalInfo0, GoalInfo) :-
-    goal_info_remove_feature(GoalInfo0, Feature, GoalInfo1),
-    goal_info_remove_features(Features, GoalInfo1, GoalInfo).
-
-goal_info_add_feature(GoalInfo0, Feature, GoalInfo) :-
-    goal_info_get_features(GoalInfo0, Features0),
+goal_info_add_feature(Feature, !GoalInfo) :-
+    goal_info_get_features(!.GoalInfo, Features0),
     set__insert(Features0, Feature, Features),
-    goal_info_set_features(GoalInfo0, Features, GoalInfo).
+    goal_info_set_features(Features, !GoalInfo).
 
-goal_info_remove_feature(GoalInfo0, Feature, GoalInfo) :-
-    goal_info_get_features(GoalInfo0, Features0),
+goal_info_remove_feature(Feature, !GoalInfo) :-
+    goal_info_get_features(!.GoalInfo, Features0),
     set__delete(Features0, Feature, Features),
-    goal_info_set_features(GoalInfo0, Features, GoalInfo).
+    goal_info_set_features(Features, !GoalInfo).
 
 goal_info_has_feature(GoalInfo, Feature) :-
     goal_info_get_features(GoalInfo, Features),
@@ -1788,11 +1773,11 @@
 goal_get_nonlocals(_Goal - GoalInfo, NonLocals) :-
     goal_info_get_nonlocals(GoalInfo, NonLocals).
 
-goal_add_feature(Goal - GoalInfo0, Feature, Goal - GoalInfo) :-
-    goal_info_add_feature(GoalInfo0, Feature, GoalInfo).
+goal_add_feature(Feature, Goal - GoalInfo0, Goal - GoalInfo) :-
+    goal_info_add_feature(Feature, GoalInfo0, GoalInfo).
 
-goal_remove_feature(Goal - GoalInfo0, Feature, Goal - GoalInfo) :-
-    goal_info_remove_feature(GoalInfo0, Feature, GoalInfo).
+goal_remove_feature(Feature, Goal - GoalInfo0, Goal - GoalInfo) :-
+    goal_info_remove_feature(Feature, GoalInfo0, GoalInfo).
 
 goal_has_feature(_Goal - GoalInfo, Feature) :-
     goal_info_has_feature(GoalInfo, Feature).
@@ -2033,7 +2018,7 @@
 
 true_goal(Context, Goal - GoalInfo) :-
     true_goal(Goal - GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo).
+    goal_info_set_context(Context, GoalInfo0, GoalInfo).
 
 fail_goal(disj([]) - GoalInfo) :-
     instmap_delta_init_unreachable(InstMapDelta),
@@ -2041,7 +2026,7 @@
 
 fail_goal(Context, Goal - GoalInfo) :-
     fail_goal(Goal - GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo).
+    goal_info_set_context(Context, GoalInfo0, GoalInfo).
 
 %-----------------------------------------------------------------------------%
 
@@ -2081,7 +2066,7 @@
 %-----------------------------------------------------------------------------%
 
 set_goal_contexts(Context, Goal0 - GoalInfo0, Goal - GoalInfo) :-
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     set_goal_contexts_2(Context, Goal0, Goal).
 
 :- pred set_goal_contexts_2(prog_context::in, hlds_goal_expr::in,
@@ -2214,7 +2199,7 @@
     Goal = unify(Var, RHS, Mode, Unification, Context),
     set__singleton_set(NonLocals, Var),
     instmap_delta_init_reachable(InstMapDelta0),
-    instmap_delta_insert(InstMapDelta0, Var, Inst, InstMapDelta),
+    instmap_delta_insert(Var, Inst, InstMapDelta0, InstMapDelta),
     goal_info_init(NonLocals, InstMapDelta, det, pure, GoalInfo).
 
 construct_functor(Var, ConsId, Args, Goal) :-
Index: compiler/hlds_llds.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/hlds_llds.m,v
retrieving revision 1.7
diff -u -b -r1.7 hlds_llds.m
--- compiler/hlds_llds.m	22 Mar 2005 06:39:59 -0000	1.7
+++ compiler/hlds_llds.m	27 Aug 2005 17:13:05 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 2002-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -21,10 +23,8 @@
 :- import_module set.
 :- import_module std_util.
 
-%
 % The following types are annotations on the HLDS
 % that are used only by the LLDS back-end.
-%
 
 :- type stack_slot
 	--->	det_slot(int)
@@ -65,10 +65,12 @@
 				% variable to any_reg.
 
 	% see compiler/notes/allocation.html for what these alternatives mean
-:- type resume_point	--->	resume_point(set(prog_var), resume_locs)
+:- type resume_point
+    --->    resume_point(set(prog_var), resume_locs)
 			;	no_resume_point.
 
-:- type resume_locs	--->	orig_only
+:- type resume_locs
+    --->    orig_only
 			;	stack_only
 			;	orig_and_stack
 			;	stack_and_orig.
@@ -195,68 +197,68 @@
 
 %-----------------------------------------------------------------------------%
 
-	% goal_info_initialize_liveness_info(GoalInfo0, PreBirths, PostBirths,
-	%	PreDeaths, PostDeaths, ResumePoint, GoalInfo):
-	% Updates GoalInfo0 by overwriting the previous values of its
+    % goal_info_initialize_liveness_info(PreBirths, PostBirths,
+    %   PreDeaths, PostDeaths, ResumePoint, !GoalInfo):
+    % Updates !GoalInfo by overwriting the previous values of its
 	% pre_births, post_births, pre_deaths, post_deaths and resume_point
-	% fields, yielding GoalInfo.
-
-:- pred goal_info_initialize_liveness_info(hlds_goal_info::in,
-	set(prog_var)::in, set(prog_var)::in, set(prog_var)::in,
-	set(prog_var)::in, resume_point::in, hlds_goal_info::out) is det.
+    % fields.
+    %
+:- pred goal_info_initialize_liveness_info(
+    set(prog_var)::in, set(prog_var)::in, set(prog_var)::in, set(prog_var)::in,
+    resume_point::in, hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_pre_births(hlds_goal_info::in, set(prog_var)::in,
-	hlds_goal_info::out) is det.
+:- pred goal_info_set_pre_births(set(prog_var)::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_post_births(hlds_goal_info::in, set(prog_var)::in,
-	hlds_goal_info::out) is det.
+:- pred goal_info_set_post_births(set(prog_var)::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_pre_deaths(hlds_goal_info::in, set(prog_var)::in,
-	hlds_goal_info::out) is det.
+:- pred goal_info_set_pre_deaths(set(prog_var)::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_post_deaths(hlds_goal_info::in, set(prog_var)::in,
-	hlds_goal_info::out) is det.
+:- pred goal_info_set_post_deaths(set(prog_var)::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_follow_vars(hlds_goal_info::in,
-	maybe(abs_follow_vars)::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_follow_vars(maybe(abs_follow_vars)::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_store_map(hlds_goal_info::in, abs_store_map::in,
-	hlds_goal_info::out) is det.
+:- pred goal_info_set_store_map(abs_store_map::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_resume_point(hlds_goal_info::in, resume_point::in,
-	hlds_goal_info::out) is det.
+:- pred goal_info_set_resume_point(resume_point::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_need_across_call(hlds_goal_info::in,
-	need_across_call::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_need_across_call(need_across_call::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_need_in_resume(hlds_goal_info::in,
-	need_in_resume::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_need_in_resume(need_in_resume::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
-:- pred goal_info_set_need_in_par_conj(hlds_goal_info::in,
-	need_in_par_conj::in, hlds_goal_info::out) is det.
+:- pred goal_info_set_need_in_par_conj(need_in_par_conj::in,
+    hlds_goal_info::in, hlds_goal_info::out) is det.
 
 %-----------------------------------------------------------------------------%
 
-:- pred goal_set_follow_vars(hlds_goal::in, maybe(abs_follow_vars)::in,
-	hlds_goal::out) is det.
+:- pred goal_set_follow_vars(maybe(abs_follow_vars)::in,
+    hlds_goal::in, hlds_goal::out) is det.
 
-:- pred goal_set_resume_point(hlds_goal::in, resume_point::in,
-	hlds_goal::out) is det.
+:- pred goal_set_resume_point(resume_point::in,
+    hlds_goal::in, hlds_goal::out) is det.
 
 :- pred goal_info_resume_vars_and_loc(resume_point::in,
 	set(prog_var)::out, resume_locs::out) is det.
 
 %-----------------------------------------------------------------------------%
 
-	% rename_vars_in_llds_code_gen_info(Details0, Must, Subn, Details):
+    % rename_vars_in_llds_code_gen_info(Must, Subn, Details0, Details):
 	% Renames all the variables in Details0 according to the substitution
 	% Subn, yielding Details. If Must is yes, then require every variable
 	% in Details0 to be in the domain of Subn. If Must is no, then leave
 	% variables not in the domain of Subn unchanged.
-
-:- pred rename_vars_in_llds_code_gen_info(llds_code_gen_details::in,
-	bool::in, map(prog_var, prog_var)::in, llds_code_gen_details::out)
-	is det.
+    %
+:- pred rename_vars_in_llds_code_gen_info(bool::in,
+    map(prog_var, prog_var)::in,
+    llds_code_gen_details::in, llds_code_gen_details::out) is det.
 
 %-----------------------------------------------------------------------------%
 
@@ -286,17 +288,16 @@
 	;	need_resume(need_in_resume)
 	;	need_par_conj(need_in_par_conj).
 
-:- type llds_code_gen_details --->
-	llds_code_gen_details(
+:- type llds_code_gen_details
+    --->    llds_code_gen_details(
+                % All four of these fields are computed by liveness.m.
+                % For atomic goals, the post-deadness should be applied
+                % _before_ the goal.
 		pre_births		:: set(prog_var),
 		post_births		:: set(prog_var),
 		pre_deaths		:: set(prog_var),
 		post_deaths		:: set(prog_var),
-			% All four of these fields are computed by liveness.m.
-			% For atomic goals, the post-deadness should be applied
-			% _before_ the goal.
 
-		follow_vars		:: maybe(abs_follow_vars),
 			% Initially set to `no' for all goals, which
 			% means the absence of the advisory
 			% information. Can be set to `yes' by the
@@ -305,8 +306,8 @@
 			%
 			% For the semantics of the value inside a `yes',
 			% see the documentation of the follow_vars type.
+                follow_vars     :: maybe(abs_follow_vars),
 
-		store_map		:: abs_store_map,
 			% This annotation is meaningful only after the
 			% store_alloc pass, and even then only if
 			% attached to a goal representing a branched
@@ -321,8 +322,8 @@
 			%
 			% This field should contain an empty map if its
 			% contents are not meaningful.
+                store_map       :: abs_store_map,
 
-		resume_point		:: resume_point,
 			% If this goal establishes a resumption point,
 			% i.e. it is the second or later disjunct of a
 			% disjunction or if it is the condition of an
@@ -335,8 +336,8 @@
 			% pass. Before then, and after then if the goal
 			% does not establish a resumption point, it
 			% should contain no_resume_point.
+                resume_point        :: resume_point,
 
-		maybe_need		:: maybe_need
 			% This field is filled in during the stackvars pass.
 			% It is not meaningful before then, and should
 			% contain `no_need'.
@@ -358,6 +359,7 @@
 			% specifies what variables are required to be stored
 			% on the stack by the parallel conjunction execution
 			% mechanism.
+                maybe_need      :: maybe_need
 	).
 
 %-----------------------------------------------------------------------------%
@@ -504,9 +506,9 @@
 
 %-----------------------------------------------------------------------------%
 
-goal_info_initialize_liveness_info(GoalInfo0, PreBirths, PostBirths,
-		PreDeaths, PostDeaths, ResumePoint, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_initialize_liveness_info(PreBirths, PostBirths,
+        PreDeaths, PostDeaths, ResumePoint, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = (((((LLDSInfo0
 		^ pre_births := PreBirths)
@@ -515,85 +517,85 @@
 		^ post_deaths := PostDeaths)
 		^ resume_point := ResumePoint),
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_pre_births(GoalInfo0, PreBirths, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_pre_births(PreBirths, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ pre_births := PreBirths,
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_post_births(GoalInfo0, PostBirths, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_post_births(PostBirths, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ post_births := PostBirths,
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_pre_deaths(GoalInfo0, PreDeaths, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_pre_deaths(PreDeaths, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ pre_deaths := PreDeaths,
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_post_deaths(GoalInfo0, PostDeaths, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_post_deaths(PostDeaths, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ post_deaths := PostDeaths,
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_follow_vars(GoalInfo0, FollowVars, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_follow_vars(FollowVars, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ follow_vars := FollowVars,
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_store_map(GoalInfo0, StoreMap, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_store_map(StoreMap, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ store_map := StoreMap,
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_resume_point(GoalInfo0, ResumePoint, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_resume_point(ResumePoint, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ resume_point := ResumePoint,
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_need_across_call(GoalInfo0, NeedAcrossCall, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_need_across_call(NeedAcrossCall, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ maybe_need := need_call(NeedAcrossCall),
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_need_in_resume(GoalInfo0, NeedInResume, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_need_in_resume(NeedInResume, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ maybe_need := need_resume(NeedInResume),
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
-goal_info_set_need_in_par_conj(GoalInfo0, NeedInParConj, GoalInfo) :-
-	goal_info_get_code_gen_info(GoalInfo0, CodeGenInfo0),
+goal_info_set_need_in_par_conj(NeedInParConj, !GoalInfo) :-
+    goal_info_get_code_gen_info(!.GoalInfo, CodeGenInfo0),
 	LLDSInfo0 = get_details(CodeGenInfo0),
 	LLDSInfo = LLDSInfo0 ^ maybe_need := need_par_conj(NeedInParConj),
 	CodeGenInfo = llds_code_gen_info(LLDSInfo),
-	goal_info_set_code_gen_info(GoalInfo0, CodeGenInfo, GoalInfo).
+    goal_info_set_code_gen_info(CodeGenInfo, !GoalInfo).
 
 %-----------------------------------------------------------------------------%
 
-goal_set_follow_vars(Goal - GoalInfo0, FollowVars, Goal - GoalInfo) :-
-	goal_info_set_follow_vars(GoalInfo0, FollowVars, GoalInfo).
+goal_set_follow_vars(FollowVars, Goal - GoalInfo0, Goal - GoalInfo) :-
+    goal_info_set_follow_vars(FollowVars, GoalInfo0, GoalInfo).
 
-goal_set_resume_point(Goal - GoalInfo0, ResumePoint, Goal - GoalInfo) :-
-	goal_info_set_resume_point(GoalInfo0, ResumePoint, GoalInfo).
+goal_set_resume_point(ResumePoint, Goal - GoalInfo0, Goal - GoalInfo) :-
+    goal_info_set_resume_point(ResumePoint, GoalInfo0, GoalInfo).
 
 goal_info_resume_vars_and_loc(Resume, Vars, Locs) :-
 	(
@@ -618,33 +620,32 @@
 
 %-----------------------------------------------------------------------------%
 
-rename_vars_in_llds_code_gen_info(Details0, Must, Subn, Details) :-
+rename_vars_in_llds_code_gen_info(Must, Subn, Details0, Details) :-
 	Details0 = llds_code_gen_details(PreBirths0, PostBirths0,
 		PreDeaths0, PostDeaths0, MaybeFollowVars0, StoreMap0,
 		ResumePoint0, MaybeNeed0),
-	rename_vars_in_var_set(PreBirths0, Must, Subn, PreBirths),
-	rename_vars_in_var_set(PostBirths0, Must, Subn, PostBirths),
-	rename_vars_in_var_set(PreDeaths0, Must, Subn, PreDeaths),
-	rename_vars_in_var_set(PostDeaths0, Must, Subn, PostDeaths),
+    rename_vars_in_var_set(Must, Subn, PreBirths0, PreBirths),
+    rename_vars_in_var_set(Must, Subn, PostBirths0, PostBirths),
+    rename_vars_in_var_set(Must, Subn, PreDeaths0, PreDeaths),
+    rename_vars_in_var_set(Must, Subn, PostDeaths0, PostDeaths),
 	(
 		MaybeFollowVars0 = no,
 		MaybeFollowVars = no
 	;
 		MaybeFollowVars0 = yes(FollowVars0),
 		FollowVars0 = abs_follow_vars(FollowVarsMap0, FirstFreeReg),
-		rename_vars_in_var_locn_map(FollowVarsMap0, Must, Subn,
-			FollowVarsMap),
+        rename_vars_in_var_locn_map(Must, Subn,
+            FollowVarsMap0, FollowVarsMap),
 		FollowVars = abs_follow_vars(FollowVarsMap, FirstFreeReg),
 		MaybeFollowVars = yes(FollowVars)
 	),
-	rename_vars_in_var_locn_map(StoreMap0, Must, Subn, StoreMap),
+    rename_vars_in_var_locn_map(Must, Subn, StoreMap0, StoreMap),
 	(
 		ResumePoint0 = no_resume_point,
 		ResumePoint = no_resume_point
 	;
 		ResumePoint0 = resume_point(ResumePointVars0, ResumeLocs),
-		rename_vars_in_var_set(ResumePointVars0, Must, Subn,
-			ResumePointVars),
+        rename_vars_in_var_set(Must, Subn, ResumePointVars0, ResumePointVars),
 		ResumePoint = resume_point(ResumePointVars, ResumeLocs)
 	),
 	(
@@ -654,30 +655,24 @@
 		MaybeNeed0 = need_call(NeedAcrossCall0),
 		NeedAcrossCall0 = need_across_call(ForwardVars0,
 			CallResumeVars0, CallNondetLiveVars0),
-		rename_vars_in_var_set(ForwardVars0, Must, Subn,
-			ForwardVars),
-		rename_vars_in_var_set(CallResumeVars0, Must, Subn,
-			CallResumeVars),
-		rename_vars_in_var_set(CallNondetLiveVars0, Must, Subn,
-			CallNondetLiveVars),
+        rename_vars_in_var_set(Must, Subn, ForwardVars0, ForwardVars),
+        rename_vars_in_var_set(Must, Subn, CallResumeVars0, CallResumeVars),
+        rename_vars_in_var_set(Must, Subn,
+            CallNondetLiveVars0, CallNondetLiveVars),
 		NeedAcrossCall = need_across_call(ForwardVars,
 			CallResumeVars, CallNondetLiveVars),
 		MaybeNeed = need_call(NeedAcrossCall)
 	;
 		MaybeNeed0 = need_resume(NeedInResume0),
-		NeedInResume0 = need_in_resume(OnStack, ResumeVars0,
-			NondetLiveVars0),
-		rename_vars_in_var_set(ResumeVars0, Must, Subn,
-			ResumeVars),
-		rename_vars_in_var_set(NondetLiveVars0, Must, Subn,
-			NondetLiveVars),
-		NeedInResume = need_in_resume(OnStack, ResumeVars,
-			NondetLiveVars),
+        NeedInResume0 = need_in_resume(OnStack, ResumeVars0, NondetLiveVars0),
+        rename_vars_in_var_set(Must, Subn, ResumeVars0, ResumeVars),
+        rename_vars_in_var_set(Must, Subn, NondetLiveVars0, NondetLiveVars),
+        NeedInResume = need_in_resume(OnStack, ResumeVars, NondetLiveVars),
 		MaybeNeed = need_resume(NeedInResume)
 	;
 		MaybeNeed0 = need_par_conj(NeedInParConj0),
 		NeedInParConj0 = need_in_par_conj(ParConjVars0),
-		rename_vars_in_var_set(ParConjVars0, Must, Subn, ParConjVars),
+        rename_vars_in_var_set(Must, Subn, ParConjVars0, ParConjVars),
 		NeedInParConj = need_in_par_conj(ParConjVars),
 		MaybeNeed = need_par_conj(NeedInParConj)
 	),
@@ -685,24 +680,23 @@
 		PreDeaths, PostDeaths, MaybeFollowVars, StoreMap,
 		ResumePoint, MaybeNeed).
 
-:- pred rename_vars_in_var_locn_map(map(prog_var, abs_locn)::in,
-	bool::in, map(prog_var, prog_var)::in, map(prog_var, abs_locn)::out)
-	is det.
+:- pred rename_vars_in_var_locn_map(bool::in, map(prog_var, prog_var)::in,
+    map(prog_var, abs_locn)::in, map(prog_var, abs_locn)::out) is det.
 
-rename_vars_in_var_locn_map(VarLocnMap0, Must, Subn, VarLocnMap) :-
+rename_vars_in_var_locn_map(Must, Subn, VarLocnMap0, VarLocnMap) :-
 	map__to_assoc_list(VarLocnMap0, VarLocnList0),
-	rename_vars_in_var_locn_list(VarLocnList0, Must, Subn, VarLocnList),
+    rename_vars_in_var_locn_list(Must, Subn, VarLocnList0, VarLocnList),
 	map__from_assoc_list(VarLocnList, VarLocnMap).
 
-:- pred rename_vars_in_var_locn_list(assoc_list(prog_var, abs_locn)::in,
-	bool::in, map(prog_var, prog_var)::in,
+:- pred rename_vars_in_var_locn_list(bool::in, map(prog_var, prog_var)::in,
+    assoc_list(prog_var, abs_locn)::in,
 	assoc_list(prog_var, abs_locn)::out) is det.
 
-rename_vars_in_var_locn_list([], _Must, _Subn, []).
-rename_vars_in_var_locn_list([Var0 - Locn | VarLocns0], Must, Subn,
-		[Var - Locn | VarLocns]) :-
-	rename_var(Var0, Must, Subn, Var),
-	rename_vars_in_var_locn_list(VarLocns0, Must, Subn, VarLocns).
+rename_vars_in_var_locn_list(_Must, _Subn, [], []).
+rename_vars_in_var_locn_list(Must, Subn,
+        [Var0 - Locn | VarLocns0], [Var - Locn | VarLocns]) :-
+    rename_var(Must, Subn, Var0, Var),
+    rename_vars_in_var_locn_list(Must, Subn, VarLocns0, VarLocns).
 
 %-----------------------------------------------------------------------------%
 
Index: compiler/inlining.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/inlining.m,v
retrieving revision 1.123
diff -u -b -r1.123 inlining.m
--- compiler/inlining.m	22 Jul 2005 12:31:55 -0000	1.123
+++ compiler/inlining.m	28 Aug 2005 02:15:24 -0000
@@ -1,84 +1,86 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1994-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
 %-----------------------------------------------------------------------------%
-
+%
 % Main author: conway.
+%
+% This module inlines
+%
+%	* (--inline-simple and --inline-simple-threshold N)
+%	  procedures whose size is below the given threshold,
+%	  PLUS
+%	  procedures that are flat (ie contain no branched structures)
+%	  and are composed of inline builtins (eg arithmetic),
+%	  and whose size is less than three times the given threshold
+%	  (XXX shouldn't hard-code 3)
+%
+%	* (--inline-compound-threshold N)
+%	  procedures where the product of the number of calls to them
+%	  and their size is below a given threshold.
+%
+%	* (--inline-single-use)
+%	  procedures which are called only once
+%
+% 	* procedures which have a `:- pragma inline(name/arity).'
+%
+% It will not inline procedures which have a
+% 	`:- pragma no_inline(name/arity).'
+%
+% If inlining a procedure takes the total number of variables over
+% a given threshold (from a command-line option), then the procedure
+% is not inlined - note that this means that some calls to a
+% procedure may inlined while others are not.
+%
+% It builds the call-graph (if necessary) works from the bottom of
+% the call-graph towards the top, first performing inlining on a
+% procedure then deciding if calls to it (higher in the call-graph)
+% should be inlined. SCCs get flattend and processed in the order
+% returned by hlds_dependency_info_get_dependency_ordering.
+%
+% There are a couple of classes of procedure that we clearly want
+% to inline because doing so *reduces* the size of the generated
+% code:
+%
+%	- access predicates that get or set one or more fields
+%	  of a structure (Inlining these is almost always a win
+%	  because the infrastructure for the call to the procedure
+%	  is almost always larger than the code to do the access.
+%	  In the case of `get' accessors, the call usually becomes
+%	  a single `field' expression to get the relevant field of
+%	  the structure. In the case of `set' accessors, it is a bit
+%	  more complicated since the code to copy the fields can be
+%	  quite big if there are lots of fields, however in the case
+%	  where several `set' accessors get called one after the other,
+%	  inlining them enables the code generator to avoid creating
+%	  the intermediate structures which is often a win).
+%
+%	- arithmetic predicates where as above, the cost of the
+%	  call will often outweigh the cost of the arithmetic.
+%
+%	- det or semi pragma C code, where often the C operation is
+%	  very small, inlining avoids a call and allows the C compiler
+%	  to do a better job of optimizing it.
+%
+% The threshold on the size of simple goals (which covers both of the
+% first two cases above), is to prevent the inlining of large goals
+% such as those that construct big terms where the duplication is
+% usually inappropriate (for example in nrev).
+%
+% The threshold on the number of variables in a procedure is to prevent
+% the problem of inlining lots of calls and having a resulting
+% procedure with so many variables that the back end of the compiler
+% gets bogged down (for example in the pseudoknot benchmark).
+%
+% Due to the way in which we generate code for model_non
+% pragma_foreign_code, procedures whose body is such a
+% pragma_foreign_code must NOT be inlined.
 
 :- module transform_hlds__inlining.
 
-	% This module inlines
-	%
-	%	* (--inline-simple and --inline-simple-threshold N)
-	%	  procedures whose size is below the given threshold,
-	%	  PLUS
-	%	  procedures that are flat (ie contain no branched structures)
-	%	  and are composed of inline builtins (eg arithmetic),
-	%	  and whose size is less than three times the given threshold
-	%	  (XXX shouldn't hard-code 3)
-	%
-	%	* (--inline-compound-threshold N)
-	%	  procedures where the product of the number of calls to them
-	%	  and their size is below a given threshold.
-	%
-	%	* (--inline-single-use)
-	%	  procedures which are called only once
-	%
-	% 	* procedures which have a `:- pragma inline(name/arity).'
-	%
-	% It will not inline procedures which have a
-	% 	`:- pragma no_inline(name/arity).'
-	%
-	% If inlining a procedure takes the total number of variables over
-	% a given threshold (from a command-line option), then the procedure
-	% is not inlined - note that this means that some calls to a
-	% procedure may inlined while others are not.
-	%
-	% It builds the call-graph (if necessary) works from the bottom of
-	% the call-graph towards the top, first performing inlining on a
-	% procedure then deciding if calls to it (higher in the call-graph)
-	% should be inlined. SCCs get flattend and processed in the order
-	% returned by hlds_dependency_info_get_dependency_ordering.
-	%
-	% There are a couple of classes of procedure that we clearly want
-	% to inline because doing so *reduces* the size of the generated
-	% code:
-	%
-	%	- access predicates that get or set one or more fields
-	%	  of a structure (Inlining these is almost always a win
-	%	  because the infrastructure for the call to the procedure
-	%	  is almost always larger than the code to do the access.
-	%	  In the case of `get' accessors, the call usually becomes
-	%	  a single `field' expression to get the relevant field of
-	%	  the structure. In the case of `set' accessors, it is a bit
-	%	  more complicated since the code to copy the fields can be
-	%	  quite big if there are lots of fields, however in the case
-	%	  where several `set' accessors get called one after the other,
-	%	  inlining them enables the code generator to avoid creating
-	%	  the intermediate structures which is often a win).
-	%
-	%	- arithmetic predicates where as above, the cost of the
-	%	  call will often outweigh the cost of the arithmetic.
-	%
-	%	- det or semi pragma C code, where often the C operation is
-	%	  very small, inlining avoids a call and allows the C compiler
-	%	  to do a better job of optimizing it.
-	%
-	% The threshold on the size of simple goals (which covers both of the
-	% first two cases above), is to prevent the inlining of large goals
-	% such as those that construct big terms where the duplication is
-	% usually inappropriate (for example in nrev).
-	%
-	% The threshold on the number of variables in a procedure is to prevent
-	% the problem of inlining lots of calls and having a resulting
-	% procedure with so many variables that the back end of the compiler
-	% gets bogged down (for example in the pseudoknot benchmark).
-	%
-	% Due to the way in which we generate code for model_non
-	% pragma_foreign_code, procedures whose body is such a
-	% pragma_foreign_code must NOT be inlined.
-
 %-----------------------------------------------------------------------------%
 
 :- interface.
@@ -95,6 +97,8 @@
 
 :- pred inlining(module_info::in, module_info::out, io::di, io::uo) is det.
 
+	% This heuristic is used for both local and intermodule inlining.
+    %
 :- pred inlining__is_simple_clause_list(list(clause)::in, int::in) is semidet.
 
 :- pred inlining__is_simple_goal(hlds_goal::in, int::in) is semidet.
@@ -109,6 +113,7 @@
 	% for the called goal and various information about the variables
 	% and types in the procedure currently being analysed, rename the
 	% goal for the called procedure so that it can be inlined.
+    %
 :- pred inlining__do_inline_call(list(tvar)::in, list(prog_var)::in,
 	pred_info::in, proc_info::in, prog_varset::in, prog_varset::out,
 	vartypes::in, vartypes::out, tvarset::in, tvarset::out,
@@ -119,6 +124,7 @@
 	%
 	% Work out a type substitution to map the callee's argument
 	% types into the caller's.
+    %
 :- pred inlining__get_type_substitution(list(type)::in, list(type)::in,
 	head_type_params::in, list(tvar)::in, map(tvar, type)::out) is det.
 
@@ -126,6 +132,7 @@
 	%	CallerVarSet0, CalleeVarSet, CallerVarSet,
 	%	CallerVarTypes0, CalleeVarTypes, CallerVarTypes,
 	%	VarRenaming, CalledGoal, RenamedGoal).
+    %
 :- pred inlining__rename_goal(list(prog_var)::in, list(prog_var)::in,
 	prog_varset::in, prog_varset::in, prog_varset::out,
 	vartypes::in, vartypes::in, vartypes::out,
@@ -135,6 +142,7 @@
 	% 	InlinePromisedPure, CallingPredMarkers, ModuleInfo).
 	%
 	% Determine whether a predicate can be inlined.
+    %
 :- pred inlining__can_inline_proc(pred_id::in, proc_id::in, builtin_state::in,
 	bool::in, pred_markers::in, module_info::in) is semidet.
 
@@ -216,8 +224,7 @@
 		CompoundThreshold),
 	globals__lookup_int_option(Globals, inline_simple_threshold,
 		SimpleThreshold),
-	globals__lookup_int_option(Globals, inline_vars_threshold,
-		VarThreshold),
+	globals__lookup_int_option(Globals, inline_vars_threshold, VarThreshold),
 	globals__lookup_bool_option(Globals, highlevel_code, HighLevelCode),
 	globals__io_get_trace_level(TraceLevel, !IO),
 	AnyTracing = bool__not(given_trace_level_is_none(TraceLevel)),
@@ -239,17 +246,15 @@
 		map__init(NeededMap)
 	),
 
-		% build the call graph and extract the topological sort
-		% Note: the topological sort returns a list of SCCs.
-		% Clearly, we want to process the SCCs bottom to top
-		% (which is the order that they are returned), but it
-		% is not easy to guess the best way to flatten each SCC
-		% to achieve the best result. The current implementation
-		% just uses the ordering of the list returned by the
-		% topological sort. A more sophisticated approach would be
-		% to break the cycle so that the procedure(s) that are called
-		% by higher SCCs are processed last, but we do not implement
-		% that yet.
+    % Build the call graph and extract the topological sort.
+    % Note: the topological sort returns a list of SCCs. Clearly, we want to
+    % process the SCCs bottom to top (which is the order that they are
+    % returned), but it is not easy to guess the best way to flatten each SCC
+    % to achieve the best result. The current implementation just uses the
+    % ordering of the list returned by the topological sort. A more
+    % sophisticated approach would be to break the cycle so that
+    % the procedure(s) that are called by higher SCCs are processed last,
+    % but we do not implement that yet.
 	module_info_ensure_dependency_info(!ModuleInfo),
 	module_info_dependency_info(!.ModuleInfo, DepInfo),
 	hlds_dependency_info_get_dependency_ordering(DepInfo, SCCs),
@@ -258,8 +263,7 @@
 	inlining__do_inlining(PredProcs, NeededMap, Params, InlinedProcs0,
 		!ModuleInfo, !IO),
 
-		% The dependency graph is now out of date and
-		% needs to be rebuilt.
+    % The dependency graph is now out of date and needs to be rebuilt.
 	module_info_clobber_dependency_info(!ModuleInfo).
 
 :- pred inlining__do_inlining(list(pred_proc_id)::in, needed_map::in,
@@ -273,15 +277,13 @@
 	inlining__mark_predproc(PPId, Needed, Params, !.Module, !Inlined, !IO),
 	inlining__do_inlining(PPIds, Needed, Params, !.Inlined, !Module, !IO).
 
+    % This predicate effectively adds implicit `pragma inline' directives
+    % for procedures that match its heuristic.
+    %
 :- pred inlining__mark_predproc(pred_proc_id::in, needed_map::in,
 	inline_params::in, module_info::in,
 	set(pred_proc_id)::in, set(pred_proc_id)::out, io::di, io::uo) is det.
 
-%
-% This predicate effectively adds implicit `pragma inline'
-% directives for procedures that match its heuristic.
-%
-
 inlining__mark_predproc(PredProcId, NeededMap, Params, ModuleInfo,
 		!InlinedProcs, !IO) :-
 	(
@@ -302,8 +304,7 @@
 		%
 		(
 			Simple = yes,
-			inlining__is_simple_goal(CalledGoal,
-				SimpleThreshold)
+			inlining__is_simple_goal(CalledGoal, SimpleThreshold)
 		;
 			CompoundThreshold > 0,
 			map__search(NeededMap, Entity, Needed),
@@ -316,8 +317,7 @@
 			Needed = yes(NumUses),
 			NumUses = 1
 		),
-		% Don't inline recursive predicates
-		% (unless explicitly requested)
+		% Don't inline recursive predicates (unless explicitly requested).
 		\+ goal_calls(CalledGoal, PredProcId)
 	->
 		inlining__mark_proc_as_inlined(PredProcId, ModuleInfo,
@@ -326,8 +326,6 @@
 		true
 	).
 
-	% this heuristic is used for both local and intermodule inlining
-
 inlining__is_simple_clause_list(Clauses, SimpleThreshold) :-
 	clause_list_size(Clauses, Size),
 	(
@@ -404,31 +402,51 @@
 
 :- type inline_info
 	---> inline_info(
-		int,			% variable threshold for inlining
-		bool,			% highlevel_code option
-		bool,			% is executing tracing enabled
-		set(pred_proc_id),	% inlined procs
-		module_info,		% module_info
-		list(tvar),		% universally quantified type vars
+                i_var_threshold     :: int,
+                                    % variable threshold for inlining
+
+                i_highlevel_code    :: bool,
+                                    % highlevel_code option
+
+                i_exec_trace        :: bool,
+                                    % is executing tracing enabled
+
+                i_inlined_procs     :: set(pred_proc_id),
+
+                i_module_info       :: module_info,
+
+                i_univ_caller_tvars :: list(tvar),
+                                    % Universally quantified type vars
 					% occurring in the argument types
 					% for this predicate (the caller,
 					% not the callee).  These are the
 					% ones that must not be bound.
-		pred_markers,		% markers for the current predicate
 
-			% the following fields are updated as a result
-			% of inlining
-		prog_varset,		% varset
-		vartypes,		% variable types
-		tvarset,		% type variables
-		rtti_varmaps,		% information about locations of
+                i_pred_markers      :: pred_markers,
+                                    % markers for the current predicate
+
+                % All the following fields are updated as a result of inlining.
+
+                i_prog_varset 		:: prog_varset,
+                i_vartypes          :: vartypes,
+                i_tvarset           :: tvarset,
+
+                i_rtti_varmaps      :: rtti_varmaps,
+                                    % information about locations of
 					% type_infos and typeclass_infos
-		bool,			% Did we do any inlining in the proc?
-		bool,			% Does the goal need to be
-					% requantified?
-		bool,			% Did we change the determinism
+
+                i_done_any_inlining :: bool,
+                                    % Did we do any inlining in the proc?
+
+                i_need_requant      :: bool,
+                                    % Does the goal need to be requantified?
+
+                i_changed_detism    :: bool,
+                                    % Did we change the determinism
 					% of any subgoal?
-		bool			% Did we change the purity of
+
+                i_changed_purity    :: bool
+                                    % Did we change the purity of
 					% any subgoal.
 	).
 
@@ -797,7 +815,7 @@
 	goal_util__create_variables(CalleeListOfVars,
 		CalleeVarSet, CalleeVarTypes,
 		VarSet0, VarSet, VarTypes1, VarTypes, Subn0, Subn),
-	goal_util__must_rename_vars_in_goal(CalledGoal, Subn, Goal).
+	goal_util__must_rename_vars_in_goal(Subn, CalledGoal, Goal).
 
 %-----------------------------------------------------------------------------%
 
Index: compiler/instmap.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/instmap.m,v
retrieving revision 1.41
diff -u -b -r1.41 instmap.m
--- compiler/instmap.m	27 Aug 2005 09:41:55 -0000	1.41
+++ compiler/instmap.m	27 Aug 2005 17:03:04 -0000
@@ -139,25 +139,24 @@
 :- pred instmap__lookup_vars(list(prog_var)::in, instmap::in, list(inst)::out)
     is det.
 
-    % Insert an entry into an instmap_delta.  Note that you
-    % cannot call instmap_delta_insert for a variable already
-    % present.
+    % Insert an entry into an instmap_delta. Note that you cannot call
+    % instmap_delta_insert for a variable already present.
     %
-:- pred instmap_delta_insert(instmap_delta::in, prog_var::in, (inst)::in,
-    instmap_delta::out) is det.
+:- pred instmap_delta_insert(prog_var::in, (inst)::in,
+    instmap_delta::in, instmap_delta::out) is det.
 
     % Set an entry in an instmap.
     %
-:- pred instmap__set(instmap::in, prog_var::in, (inst)::in, instmap::out)
+:- pred instmap__set(prog_var::in, (inst)::in, instmap::in, instmap::out)
     is det.
 
     % Set multiple entries in an instmap.
     %
-:- pred instmap__set_vars(instmap::in, list(prog_var)::in, list(inst)::in,
-    instmap::out) is det.
+:- pred instmap__set_vars(list(prog_var)::in, list(inst)::in,
+    instmap::in, instmap::out) is det.
 
-:- pred instmap_delta_set(instmap_delta::in, prog_var::in, (inst)::in,
-    instmap_delta::out) is det.
+:- pred instmap_delta_set(prog_var::in, (inst)::in,
+    instmap_delta::in, instmap_delta::out) is det.
 
     % Bind a variable in an instmap to a functor at the beginning
     % of a case in a switch. Aborts on compiler generated cons_ids.
@@ -223,20 +222,20 @@
     % instmap__restrict takes an instmap and a set of vars and returns
     % an instmap with its domain restricted to those vars.
     %
-:- pred instmap__restrict(instmap::in, set(prog_var)::in, instmap::out)
+:- pred instmap__restrict(set(prog_var)::in, instmap::in, instmap::out)
     is det.
 
     % instmap_delta_restrict takes an instmap and a set of vars and returns
     % an instmap_delta with its domain restricted to those vars.
     %
-:- pred instmap_delta_restrict(instmap_delta::in, set(prog_var)::in,
-    instmap_delta::out) is det.
+:- pred instmap_delta_restrict(set(prog_var)::in,
+    instmap_delta::in, instmap_delta::out) is det.
 
     % instmap_delta_delete_vars takes an instmap_delta and a list of vars
     % and returns an instmap_delta with those vars removed from its domain.
     %
-:- pred instmap_delta_delete_vars(instmap_delta::in, list(prog_var)::in,
-    instmap_delta::out) is det.
+:- pred instmap_delta_delete_vars(list(prog_var)::in,
+    instmap_delta::in, instmap_delta::out) is det.
 
     % `instmap__no_output_vars(Instmap, InstmapDelta, Vars, ModuleInfo)'
     % is true if none of the vars in the set Vars could have become more
@@ -278,17 +277,17 @@
 
 %-----------------------------------------------------------------------------%
 
-    % `instmap_delta_apply_sub(InstmapDelta0, Must, Sub, InstmapDelta)'
+    % `instmap_delta_apply_sub(Must, Sub, InstmapDelta0, InstmapDelta)'
     % the variable substitution Sub to InstmapDelta0 to get the new
     % instmap_delta InstmapDelta.  If there is a variable in
     % InstmapDelta0 which does not appear in Sub, it is ignored if
     % Must is set to no, otherwise it is an error.
     %
-:- pred instmap_delta_apply_sub(instmap_delta::in, bool::in,
-    map(prog_var, prog_var)::in, instmap_delta::out) is det.
+:- pred instmap_delta_apply_sub(bool::in, map(prog_var, prog_var)::in,
+    instmap_delta::in, instmap_delta::out) is det.
 
-:- pred instmap__apply_sub(instmap::in, bool::in, map(prog_var, prog_var)::in,
-    instmap::out) is det.
+:- pred instmap__apply_sub(bool::in, map(prog_var, prog_var)::in,
+    instmap::in, instmap::out) is det.
 
 %-----------------------------------------------------------------------------%
 
@@ -393,7 +392,7 @@
     ( Inst1 = Inst2 ->
         instmap_delta_from_mode_list_2(Vars, Modes, ModuleInfo, !InstMapDelta)
     ;
-        instmap_delta_set(!.InstMapDelta, Var, Inst2, !:InstMapDelta),
+        instmap_delta_set(Var, Inst2, !InstMapDelta),
         instmap_delta_from_mode_list_2(Vars, Modes, ModuleInfo, !InstMapDelta)
     ).
 
@@ -465,21 +464,21 @@
     instmap__lookup_var(InstMap, Arg, Inst),
     instmap__lookup_vars(Args, InstMap, Insts).
 
-instmap__set(unreachable, _Var, _Inst, unreachable).
-instmap__set(reachable(InstMapping0), Var, Inst, reachable(InstMapping)) :-
+instmap__set(_Var, _Inst, unreachable, unreachable).
+instmap__set(Var, Inst, reachable(InstMapping0), reachable(InstMapping)) :-
     map__set(InstMapping0, Var, Inst, InstMapping).
 
-instmap__set_vars(InstMap, [], [], InstMap).
-instmap__set_vars(InstMap0, [V | Vs], [I | Is], InstMap) :-
-    instmap__set(InstMap0, V, I, InstMap1),
-    instmap__set_vars(InstMap1, Vs, Is, InstMap).
-instmap__set_vars(_, [_ | _], [], _) :-
+instmap__set_vars([], [], !InstMap).
+instmap__set_vars([V | Vs], [I | Is], !InstMap) :-
+    instmap__set(V, I, !InstMap),
+    instmap__set_vars(Vs, Is, !InstMap).
+instmap__set_vars([_ | _], [], !InstMap) :-
     error("instmap__set_vars").
-instmap__set_vars(_, [], [_ | _], _) :-
+instmap__set_vars([], [_ | _], !InstMap) :-
     error("instmap__set_vars").
 
-instmap_delta_set(unreachable, _Var, _Inst, unreachable).
-instmap_delta_set(reachable(InstMapping0), Var, Inst, Instmap) :-
+instmap_delta_set(_Var, _Inst, unreachable, unreachable).
+instmap_delta_set(Var, Inst, reachable(InstMapping0), Instmap) :-
     ( Inst = not_reached ->
         Instmap = unreachable
     ;
@@ -487,8 +486,8 @@
         Instmap = reachable(InstMapping)
     ).
 
-instmap_delta_insert(unreachable, _Var, _Inst, unreachable).
-instmap_delta_insert(reachable(InstMapping0), Var, Inst, Instmap) :-
+instmap_delta_insert(_Var, _Inst, unreachable, unreachable).
+instmap_delta_insert(Var, Inst, reachable(InstMapping0), Instmap) :-
     ( Inst = not_reached ->
         Instmap = unreachable
     ;
@@ -498,13 +497,12 @@
 
 %-----------------------------------------------------------------------------%
 
-instmap_delta_bind_var_to_functor(Var, Type, ConsId, InstMap,
-        InstmapDelta0, InstmapDelta, !ModuleInfo) :-
+instmap_delta_bind_var_to_functor(Var, Type, ConsId, InstMap, !InstmapDelta,
+        !ModuleInfo) :-
     (
-        InstmapDelta0 = unreachable,
-        InstmapDelta = unreachable
+        !.InstmapDelta = unreachable
     ;
-        InstmapDelta0 = reachable(InstmappingDelta0),
+        !.InstmapDelta = reachable(InstmappingDelta0),
 
         % Get the initial inst from the InstMap
         instmap__lookup_var(InstMap, Var, OldInst),
@@ -516,22 +514,20 @@
         ;
             NewInst1 = OldInst
         ),
-        bind_inst_to_functor(Type, ConsId, NewInst1, NewInst,
-            !ModuleInfo),
+        bind_inst_to_functor(Type, ConsId, NewInst1, NewInst, !ModuleInfo),
 
-        % add `Var :: OldInst -> NewInst' to the instmap delta.
+        % Add `Var :: OldInst -> NewInst' to the instmap delta.
         ( NewInst \= OldInst ->
-            instmap_delta_set(InstmapDelta0, Var, NewInst, InstmapDelta)
+            instmap_delta_set(Var, NewInst, !InstmapDelta)
         ;
-            InstmapDelta = InstmapDelta0
+            true
         )
     ).
 
-instmap__bind_var_to_functor(Var, Type, ConsId, InstMap0, InstMap,
-        !ModuleInfo) :-
-    instmap__lookup_var(InstMap0, Var, Inst0),
+instmap__bind_var_to_functor(Var, Type, ConsId, !InstMap, !ModuleInfo) :-
+    instmap__lookup_var(!.InstMap, Var, Inst0),
     bind_inst_to_functor(Type, ConsId, Inst0, Inst, !ModuleInfo),
-    instmap__set(InstMap0, Var, Inst, InstMap).
+    instmap__set(Var, Inst, !InstMap).
 
 :- pred bind_inst_to_functor((type)::in, cons_id::in, (inst)::in, (inst)::out,
     module_info::in, module_info::out) is det.
@@ -603,17 +599,17 @@
 
 %-----------------------------------------------------------------------------%
 
-instmap__restrict(unreachable, _, unreachable).
-instmap__restrict(reachable(InstMapping0), Vars, reachable(InstMapping)) :-
+instmap__restrict(_, unreachable, unreachable).
+instmap__restrict(Vars, reachable(InstMapping0), reachable(InstMapping)) :-
     map__select(InstMapping0, Vars, InstMapping).
 
-instmap_delta_restrict(unreachable, _, unreachable).
-instmap_delta_restrict(reachable(InstMapping0), Vars, reachable(InstMapping)) :-
+instmap_delta_restrict(_, unreachable, unreachable).
+instmap_delta_restrict(Vars, reachable(InstMapping0), reachable(InstMapping)) :-
     map__select(InstMapping0, Vars, InstMapping).
 
-instmap_delta_delete_vars(unreachable, _, unreachable).
-instmap_delta_delete_vars(reachable(InstMapping0), Vars,
-        reachable(InstMapping)) :-
+instmap_delta_delete_vars(_, unreachable, unreachable).
+instmap_delta_delete_vars(Vars,
+        reachable(InstMapping0), reachable(InstMapping)) :-
     map__delete_list(InstMapping0, Vars, InstMapping).
 
 %-----------------------------------------------------------------------------%
@@ -624,33 +620,31 @@
     % or if-then-else, and update the instantiatedness of all the nonlocal
     % variables, checking that it is the same for every branch.
     %
-instmap__merge(NonLocals, InstMapList, MergeContext, ModeInfo0, ModeInfo) :-
-    mode_info_get_instmap(ModeInfo0, InstMap0),
-    mode_info_get_module_info(ModeInfo0, ModuleInfo0),
+instmap__merge(NonLocals, InstMapList, MergeContext, !ModeInfo) :-
+    mode_info_get_instmap(!.ModeInfo, InstMap0),
+    mode_info_get_module_info(!.ModeInfo, ModuleInfo0),
     get_reachable_instmaps(InstMapList, InstMappingList),
     ( InstMappingList = [] ->
-        InstMap = unreachable,
-        ModeInfo2 = ModeInfo0
+        InstMap = unreachable
     ; InstMap0 = reachable(InstMapping0) ->
         set__to_sorted_list(NonLocals, NonLocalsList),
-        mode_info_get_var_types(ModeInfo0, VarTypes),
+        mode_info_get_var_types(!.ModeInfo, VarTypes),
         instmap__merge_2(NonLocalsList, InstMapList, VarTypes,
             InstMapping0, InstMapping, ModuleInfo0, ModuleInfo, ErrorList),
-        mode_info_set_module_info(ModuleInfo, ModeInfo0, ModeInfo1),
+        mode_info_set_module_info(ModuleInfo, !ModeInfo),
         ( ErrorList = [FirstError | _] ->
             FirstError = Var - _,
             set__singleton_set(WaitingVars, Var),
             mode_info_error(WaitingVars,
-                mode_error_disj(MergeContext, ErrorList), ModeInfo1, ModeInfo2)
+                mode_error_disj(MergeContext, ErrorList), !ModeInfo)
         ;
-            ModeInfo2 = ModeInfo1
+            true
         ),
         InstMap = reachable(InstMapping)
     ;
-        InstMap = unreachable,
-        ModeInfo2 = ModeInfo0
+        InstMap = unreachable
     ),
-    mode_info_set_instmap(InstMap, ModeInfo2, ModeInfo).
+    mode_info_set_instmap(InstMap, !ModeInfo).
 
 :- pred get_reachable_instmaps(list(instmap)::in,
     list(map(prog_var, inst))::out) is det.
@@ -1045,15 +1039,15 @@
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
-instmap_delta_apply_sub(unreachable, _Must, _Sub, unreachable).
-instmap_delta_apply_sub(reachable(OldInstMapping), Must, Sub,
-        reachable(InstMapping)) :-
+instmap_delta_apply_sub(_Must, _Sub, unreachable, unreachable).
+instmap_delta_apply_sub(Must, Sub,
+        reachable(OldInstMapping), reachable(InstMapping)) :-
     map__to_assoc_list(OldInstMapping, InstMappingAL),
     instmap_delta_apply_sub_2(InstMappingAL, Must, Sub,
         map__init, InstMapping).
 
-instmap__apply_sub(InstMap0, Must, Sub, InstMap) :-
-    instmap_delta_apply_sub(InstMap0, Must, Sub, InstMap).
+instmap__apply_sub(Must, Sub, InstMap0, InstMap) :-
+    instmap_delta_apply_sub(Must, Sub, InstMap0, InstMap).
 
 :- pred instmap_delta_apply_sub_2(assoc_list(prog_var, inst)::in, bool::in,
     map(prog_var, prog_var)::in, instmapping::in, instmapping::out) is det.
Index: compiler/interval.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/interval.m,v
retrieving revision 1.5
diff -u -b -r1.5 interval.m
--- compiler/interval.m	12 Aug 2005 05:14:12 -0000	1.5
+++ compiler/interval.m	27 Aug 2005 16:52:29 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 2002-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -49,8 +51,8 @@
 	--->	call_site
 	;	resume_point.
 
-:- type save_point --->
-	save_point(
+:- type save_point
+    --->    save_point(
 		save_point_type,
 		goal_path
 	).
@@ -76,15 +78,15 @@
 
 :- type interval_id	--->	interval_id(int).
 
-:- type branch_end_info --->
-	branch_end_info(
+:- type branch_end_info
+    --->    branch_end_info(
 		flushed_after_branch	:: set(prog_var),
 		accessed_after_branch	:: set(prog_var),
 		interval_after_branch	:: interval_id
 	).
 
-:- type insert_spec --->
-	insert_spec(
+:- type insert_spec
+    --->    insert_spec(
 		hlds_goal,
 		set(prog_var)
 	).
@@ -93,8 +95,8 @@
 
 :- type anchor_follow_info	==	pair(set(prog_var), set(interval_id)).
 
-:- type interval_params --->
-	interval_params(
+:- type interval_params
+    --->    interval_params(
 		module_info		:: module_info,
 		var_types		:: vartypes,
 		at_most_zero_calls	:: bool
@@ -117,8 +119,7 @@
 		interval_end		:: map(interval_id, anchor),
 		interval_succ		:: map(interval_id, list(interval_id)),
 		interval_vars		:: map(interval_id, set(prog_var)),
-		interval_delvars	:: map(interval_id,
-						list(set(prog_var)))
+        interval_delvars    :: map(interval_id, list(set(prog_var)))
 	).
 
 :- type maybe_needs_flush
@@ -126,14 +127,12 @@
 	;	doesnt_need_flush.
 
 :- typeclass build_interval_info_acc(T) where [
-        pred use_cell(prog_var::in, list(prog_var)::in, cons_id::in,
-                hlds_goal::in, interval_info::in, interval_info::out,
-		T::in, T::out) is det
+    pred use_cell(prog_var::in, list(prog_var)::in, cons_id::in, hlds_goal::in,
+        interval_info::in, interval_info::out, T::in, T::out) is det
 ].
 
 :- pred build_interval_info_in_goal(hlds_goal::in, interval_info::in,
-	interval_info::out, T::in, T::out) is det
-	<= build_interval_info_acc(T).
+    interval_info::out, T::in, T::out) is det <= build_interval_info_acc(T).
 
 :- pred record_interval_vars(interval_id::in, list(prog_var)::in,
 	interval_info::in, interval_info::out) is det.
@@ -152,16 +151,16 @@
 	vartypes::in, vartypes::out, rename_map::in, rename_map::out,
 	insert_spec::in, maybe(goal_feature)::in, hlds_goal::out) is det.
 
-% The final RenameMap may ask for some of the head variables to be renamed.
-% Doing so is inconvenient, e.g. because the debugger wants head variables to
-% have names of a fixed form. Instead, we exploit the fact that the
-% transformation does not care about actual variable names or even numbers;
-% all it cares about wrt renaming is that the variables it has renamed apart
-% should stay renamed apart. We therefore swap the roles of the original and
-% the renamed variable in the goal representing the procedure body. The
-% resulting procedure definition will be isomorphic to the one we would have
-% get by applying the original renaming to the headvars.
-
+    % The final RenameMap may ask for some of the head variables to be renamed.
+    % Doing so is inconvenient, e.g. because the debugger wants head variables
+    % to have names of a fixed form. Instead, we exploit the fact that the
+    % transformation does not care about actual variable names or even numbers;
+    % all it cares about wrt renaming is that the variables it has renamed
+    % apart should stay renamed apart. We therefore swap the roles of the
+    % original and the renamed variable in the goal representing the procedure
+    % body. The resulting procedure definition will be isomorphic to the one
+    % we would have get by applying the original renaming to the headvars.
+    %
 :- pred apply_headvar_correction(set(prog_var)::in, rename_map::in,
 	hlds_goal::in, hlds_goal::out) is det.
 
@@ -192,6 +191,7 @@
 :- import_module ll_backend__liveness.
 :- import_module ll_backend__live_vars.
 :- import_module ll_backend__store_alloc.
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__mercury_to_mercury.
 :- import_module parse_tree__prog_type.
 
@@ -213,7 +213,8 @@
 	build_interval_info_in_par_conj(Goals, !IntervalInfo, !Acc).
 
 build_interval_info_in_goal(disj(Goals) - GoalInfo, !IntervalInfo, !Acc) :-
-	( Goals = [FirstDisjunct | _] ->
+    (
+        Goals = [FirstDisjunct | _],
 		reached_branch_end(GoalInfo, yes(FirstDisjunct), disj,
 			StartAnchor, EndAnchor, BeforeId, AfterId,
 			MaybeResumeVars, !IntervalInfo, !Acc),
@@ -223,6 +224,7 @@
 		leave_branch_start(disj, StartAnchor, BeforeId,
 			MaybeResumeVars, OpenIntervals, !IntervalInfo)
 	;
+        Goals = [],
 		% We could reset the set of variables in the current interval
 		% to the empty set, since any variable accesses after a fail
 		% goal (which is what an empty disjunction represent) will not
@@ -285,8 +287,8 @@
 	VarTypes = IntParams ^ var_types,
 	list__map(map__lookup(VarTypes), ArgVars, ArgTypes),
 	ModuleInfo = IntParams ^ module_info,
-	arg_info__compute_in_and_out_vars(ModuleInfo, ArgVars,
-		ArgModes, ArgTypes, InputArgs, _OutputArgs),
+    arg_info__compute_in_and_out_vars(ModuleInfo, ArgVars, ArgModes, ArgTypes,
+        InputArgs, _OutputArgs),
 	determinism_to_code_model(Detism, CodeModel),
 
 	% Casts are generated inline.
@@ -298,8 +300,8 @@
 			GenericVarsArgInfos, _),
 		assoc_list__keys(GenericVarsArgInfos, GenericVars),
 		list__append(GenericVars, InputArgs, Inputs),
-		build_interval_info_at_call(Inputs,
-                        MaybeNeedAcrossCall, GoalInfo, !IntervalInfo, !Acc)
+        build_interval_info_at_call(Inputs, MaybeNeedAcrossCall, GoalInfo,
+            !IntervalInfo, !Acc)
 	).
 
 build_interval_info_in_goal(Goal - GoalInfo, !IntervalInfo, !Acc) :-
@@ -316,10 +318,9 @@
 		require_in_regs(Inputs, !IntervalInfo),
 		require_access(Inputs, !IntervalInfo)
 	;
-		goal_info_get_maybe_need_across_call(GoalInfo,
-			MaybeNeedAcrossCall),
-		build_interval_info_at_call(Inputs, MaybeNeedAcrossCall,
-			GoalInfo, !IntervalInfo, !Acc)
+        goal_info_get_maybe_need_across_call(GoalInfo, MaybeNeedAcrossCall),
+        build_interval_info_at_call(Inputs, MaybeNeedAcrossCall, GoalInfo,
+            !IntervalInfo, !Acc)
 	).
 
 build_interval_info_in_goal(Goal - GoalInfo, !IntervalInfo, !Acc) :-
@@ -354,7 +355,7 @@
 		Unification = construct(CellVar, _ConsId, ArgVars, _,
 			HowToConstruct, _, _),
 		( HowToConstruct = reuse_cell(_) ->
-			error("build_interval_info_in_goal: reuse")
+            unexpected(this_file, "build_interval_info_in_goal: reuse")
 		;
 			true
 		),
@@ -370,8 +371,8 @@
 		IntParams = !.IntervalInfo ^ interval_params,
 		ModuleInfo = IntParams ^ module_info,
 		( shared_left_to_right_deconstruct(ModuleInfo, ArgModes) ->
-                        use_cell(CellVar, ArgVars, ConsId, Goal - GoalInfo,
-                                !IntervalInfo, !Acc)
+            use_cell(CellVar, ArgVars, ConsId, Goal - GoalInfo, !IntervalInfo,
+                !Acc)
 		;
 			true
 		),
@@ -387,11 +388,11 @@
 		require_access([Var1, Var2], !IntervalInfo)
 	;
 		Unification = complicated_unify(_, _, _),
-		error("build_interval_info_in_goal: complicated_unify")
+        unexpected(this_file, "build_interval_info_in_goal: complicated_unify")
 	).
 
 build_interval_info_in_goal(shorthand(_) - _, !IntervalInfo, !Acc) :-
-	error("shorthand in build_interval_info_in_goal").
+    unexpected(this_file, "shorthand in build_interval_info_in_goal").
 
 :- pred shared_left_to_right_deconstruct(module_info::in, list(uni_mode)::in)
 	is semidet.
@@ -416,8 +417,8 @@
 		!IntervalInfo, !Acc) :-
 	(
 		MaybeNeedAcrossCall = yes(NeedAcrossCall),
-		NeedAcrossCall = need_across_call(ForwardVars,
-			ResumeVars, NondetLiveVars),
+        NeedAcrossCall = need_across_call(ForwardVars, ResumeVars,
+            NondetLiveVars),
 		VarsOnStack0 = set__union_list([ForwardVars, ResumeVars,
 			NondetLiveVars]),
 		goal_info_get_goal_path(GoalInfo, GoalPath),
@@ -433,8 +434,7 @@
 			; IntParams ^ at_most_zero_calls = no
 			)
 		->
-			record_interval_succ(BeforeCallId, AfterCallId,
-				!IntervalInfo),
+            record_interval_succ(BeforeCallId, AfterCallId, !IntervalInfo),
 			VarsOnStack = VarsOnStack0
 		;
 			% If the call cannot succeed, then execution cannot
@@ -456,7 +456,8 @@
 		require_access(Inputs, !IntervalInfo)
 	;
 		MaybeNeedAcrossCall = no,
-		error("build_interval_info_at_call: no need across call")
+        unexpected(this_file,
+            "build_interval_info_at_call: no need across call")
 	).
 
 %-----------------------------------------------------------------------------%
@@ -546,7 +547,7 @@
 		set__sorted_list_to_set(StoreMapVarList, StoreMapVars),
 		require_flushed(StoreMapVars, !IntervalInfo)
 	;
-		error("reached_branch_end: no store map")
+        unexpected(this_file, "reached_branch_end: no store map")
 	),
 	EndAnchor = branch_end(Construct, GoalPath),
 	StartAnchor = branch_start(Construct, GoalPath),
@@ -574,8 +575,7 @@
 
 :- pred reached_branch_start(maybe_needs_flush::in, anchor::in,
 	interval_id::in, set(interval_id)::out, interval_info::in,
-	interval_info::out, T::in, T::out) is det
-	<= build_interval_info_acc(T).
+    interval_info::out, T::in, T::out) is det <= build_interval_info_acc(T).
 
 reached_branch_start(MaybeNeedsFlush, StartAnchor, BeforeId, OpenIntervals,
 		!IntervalInfo, !Acc) :-
@@ -657,10 +657,8 @@
 		set__init, CurOpenIntervalVars),
 	( map__search(AnchorFollowMap0, Anchor, AnchorFollowInfo0) ->
 		AnchorFollowInfo0 = OpenIntervalVars0 - OpenIntervals0,
-		OpenIntervalVars =
-			set__union(OpenIntervalVars0, CurOpenIntervalVars),
-		OpenIntervals =
-			set__union(OpenIntervals0, CurOpenIntervals),
+        OpenIntervalVars = set__union(OpenIntervalVars0, CurOpenIntervalVars),
+        OpenIntervals = set__union(OpenIntervals0, CurOpenIntervals),
 		AnchorFollowInfo = OpenIntervalVars - OpenIntervals,
 		svmap__det_update(Anchor, AnchorFollowInfo,
 			AnchorFollowMap0, AnchorFollowMap)
@@ -711,10 +709,8 @@
 	AccessedLater = !.IntervalInfo ^ accessed_later,
 	CurInterval = !.IntervalInfo ^ cur_interval,
 	BranchEndMap0 = !.IntervalInfo ^ branch_end_map,
-	BranchEndInfo = branch_end_info(FlushedLater, AccessedLater,
-		CurInterval),
-	svmap__det_insert(GoalPath, BranchEndInfo,
-		BranchEndMap0, BranchEndMap),
+    BranchEndInfo = branch_end_info(FlushedLater, AccessedLater, CurInterval),
+    svmap__det_insert(GoalPath, BranchEndInfo, BranchEndMap0, BranchEndMap),
 	!:IntervalInfo = !.IntervalInfo ^ branch_end_map := BranchEndMap.
 
 :- pred record_cond_end(goal_path::in, interval_info::in, interval_info::out)
@@ -760,7 +756,7 @@
 record_interval_no_succ(Id, !IntervalInfo) :-
 	SuccMap0 = !.IntervalInfo ^ interval_succ,
 	( map__search(SuccMap0, Id, _Succ0) ->
-		error("record_interval_no_succ: already in succ map")
+        unexpected(this_file, "record_interval_no_succ: already in succ map")
 	;
 		svmap__det_insert(Id, [], SuccMap0, SuccMap)
 	),
@@ -849,8 +845,7 @@
 record_decisions_in_goal(!Goal, VarSet0, VarSet, VarTypes0, VarTypes,
 		!VarRename, InsertMap, MaybeFeature) :-
 	record_decisions_in_goal(!Goal, var_info(VarSet0, VarTypes0),
-		var_info(VarSet, VarTypes), !VarRename, InsertMap,
-		MaybeFeature).
+        var_info(VarSet, VarTypes), !VarRename, InsertMap, MaybeFeature).
 
 :- pred record_decisions_in_goal(hlds_goal::in, hlds_goal::out,
 	var_info::in, var_info::out, rename_map::in, rename_map::out,
@@ -879,13 +874,12 @@
 			!.VarRename, _, InsertMap, MaybeFeature),
 		lookup_inserts(InsertMap, StartAnchor, StartInserts),
 		record_decisions_in_disj(LaterGoals0, LaterGoals,
-			!VarInfo, !.VarRename, StartInserts, InsertMap,
-                        MaybeFeature),
+            !VarInfo, !.VarRename, StartInserts, InsertMap, MaybeFeature),
 		Goals = [FirstGoal | LaterGoals],
 		Goal1 = disj(Goals) - GoalInfo0,
 		lookup_inserts(InsertMap, EndAnchor, Inserts),
-		insert_goals_after(Goal1, Goal, !VarInfo, !:VarRename,
-			Inserts, MaybeFeature)
+        insert_goals_after(Goal1, Goal, !VarInfo, !:VarRename, Inserts,
+            MaybeFeature)
 	;
 		Goal = disj(Goals0) - GoalInfo0
 	).
@@ -895,7 +889,7 @@
 	Goal0 = switch(Var0, Det, Cases0) - GoalInfo0,
 	record_decisions_in_cases(Cases0, Cases, !VarInfo, !.VarRename,
 		InsertMap, MaybeFeature),
-	rename_var(Var0, no, !.VarRename, Var),
+    rename_var(no, !.VarRename, Var0, Var),
 	Goal1 = switch(Var, Det, Cases) - GoalInfo0,
 	construct_anchors(switch, Goal0, _StartAnchor, EndAnchor),
 	lookup_inserts(InsertMap, EndAnchor, Inserts),
@@ -918,7 +912,7 @@
                 MaybeFeature) :-
 	Goal0 = if_then_else(Vars0, Cond0, Then0, Else0) - GoalInfo0,
 	construct_anchors(ite, Goal0, StartAnchor, EndAnchor),
-	rename_var_list(Vars0, no, !.VarRename, Vars),
+    rename_var_list(no, !.VarRename, Vars0, Vars),
 	record_decisions_in_goal(Cond0, Cond, !VarInfo, !VarRename, InsertMap,
                 MaybeFeature),
 	record_decisions_in_goal(Then0, Then, !VarInfo, !.VarRename, _,
@@ -941,7 +935,7 @@
 	Goal0 = scope(Reason0, SubGoal0) - GoalInfo,
 	(
 		Reason0 = exist_quant(Vars0),
-		rename_var_list(Vars0, no, !.VarRename, Vars),
+        rename_var_list(no, !.VarRename, Vars0, Vars),
 		Reason = exist_quant(Vars)
 	;
 		Reason0 = promise_purity(_, _),
@@ -957,7 +951,7 @@
 		Reason = Reason0
 	;
 		Reason0 = from_ground_term(Var0),
-		rename_var(Var0, no, !.VarRename, Var),
+        rename_var(no, !.VarRename, Var0, Var),
 		Reason = from_ground_term(Var)
 	),
 	record_decisions_in_goal(SubGoal0, SubGoal, !VarInfo, !VarRename,
@@ -996,10 +990,10 @@
 record_decisions_in_goal(Goal0, Goal, !VarInfo, !VarRename, _InsertMap,
                 _MaybeFeature) :-
 	Goal0 = unify(_, _, _, _, _) - _,
-	rename_vars_in_goal(Goal0, !.VarRename, Goal).
+    rename_vars_in_goal(!.VarRename, Goal0, Goal).
 
 record_decisions_in_goal(shorthand(_) - _, _, !VarInfo, !VarRename, _, _) :-
-	error("shorthand in record_decisions_in_goal").
+    unexpected(this_file, "shorthand in record_decisions_in_goal").
 
 %-----------------------------------------------------------------------------%
 
@@ -1019,11 +1013,10 @@
 
 insert_goals_after(BranchesGoal, Goal, !VarInfo, VarRename, Inserts,
                 MaybeFeature) :-
-	make_inserted_goals(!VarInfo, map__init, VarRename,
-		Inserts, MaybeFeature, InsertGoals),
+    make_inserted_goals(!VarInfo, map__init, VarRename, Inserts, MaybeFeature,
+        InsertGoals),
 	BranchesGoal = _ - BranchesGoalInfo,
-	conj_list_to_goal([BranchesGoal | InsertGoals], BranchesGoalInfo,
-		Goal).
+    conj_list_to_goal([BranchesGoal | InsertGoals], BranchesGoalInfo, Goal).
 
 :- pred make_inserted_goals(var_info::in, var_info::out,
 	rename_map::in, rename_map::out, list(insert_spec)::in,
@@ -1046,13 +1039,12 @@
 		GoalExpr0 = unify(_, _, _, Unification0, _),
 		Unification0 = deconstruct(_, _, ArgVars, _, _, _)
 	->
-		Unification1 = Unification0 ^ deconstruct_can_fail
-			:= cannot_fail,
+        Unification1 = Unification0 ^ deconstruct_can_fail := cannot_fail,
 		GoalExpr1 = GoalExpr0 ^ unify_kind := Unification1,
-		goal_info_set_determinism(GoalInfo0, det, GoalInfo1),
+        goal_info_set_determinism(det, GoalInfo0, GoalInfo1),
         (
             MaybeFeature = yes(Feature),
-            goal_info_add_feature(GoalInfo1, Feature, GoalInfo2)
+            goal_info_add_feature(Feature, GoalInfo1, GoalInfo2)
         ;
             MaybeFeature = no,
             GoalInfo2 = GoalInfo1
@@ -1060,15 +1052,14 @@
 		Goal2 = GoalExpr1 - GoalInfo2,
 		!.VarInfo = var_info(VarSet0, VarTypes0),
 		create_shadow_vars(ArgVars, VarsToExtract, VarSet0, VarSet,
-			VarTypes0, VarTypes, map__init, NewRename,
-			map__init, VoidRename),
+            VarTypes0, VarTypes, map__init, NewRename, map__init, VoidRename),
 		!:VarInfo = var_info(VarSet, VarTypes),
 		map__merge(!.VarRename, NewRename, !:VarRename),
 		% We rename the original goal
-		rename_vars_in_goal(Goal2, !.VarRename, Goal3),
-		rename_vars_in_goal(Goal3, VoidRename, Goal)
+        rename_vars_in_goal(!.VarRename, Goal2, Goal3),
+        rename_vars_in_goal(VoidRename, Goal3, Goal)
 	;
-		error("make_inserted_goal: not a deconstruct")
+        unexpected(this_file, "make_inserted_goal: not a deconstruct")
 	).
 
 make_inserted_goal(VarSet0, VarSet, VarTypes0, VarTypes, !RenameMap,
@@ -1092,8 +1083,7 @@
 
 :- pred create_shadow_var(prog_var::in, set(prog_var)::in,
 	prog_varset::in, prog_varset::out, vartypes::in, vartypes::out,
-	rename_map::in, rename_map::out, rename_map::in, rename_map::out)
-	is det.
+    rename_map::in, rename_map::out, rename_map::in, rename_map::out) is det.
 
 create_shadow_var(Arg, VarsToExtract, !VarSet, !VarTypes,
 		!VarRename, !VoidRename) :-
@@ -1116,7 +1106,7 @@
 record_decisions_at_call_site(Goal0, Goal, !VarInfo, !VarRename,
 		MustHaveMap, InsertMap, MaybeFeature) :-
 	Goal0 = _ - GoalInfo0,
-	rename_vars_in_goal(Goal0, !.VarRename, Goal1),
+    rename_vars_in_goal(!.VarRename, Goal0, Goal1),
 	(
 		goal_info_maybe_get_maybe_need_across_call(GoalInfo0,
 			MaybeNeedAcrossCall),
@@ -1133,7 +1123,7 @@
 			Goal = Goal1
 		;
 			MustHaveMap = yes,
-			error("record_decisions_at_call_site: no save map")
+            unexpected(this_file, "record_decisions_at_call_site: no save map")
 		)
 	).
 
@@ -1205,7 +1195,7 @@
 	( map__is_empty(Subst) ->
 		Goal = Goal0
 	;
-		goal_util__rename_vars_in_goal(Goal0, Subst, Goal)
+        goal_util__rename_vars_in_goal(Subst, Goal0, Goal)
 	).
 
 :- pred build_headvar_subst(list(prog_var)::in, rename_map::in,
@@ -1325,5 +1315,11 @@
 	io__write_list(List, ", ", io__write_int, !IO).
 
 interval_id_to_int(interval_id(Num)) = Num.
+
+%-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "interval.m".
 
 %-----------------------------------------------------------------------------%
Index: compiler/ite_gen.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/ite_gen.m,v
retrieving revision 1.78
diff -u -b -r1.78 ite_gen.m
--- compiler/ite_gen.m	17 May 2005 04:19:22 -0000	1.78
+++ compiler/ite_gen.m	28 Aug 2005 01:02:40 -0000
@@ -1,4 +1,6 @@
 %---------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%---------------------------------------------------------------------------%
 % Copyright (C) 1994-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -28,8 +30,7 @@
 	code_info::in, code_info::out) is det.
 
 :- pred ite_gen__generate_negation(code_model::in, hlds_goal::in,
-	hlds_goal_info::in, code_tree::out, code_info::in, code_info::out)
-	is det.
+    hlds_goal_info::in, code_tree::out, code_info::in, code_info::out) is det.
 
 %---------------------------------------------------------------------------%
 
@@ -44,6 +45,7 @@
 :- import_module libs__tree.
 :- import_module ll_backend__code_gen.
 :- import_module ll_backend__trace.
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__prog_data.
 
 :- import_module bool.
@@ -74,20 +76,19 @@
 	->
 		ResumeVars = ResumeVarsPrime,
 		ResumeLocs = ResumeLocsPrime,
-			% The pre_goal_update sanity check insists on
-			% no_resume_point, to make sure that all resume
-			% points have been handled by surrounding code.
-		goal_info_set_resume_point(CondInfo0, no_resume_point,
-			CondInfo),
+        % The pre_goal_update sanity check insists on no_resume_point,
+        % to make sure that all resume points have been handled by
+        % surrounding code.
+        goal_info_set_resume_point(no_resume_point, CondInfo0, CondInfo),
 		CondGoal = CondExpr - CondInfo
 	;
-		error("condition of an if-then-else has no resume point")
+        unexpected(this_file,
+            "condition of an if-then-else has no resume point")
 	),
 
-		% Make sure that the variables whose values will be needed
-		% on backtracking to the else part are materialized into
-		% registers or stack slots. Their locations are recorded
-		% in ResumeMap.
+    % Make sure that the variables whose values will be needed on backtracking
+    % to the else part are materialized into registers or stack slots.
+    % Their locations are recorded in ResumeMap.
 	code_info__produce_vars(ResumeVars, ResumeMap, FlushCode, !CI),
 
 		% Maybe save the heap state current before the condition.
@@ -105,10 +106,10 @@
 	),
 	code_info__maybe_save_hp(ReclaimHeap, SaveHpCode, MaybeHpSlot, !CI),
 
-		% Maybe save the current trail state before the condition
+    % Maybe save the current trail state before the condition.
 	globals__lookup_bool_option(Globals, use_trail, UseTrail),
-	code_info__maybe_save_ticket(UseTrail, SaveTicketCode,
-		MaybeTicketSlot, !CI),
+    code_info__maybe_save_ticket(UseTrail, SaveTicketCode, MaybeTicketSlot,
+        !CI),
 
 	code_info__remember_position(!.CI, BranchStart),
 
@@ -117,29 +118,28 @@
 
 	code_info__make_resume_point(ResumeVars, ResumeLocs, ResumeMap,
 		ResumePoint, !CI),
-	code_info__effect_resume_point(ResumePoint, EffCodeModel,
-		EffectResumeCode, !CI),
+    code_info__effect_resume_point(ResumePoint, EffCodeModel, EffectResumeCode,
+        !CI),
 
-		% Generate the condition
+    % Generate the condition.
 	trace__maybe_generate_internal_event_code(CondGoal, IteGoalInfo,
 		CondTraceCode, !CI),
 	code_gen__generate_goal(CondCodeModel, CondGoal, CondCode, !CI),
 
 	code_info__ite_enter_then(HijackInfo, ThenNeckCode, ElseNeckCode, !CI),
 
-		% Kill again any variables that have become zombies
+    % Kill again any variables that have become zombies.
 	code_info__pickup_zombies(Zombies, !CI),
 	code_info__make_vars_forward_dead(Zombies, !CI),
 
-		% Discard hp and prune trail ticket if the condition succeeded
+    % Discard hp and prune trail ticket if the condition succeeded.
 	( CondCodeModel = model_non ->
 		% We cannot release the stack slots used for the heap pointer
 		% and the trail ticket if the condition can be backtracked
 		% into.  Nor can we prune the trail ticket that we allocated,
 		% since the condition may have allocated other trail tickets
 		% since then which have not yet been pruned.
-		code_info__maybe_reset_ticket(
-			MaybeTicketSlot, solve, ResetTicketCode)
+        code_info__maybe_reset_ticket(MaybeTicketSlot, solve, ResetTicketCode)
 	;
 		code_info__maybe_release_hp(MaybeHpSlot, !CI),
 		code_info__maybe_reset_prune_and_release_ticket(
@@ -157,7 +157,7 @@
 		code_info__generate_branch_end(EmptyStoreMap, no,
 			MaybeEnd0, ThenSaveCode, !CI)
 	;
-			% Generate the then branch
+        % Generate the then branch.
 		trace__maybe_generate_internal_event_code(ThenGoal,
 			IteGoalInfo, ThenTraceCode, !CI),
 		code_gen__generate_goal(CodeModel, ThenGoal, ThenCode, !CI),
@@ -165,17 +165,16 @@
 			MaybeEnd0, ThenSaveCode, !CI)
 	),
 
-		% Generate the entry to the else branch
+    % Generate the entry to the else branch.
 	code_info__reset_to_position(BranchStart, !CI),
 	code_info__generate_resume_point(ResumePoint, ResumeCode, !CI),
 
 		% Restore the heap pointer and solver state if necessary.
-	code_info__maybe_restore_and_release_hp(MaybeHpSlot, RestoreHpCode,
-		!CI),
-	code_info__maybe_reset_discard_and_release_ticket(
-		MaybeTicketSlot, undo, RestoreTicketCode, !CI),
+    code_info__maybe_restore_and_release_hp(MaybeHpSlot, RestoreHpCode, !CI),
+    code_info__maybe_reset_discard_and_release_ticket(MaybeTicketSlot, undo,
+        RestoreTicketCode, !CI),
 
-		% Generate the else branch
+    % Generate the else branch.
 	trace__maybe_generate_internal_event_code(ElseGoal, IteGoalInfo,
 		ElseTraceCode, !CI),
 	code_gen__generate_goal(CodeModel, ElseGoal, ElseCode, !CI),
@@ -184,40 +183,38 @@
 
 	code_info__get_next_label(EndLabel, !CI),
 	JumpToEndCode = node([
-		goto(label(EndLabel))
-			- "Jump to the end of if-then-else"
+        goto(label(EndLabel)) - "Jump to the end of if-then-else"
 	]),
 	EndLabelCode = node([
-		label(EndLabel)
-			- "end of if-then-else"
+        label(EndLabel) - "end of if-then-else"
 	]),
 	make_pneg_context_wrappers(Globals, PNegCondCode, PNegThenCode,
 		PNegElseCode),
-	Code =
-		tree(FlushCode,
-		tree(SaveHpCode,
-		tree(SaveTicketCode,
-		tree(PrepareHijackCode,
-		tree(EffectResumeCode,
-		tree(CondTraceCode,
-		tree(PNegCondCode,
-		tree(CondCode,
-		tree(ThenNeckCode,
-		tree(ResetTicketCode,
-		tree(ThenTraceCode,
-		tree(PNegThenCode,
-		tree(ThenCode,
-		tree(ThenSaveCode,
-		tree(JumpToEndCode,
-		tree(ResumeCode,
-		tree(ElseNeckCode,
-		tree(RestoreHpCode,
-		tree(RestoreTicketCode,
-		tree(ElseTraceCode,
-		tree(PNegElseCode,
-		tree(ElseCode,
-		tree(ElseSaveCode,
-		     EndLabelCode))))))))))))))))))))))),
+    Code = tree_list([
+        FlushCode,
+        SaveHpCode,
+        SaveTicketCode,
+        PrepareHijackCode,
+        EffectResumeCode,
+        CondTraceCode,
+        PNegCondCode,
+        CondCode,
+        ThenNeckCode,
+        ResetTicketCode,
+        ThenTraceCode,
+        PNegThenCode,
+        ThenCode,
+        ThenSaveCode,
+        JumpToEndCode,
+        ResumeCode,
+        ElseNeckCode,
+        RestoreHpCode,
+        RestoreTicketCode,
+        ElseTraceCode,
+        PNegElseCode,
+        ElseCode,
+        ElseSaveCode,
+        EndLabelCode]),
 	code_info__after_all_branches(StoreMap, MaybeEnd, !CI).
 
 %---------------------------------------------------------------------------%
@@ -234,16 +231,14 @@
 	( Resume = resume_point(ResumeVarsPrime, ResumeLocsPrime) ->
 		ResumeVars = ResumeVarsPrime,
 		ResumeLocs = ResumeLocsPrime,
-		goal_info_set_resume_point(GoalInfo0, no_resume_point,
-			GoalInfo),
+        goal_info_set_resume_point(no_resume_point, GoalInfo0, GoalInfo),
 		Goal = GoalExpr - GoalInfo
 	;
 		error("negated goal has no resume point")
 	),
 
-		% For a negated simple test, we can generate better code
-		% than the general mechanism, because we don't have to
-		% flush the cache.
+    % For a negated simple test, we can generate better code than the
+    % general mechanism, because we don't have to flush the cache.
 	(
 		CodeModel = model_semi,
 		GoalExpr = unify(_, _, _, simple_test(L, R), _),
@@ -251,13 +246,11 @@
 		code_info__get_globals(!.CI, Globals),
 		globals__lookup_bool_option(Globals, simple_neg, yes)
 	->
-			% Because we are generating the negated goal ourselves,
-			% we need to apply the pre- and post-goal updates
-			% that would normally be applied by
-			% code_gen__generate_goal.
+        % Because we are generating the negated goal ourselves, we need to
+        % apply the pre- and post-goal updates that would normally be applied
+        % by code_gen__generate_goal.
 
-		code_info__enter_simple_neg(ResumeVars, GoalInfo, SimpleNeg,
-			!CI),
+        code_info__enter_simple_neg(ResumeVars, GoalInfo, SimpleNeg, !CI),
 		code_info__produce_variable(L, CodeL, ValL, !CI),
 		code_info__produce_variable(R, CodeR, ValR, !CI),
 		Type = code_info__variable_type(!.CI, L),
@@ -281,7 +274,7 @@
 
 	% The code of generate_negation_general is a cut-down version
 	% of the code for if-then-elses.
-
+    %
 :- pred generate_negation_general(code_model::in, hlds_goal::in,
 	hlds_goal_info::in, set(prog_var)::in, resume_locs::in, code_tree::out,
 	code_info::in, code_info::out) is det.
@@ -291,9 +284,9 @@
 
 	code_info__produce_vars(ResumeVars, ResumeMap, FlushCode, !CI),
 
-		% Maybe save the heap state current before the condition;
-		% this ought to be after we make the failure continuation
-		% because that causes the cache to get flushed
+    % Maybe save the heap state current before the condition; this ought
+    % to be after we make the failure continuation % because that causes
+    % the cache to get flushed.
 	code_info__get_globals(!.CI, Globals),
 	(
 		globals__lookup_bool_option(Globals,
@@ -318,23 +311,22 @@
 	code_info__effect_resume_point(ResumePoint, CodeModel,
 		EffectResumeCode, !CI),
 
-		% Generate the negated goal as a semi-deterministic goal;
-		% it cannot be nondet, since mode correctness requires it
-		% to have no output vars.
+    % Generate the negated goal as a semi-deterministic goal; it cannot be
+    % nondet, since mode correctness requires it to have no output vars.
 	trace__maybe_generate_internal_event_code(Goal, NotGoalInfo,
 		EnterTraceCode, !CI),
 	code_gen__generate_goal(model_semi, Goal, GoalCode, !CI),
 
 	code_info__ite_enter_then(HijackInfo, ThenNeckCode, ElseNeckCode, !CI),
 
-		% Kill again any variables that have become zombies
+    % Kill again any variables that have become zombies.
 	code_info__pickup_zombies(Zombies, !CI),
 	code_info__make_vars_forward_dead(Zombies, !CI),
 
 	code_info__get_forward_live_vars(!.CI, LiveVars),
 
 	( CodeModel = model_det ->
-			% the then branch will never be reached
+        % The then branch will never be reached.
 		PruneTicketCode = empty,
 		FailTraceCode = empty,
 		FailCode = empty
@@ -348,63 +340,61 @@
 		trace__maybe_generate_negated_event_code(Goal, NotGoalInfo,
 			neg_failure, FailTraceCode, !CI),
 		code_info__generate_failure(FailCode, !CI),
-			% We want liveness after not(G) to be the same as
-			% after G. Information about what variables are where
-			% will be set by code_info__generate_resume_point.
+        % We want liveness after not(G) to be the same as after G.
+        % Information about what variables are where will be set
+        % by code_info__generate_resume_point.
 		code_info__reset_to_position(AfterNegatedGoal, !CI)
 	),
 
-		% Generate the entry to the else branch
+    % Generate the entry to the else branch.
 	code_info__generate_resume_point(ResumePoint, ResumeCode, !CI),
 
 	code_info__set_forward_live_vars(LiveVars, !CI),
 
 		% Restore the heap pointer and solver state if necessary.
-	code_info__maybe_restore_and_release_hp(MaybeHpSlot, RestoreHpCode,
-		!CI),
-	code_info__maybe_reset_discard_and_release_ticket(
-		MaybeTicketSlot, undo, RestoreTicketCode, !CI),
+    code_info__maybe_restore_and_release_hp(MaybeHpSlot, RestoreHpCode, !CI),
+    code_info__maybe_reset_discard_and_release_ticket( MaybeTicketSlot, undo,
+        RestoreTicketCode, !CI),
 	trace__maybe_generate_negated_event_code(Goal, NotGoalInfo,
 		neg_success, SuccessTraceCode, !CI),
 
 	make_pneg_context_wrappers(Globals, PNegCondCode, PNegThenCode,
 		PNegElseCode),
-	Code =
-		tree(FlushCode,
-		tree(PrepareHijackCode,
-		tree(EffectResumeCode,
-		tree(SaveHpCode,
-		tree(SaveTicketCode,
-		tree(EnterTraceCode,
-		tree(PNegCondCode,
-		tree(GoalCode,
-		tree(ThenNeckCode,
-		tree(PruneTicketCode,
-		tree(FailTraceCode,
-		tree(PNegThenCode,
-		tree(FailCode,
-		tree(ResumeCode,
-		tree(ElseNeckCode,
-		tree(RestoreTicketCode,
-		tree(RestoreHpCode,
-		tree(SuccessTraceCode,
-		     PNegElseCode)))))))))))))))))).
+    Code = tree_list([
+        FlushCode,
+        PrepareHijackCode,
+        EffectResumeCode,
+        SaveHpCode,
+        SaveTicketCode,
+        EnterTraceCode,
+        PNegCondCode,
+        GoalCode,
+        ThenNeckCode,
+        PruneTicketCode,
+        FailTraceCode,
+        PNegThenCode,
+        FailCode,
+        ResumeCode,
+        ElseNeckCode,
+        RestoreTicketCode,
+        RestoreHpCode,
+        SuccessTraceCode,
+        PNegElseCode]).
 
 %---------------------------------------------------------------------------%
 
-	% If the code in the condition depends on a consumer
-	% of a generator that is not complete by the time we finish
-	% executing the condition, then failure out of the condition
-	% does not necessarily mean that the condition has no solution;
-	% it may mean simply that the condition's solution depends on
-	% a generator solution that hasn't been produced yet and thus
-	% hasn't been given to the consumer yet.
+    % If the code in the condition depends on a consumer of a generator
+    % that is not complete by the time we finish executing the condition,
+    % then failure out of the condition does not necessarily mean that
+    % the condition has no solution; it may mean simply that the condition's
+    % solution depends on a generator solution that hasn't been produced yet
+    % and thus hasn't been given to the consumer yet.
+    %
+    % Detecting such situations requires knowing whether tabled subgoals
+    % (both generators and consumers) are started inside possibly negated
+    % contexts or not, which is why we wrap the condition inside
+    % MR_pneg_enter_{cond,then,exit}.
 	%
-	% Detecting such situations requires knowing whether tabled
-	% subgoals (both generators and consumers) are started inside
-	% possibly negated contexts or not, which is why we wrap the
-	% condition inside MR_pneg_enter_{cond,then,exit}.
-
 :- pred make_pneg_context_wrappers(globals::in, code_tree::out, code_tree::out,
 	code_tree::out) is det.
 
@@ -456,5 +446,11 @@
 		"\t\tMR_save_transient_registers();\n",
 		Code,
 		"\t\tMR_restore_transient_registers();\n"]).
+
+%---------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "ite_gen".
 
 %---------------------------------------------------------------------------%
Index: compiler/live_vars.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/live_vars.m,v
retrieving revision 1.110
diff -u -b -r1.110 live_vars.m
--- compiler/live_vars.m	12 Aug 2005 05:14:12 -0000	1.110
+++ compiler/live_vars.m	28 Aug 2005 00:39:58 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1994-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -97,11 +99,9 @@
 	set__difference(!.Liveness, PreDeaths, !:Liveness),
 	set__union(!.Liveness, PreBirths, !:Liveness),
 
-	%
-	% If the goal is atomic, we want to apply the postdeaths
-	% before processing the goal, but if the goal is a compound
-	% goal, then we want to apply them after processing it.
-	%
+	% If the goal is atomic, we want to apply the postdeaths before processing
+    % the goal, but if the goal is a compound goal, then we want to apply them
+    % after processing it.
 	( goal_is_atomic(Goal0) ->
 		set__difference(!.Liveness, PostDeaths, !:Liveness)
 	;
@@ -122,15 +122,13 @@
 			ResumeVars1 = ResumeVars0,
 			ResumeOnStack = no
 		),
-		NeedInResume = need_in_resume(ResumeOnStack,
-			ResumeVars1, !.NondetLiveness),
-		record_resume_site(NeedInResume, GoalInfo0, GoalInfo1,
-			!StackAlloc)
+		NeedInResume = need_in_resume(ResumeOnStack, ResumeVars1,
+            !.NondetLiveness),
+		record_resume_site(NeedInResume, GoalInfo0, GoalInfo1, !StackAlloc)
 	),
 
-	build_live_sets_in_goal_2(Goal0, Goal, GoalInfo1, GoalInfo,
-		ResumeVars1, AllocData, !StackAlloc, !Liveness,
-		!NondetLiveness),
+	build_live_sets_in_goal_2(Goal0, Goal, GoalInfo1, GoalInfo, ResumeVars1,
+        AllocData, !StackAlloc, !Liveness, !NondetLiveness),
 
 	( goal_is_atomic(Goal0) ->
 		true
@@ -149,16 +147,14 @@
 
 %-----------------------------------------------------------------------------%
 
-	% Here we process each of the different sorts of goals.
-	% `Liveness' is the set of live variables, i.e. vars which
-	% have been referenced and may be referenced again (during
-	% forward execution).
-	% `ResumeVars' is the set of variables that may or may not be
-	% `live' during the current forward execution but will become
-	% live again on backtracking.
-	% `SaveInfo' is the interference graph, i.e. the set of sets
-	% of variables which need to be on the stack at the same time.
-
+	% Here we process each of the different sorts of goals. `Liveness' is the
+    % set of live variables, i.e. vars which have been referenced and may be
+    % referenced again (during forward execution). `ResumeVars' is the set
+    % of variables that may or may not be `live' during the current forward
+    % execution but will become live again on backtracking. `SaveInfo' is the
+    % interference graph, i.e. the set of sets of variables which need to be
+    % on the stack at the same time.
+    %
 :- pred build_live_sets_in_goal_2(hlds_goal_expr::in, hlds_goal_expr::out,
 	hlds_goal_info::in, hlds_goal_info::out,
 	set(prog_var)::in, alloc_data::in, T::in, T::out,
@@ -166,8 +162,7 @@
 	set(prog_var)::in, set(prog_var)::out) is det <= stack_alloc_info(T).
 
 build_live_sets_in_goal_2(conj(Goals0), conj(Goals), GoalInfo, GoalInfo,
-		ResumeVars0, AllocData, !StackAlloc, !Liveness,
-		!NondetLiveness) :-
+		ResumeVars0, AllocData, !StackAlloc, !Liveness, !NondetLiveness) :-
 	build_live_sets_in_conj(Goals0, Goals, ResumeVars0, AllocData,
 		!StackAlloc, !Liveness, !NondetLiveness).
 
@@ -176,21 +171,19 @@
 		!StackAlloc, !Liveness, !NondetLiveness) :-
 	goal_info_get_code_gen_nonlocals(GoalInfo0, NonLocals),
 	set__union(NonLocals, !.Liveness, LiveSet),
-		% Since each parallel conjunct may be run on a different
-		% Mercury engine to the current engine, we must save all
-		% the variables that are live or nonlocal to the parallel
-		% conjunction. Nonlocal variables that are currently free, but
-		% are bound inside one of the conjuncts need a stackslot
-		% because they are passed out by reference to that stackslot.
+    % Since each parallel conjunct may be run on a different Mercury engine
+    % to the current engine, we must save all the variables that are live
+    % or nonlocal to the parallel conjunction. Nonlocal variables that are
+    % currently free, but are bound inside one of the conjuncts need a
+    % stackslot because they are passed out by reference to that stackslot.
 	NeedInParConj = need_in_par_conj(LiveSet),
 	record_par_conj(NeedInParConj, GoalInfo0, GoalInfo, !StackAlloc),
 	build_live_sets_in_par_conj(Goals0, Goals, ResumeVars0, AllocData,
 		!StackAlloc, !Liveness, !NondetLiveness).
 
 build_live_sets_in_goal_2(disj(Goals0), disj(Goals), GoalInfo, GoalInfo,
-		ResumeVars0, AllocData, !StackAlloc, !Liveness,
-		!NondetLiveness) :-
-	build_live_sets_in_disj(Goals0, Goals,GoalInfo, ResumeVars0, AllocData,
+		ResumeVars0, AllocData, !StackAlloc, !Liveness, !NondetLiveness) :-
+	build_live_sets_in_disj(Goals0, Goals, GoalInfo, ResumeVars0, AllocData,
 		!StackAlloc, !Liveness, !NondetLiveness),
 	(
 		Goals = [First | _],
@@ -198,46 +191,37 @@
 		goal_info_get_resume_point(FirstGoalInfo, ResumePoint),
 		(
 			ResumePoint = resume_point(ResumeVars, _Locs),
-				% If we can backtrack into the disjunction,
-				% we must protect the stack slots needed by
-				% any of its resumption points from being
-				% reused in the following code. The first
-				% resumption point's vars include all the
-				% vars needed by all the resumption points.
-				% However, the first disjunct can be orig_only
-				% while later disjuncts are include the stack.
-
-				% Note that we must check the disjunction's
-				% code model, not any disjuncts'; the
-				% disjunction as a whole can be model_non
+            % If we can backtrack into the disjunction, we must protect the
+            % stack slots needed by any of its resumption points from being
+            % reused in the following code. The first resumption point's vars
+            % include all the vars needed by all the resumption points.
+            % However, the first disjunct can be orig_only while later
+            % disjuncts are include the stack.
+
+            % Note that we must check the disjunction's code model, not any
+            % disjuncts'; the disjunction as a whole can be model_non
 				% without any disjunct being model_non.
 			(
 				goal_info_get_code_model(GoalInfo, model_non),
 				some [Disjunct] (
 					list__member(Disjunct, Goals),
 					Disjunct = _ - DisjunctGoalInfo,
-					goal_info_get_resume_point(
-						DisjunctGoalInfo,
+					goal_info_get_resume_point(DisjunctGoalInfo,
 						DisjunctResumePoint),
-					DisjunctResumePoint =
-						resume_point(_, Locs),
+					DisjunctResumePoint = resume_point(_, Locs),
 					resume_locs_include_stack(Locs, yes)
 				)
 			->
-				set__union(!.NondetLiveness, ResumeVars,
-					!:NondetLiveness)
+				set__union(!.NondetLiveness, ResumeVars, !:NondetLiveness)
 			;
 				true
 			)
 		;
-				% We can get here if the disjunction is
-				% not really a disjunction, because the first
-				% alternative cannot fail and will be committed
-				% to (e.g. in a first-solution context).
-				% Simplification should eliminate such
-				% disjunctions, replacing them with the first
-				% disjunct, but until that is done, we
-				% must handle them here.
+            % We can get here if the disjunction is not really a disjunction,
+            % because the first alternative cannot fail and will be committed
+            % to (e.g. in a first-solution context). Simplification should
+            % eliminate such disjunctions, replacing them with the first
+            % disjunct, but until that is done, we must handle them here.
 			ResumePoint = no_resume_point
 		)
 	;
@@ -254,20 +238,16 @@
 		if_then_else(Vars, Cond, Then, Else), GoalInfo, GoalInfo,
 		ResumeVars0, AllocData, !StackAlloc,
 		Liveness0, Liveness, NondetLiveness0, NondetLiveness) :-
-	build_live_sets_in_goal(Cond0, Cond, ResumeVars0, AllocData,
-		!StackAlloc, Liveness0, LivenessCond,
-		NondetLiveness0, NondetLivenessCond),
-	build_live_sets_in_goal(Then0, Then, ResumeVars0, AllocData,
-		!StackAlloc, LivenessCond, _LivenessThen,
-		NondetLivenessCond, NondetLivenessThen),
-	build_live_sets_in_goal(Else0, Else, ResumeVars0, AllocData,
-		!StackAlloc, Liveness0, Liveness,
-		NondetLiveness0, NondetLivenessElse),
+	build_live_sets_in_goal(Cond0, Cond, ResumeVars0, AllocData, !StackAlloc,
+        Liveness0, LivenessCond, NondetLiveness0, NondetLivenessCond),
+	build_live_sets_in_goal(Then0, Then, ResumeVars0, AllocData, !StackAlloc,
+        LivenessCond, _LivenessThen, NondetLivenessCond, NondetLivenessThen),
+	build_live_sets_in_goal(Else0, Else, ResumeVars0, AllocData, !StackAlloc,
+        Liveness0, Liveness, NondetLiveness0, NondetLivenessElse),
 	set__union(NondetLivenessThen, NondetLivenessElse, NondetLiveness).
 
 build_live_sets_in_goal_2(not(Goal0), not(Goal), GoalInfo, GoalInfo,
-		ResumeVars0, AllocData, !StackAlloc, !Liveness,
-		!NondetLiveness) :-
+		ResumeVars0, AllocData, !StackAlloc, !Liveness, !NondetLiveness) :-
 	build_live_sets_in_goal(Goal0, Goal, ResumeVars0, AllocData,
 		!StackAlloc, !Liveness, !NondetLiveness).
 
@@ -278,10 +258,10 @@
 	build_live_sets_in_goal(Goal0, Goal, ResumeVars0, AllocData,
 		!StackAlloc, !Liveness, !NondetLiveness),
 
-	% If the "some" goal cannot succeed more than once,
-	% then execution cannot backtrack into the inner goal once control
-	% has left it. Therefore the code following the "some" can reuse
-	% any stack slots needed by nondet code in the inner goal.
+	% If the "some" goal cannot succeed more than once, then execution cannot
+    % backtrack into the inner goal once control has left it. Therefore the
+    % code following the "some" can reuse any stack slots needed by nondet
+    % code in the inner goal.
 
 	goal_info_get_code_model(GoalInfo, CodeModel),
 	( CodeModel = model_non ->
@@ -302,9 +282,8 @@
 		ModuleInfo = AllocData ^ module_info,
 		arg_info__partition_generic_call_args(ModuleInfo, ArgVars,
 			Types, Modes, _InVars, OutVars, _UnusedVars),
-		build_live_sets_in_call(OutVars, GoalInfo0, GoalInfo,
-			ResumeVars0, AllocData,
-			!StackAlloc, !.Liveness, !NondetLiveness)
+		build_live_sets_in_call(OutVars, GoalInfo0, GoalInfo, ResumeVars0,
+            AllocData, !StackAlloc, !.Liveness, !NondetLiveness)
 	).
 
 build_live_sets_in_goal_2(Goal, Goal, GoalInfo0, GoalInfo, ResumeVars0,
@@ -320,13 +299,11 @@
 		GoalInfo = GoalInfo0
 	;
 		build_live_sets_in_call(OutVars, GoalInfo0, GoalInfo,
-			ResumeVars0, AllocData, !StackAlloc, !.Liveness,
-			!NondetLiveness)
+			ResumeVars0, AllocData, !StackAlloc, !.Liveness, !NondetLiveness)
 	).
 
 build_live_sets_in_goal_2(Goal, Goal, GoalInfo, GoalInfo,
-		_ResumeVars0, _AllocData,
-		!StackAlloc, !Liveness, !NondetLiveness) :-
+		_ResumeVars0, _AllocData, !StackAlloc, !Liveness, !NondetLiveness) :-
 	Goal = unify(_, _, _, Unification, _),
 	( Unification = complicated_unify(_, _, _) ->
 		error("build_live_sets_in_goal_2: complicated_unify")
@@ -346,26 +323,23 @@
 		ArgVars, _InVars, OutVars, _UnusedVars),
 	goal_info_get_code_model(GoalInfo0, CodeModel),
 	(
-		% We don't need to save any variables onto the stack
-		% before a pragma_c_code if we know that it can't
-		% succeed more than once and that it is not going
-		% to call back Mercury code, because such pragma C code
-		% won't clobber the registers.
+		% We don't need to save any variables onto the stack before a
+        % foreign_proc if we know that it can't succeed more than once
+        % and that it is not going to call back Mercury code, because
+        % such pragma C code won't clobber the registers.
 
 		CodeModel \= model_non,
 		may_call_mercury(Attributes) = will_not_call_mercury
 	->
 		GoalInfo = GoalInfo0
 	;
-		% The variables which need to be saved onto the stack
-		% before the call are all the variables that are live
-		% after the call (except for the output arguments produced
-		% by the call), plus all the variables that may be needed
-		% at an enclosing resumption point.
+		% The variables which need to be saved onto the stack before the call
+        % are all the variables that are live after the call (except for the
+        % output arguments produced by the call), plus all the variables
+        % that may be needed at an enclosing resumption point.
 
 		build_live_sets_in_call(OutVars, GoalInfo0, GoalInfo,
-			ResumeVars0, AllocData, !StackAlloc, !.Liveness,
-			!NondetLiveness)
+			ResumeVars0, AllocData, !StackAlloc, !.Liveness, !NondetLiveness)
 	).
 
 build_live_sets_in_goal_2(shorthand(_), _,_,_,_,_,_,_,_,_,_,_) :-
@@ -374,12 +348,12 @@
 
 %-----------------------------------------------------------------------------%
 
-	% The variables which need to be saved onto the stack,
-	% directly or indirectly, before a call or may_call_mercury
-	% pragma_c_code are all the variables that are live after the goal
-	% except for the output arguments produced by the goal, plus all the
-	% variables that may be needed at an enclosing resumption point.
-
+	% The variables which need to be saved onto the stack, directly or
+    % indirectly, before a call or may_call_mercury foreign_proc are all
+    % the variables that are live after the goal except for the output
+    % arguments produced by the goal, plus all the variables that may be
+    % needed at an enclosing resumption point.
+    %
 :- pred build_live_sets_in_call(set(prog_var)::in, hlds_goal_info::in,
 	hlds_goal_info::out, set(prog_var)::in, alloc_data::in, T::in, T::out,
 	set(prog_var)::in, set(prog_var)::in, set(prog_var)::out) is det
@@ -394,16 +368,14 @@
 	% calculation.
 
 	maybe_add_typeinfo_liveness(AllocData ^ proc_info,
-		AllocData ^ typeinfo_liveness, OutVars,
-		ForwardVars0, ForwardVars),
+		AllocData ^ typeinfo_liveness, OutVars, ForwardVars0, ForwardVars),
 
 	goal_info_get_determinism(GoalInfo0, Detism),
 	(
 		Detism = erroneous,
 		AllocData ^ opt_no_return_calls = yes
 	->
-		NeedAcrossCall = need_across_call(set__init, set__init,
-			set__init)
+		NeedAcrossCall = need_across_call(set__init, set__init, set__init)
 	;
 		NeedAcrossCall = need_across_call(ForwardVars, ResumeVars0,
 			!.NondetLiveness)
@@ -483,18 +455,16 @@
 		NondetLiveness0, NondetLiveness2),
 	goal_info_get_code_model(DisjGoalInfo, DisjCodeModel),
 	( DisjCodeModel = model_non ->
-			% NondetLiveness should be a set of prog_var sets.
-			% Instead of taking the union of the NondetLive sets
-			% at the ends of disjuncts, we should just keep them
-			% in this set of sets.
+        % NondetLiveness should be a set of prog_var sets. Instead of taking
+        % the union of the NondetLive sets at the ends of disjuncts, we should
+        % just keep them in this set of sets.
 		set__union(NondetLiveness1, NondetLiveness2, NondetLiveness3),
 		goal_info_get_resume_point(GoalInfo, Resume),
 		(
 			Resume = resume_point(ResumePointVars, Locs),
 			resume_locs_include_stack(Locs, yes)
 		->
-			set__union(NondetLiveness3, ResumePointVars,
-				NondetLiveness)
+			set__union(NondetLiveness3, ResumePointVars, NondetLiveness)
 		;
 			NondetLiveness = NondetLiveness3
 		)
@@ -513,54 +483,51 @@
 		!StackAlloc, !Liveness, !NondetLiveness).
 build_live_sets_in_cases([case(Cons, Goal0) | Cases0],
 		[case(Cons, Goal) | Cases], ResumeVars0, AllocData,
-		!StackAlloc, Liveness0, Liveness,
-		NondetLiveness0, NondetLiveness) :-
+		!StackAlloc, Liveness0, Liveness, NondetLiveness0, NondetLiveness) :-
 	build_live_sets_in_goal(Goal0, Goal, ResumeVars0, AllocData,
-		!StackAlloc, Liveness0, Liveness,
-		NondetLiveness0, NondetLiveness1),
+		!StackAlloc, Liveness0, Liveness, NondetLiveness0, NondetLiveness1),
 	build_live_sets_in_cases(Cases0, Cases, ResumeVars0, AllocData,
-		!StackAlloc, Liveness0, _Liveness2,
-		NondetLiveness0, NondetLiveness2),
+		!StackAlloc, Liveness0, _Liveness2, NondetLiveness0, NondetLiveness2),
 	set__union(NondetLiveness1, NondetLiveness2, NondetLiveness).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
-	% If doing typeinfo liveness calculation, any typeinfos for
-	% output variables or live variables are also live.
-	% This is because if you want to examine the live data, you need to
-	% know what shape the polymorphic args of the variables
-	% are, so you need the typeinfos to be present on the stack.
-
-	% The live variables obviously need their typeinfos
-	% live, but the output variables also need their typeinfos
-	% saved (otherwise we would throw out typeinfos and might
-	% need one at a continuation point just after a call).
-
-	% maybe_add_typeinfo_liveness takes a set of vars (output vars) and
-	% a set of live vars and if we are doing typeinfo liveness, adds the
-	% appropriate typeinfo variables to the set of variables. If not,
-	% it returns the live vars unchanged.
-
+	% If doing typeinfo liveness calculation, any typeinfos for output
+    % variables or live variables are also live. This is because if you want
+    % to examine the live data, you need to know what shape the polymorphic
+    % args of the variables are, so you need the typeinfos to be present
+    % on the stack.
+    %
+	% The live variables obviously need their typeinfos live, but the output
+    % variables also need their typeinfos saved (otherwise we would throw out
+    % typeinfos and might need one at a continuation point just after a call).
+    %
+	% maybe_add_typeinfo_liveness takes a set of vars (output vars) and a set
+    % of live vars and if we are doing typeinfo liveness, adds the appropriate
+    % typeinfo variables to the set of variables. If not, it returns the live
+    % vars unchanged.
+    %
 	% Make sure you get the output vars first, and the live vars second,
 	% since this makes a significant difference to the output set of vars.
-
+    %
 :- pred maybe_add_typeinfo_liveness(proc_info::in, bool::in,
 	set(prog_var)::in, set(prog_var)::in, set(prog_var)::out) is det.
 
 maybe_add_typeinfo_liveness(ProcInfo, TypeInfoLiveness, OutVars,
-		LiveVars1, LiveVars) :-
-	( TypeInfoLiveness = yes ->
+		!LiveVars) :-
+	(
+        TypeInfoLiveness = yes,
 		proc_info_vartypes(ProcInfo, VarTypes),
 		proc_info_rtti_varmaps(ProcInfo, RttiVarMaps),
-		proc_info_get_typeinfo_vars(LiveVars1, VarTypes, RttiVarMaps,
+		proc_info_get_typeinfo_vars(!.LiveVars, VarTypes, RttiVarMaps,
 			TypeInfoVarsLive),
 		proc_info_get_typeinfo_vars(OutVars, VarTypes, RttiVarMaps,
 			TypeInfoVarsOut),
-		set__union(LiveVars1, TypeInfoVarsOut, LiveVars2),
-		set__union(LiveVars2, TypeInfoVarsLive, LiveVars)
+		set__union(!.LiveVars, TypeInfoVarsOut, !:LiveVars),
+		set__union(!.LiveVars, TypeInfoVarsLive, !:LiveVars)
 	;
-		LiveVars = LiveVars1
+        TypeInfoLiveness = no
 	).
 
 %-----------------------------------------------------------------------------%
@@ -568,22 +535,22 @@
 :- pred record_call_site(need_across_call::in, hlds_goal_info::in,
 	hlds_goal_info::out, T::in, T::out) is det <= stack_alloc_info(T).
 
-record_call_site(NeedAcrossCall, GoalInfo0, GoalInfo, !StackAlloc) :-
-	goal_info_set_need_across_call(GoalInfo0, NeedAcrossCall, GoalInfo),
-	at_call_site(NeedAcrossCall, GoalInfo, !StackAlloc).
+record_call_site(NeedAcrossCall, !GoalInfo, !StackAlloc) :-
+	goal_info_set_need_across_call(NeedAcrossCall, !GoalInfo),
+	at_call_site(NeedAcrossCall, !.GoalInfo, !StackAlloc).
 
 :- pred record_resume_site(need_in_resume::in, hlds_goal_info::in,
 	hlds_goal_info::out, T::in, T::out) is det <= stack_alloc_info(T).
 
-record_resume_site(NeedInResume, GoalInfo0, GoalInfo, !StackAlloc) :-
-	goal_info_set_need_in_resume(GoalInfo0, NeedInResume, GoalInfo),
-	at_resume_site(NeedInResume, GoalInfo, !StackAlloc).
+record_resume_site(NeedInResume, !GoalInfo, !StackAlloc) :-
+	goal_info_set_need_in_resume(NeedInResume, !GoalInfo),
+	at_resume_site(NeedInResume, !.GoalInfo, !StackAlloc).
 
 :- pred record_par_conj(need_in_par_conj::in, hlds_goal_info::in,
 	hlds_goal_info::out, T::in, T::out) is det <= stack_alloc_info(T).
 
-record_par_conj(NeedInParConj, GoalInfo0, GoalInfo, !StackAlloc) :-
-	goal_info_set_need_in_par_conj(GoalInfo0, NeedInParConj, GoalInfo),
-	at_par_conj(NeedInParConj, GoalInfo, !StackAlloc).
+record_par_conj(NeedInParConj, !GoalInfo, !StackAlloc) :-
+	goal_info_set_need_in_par_conj(NeedInParConj, !GoalInfo),
+	at_par_conj(NeedInParConj, !.GoalInfo, !StackAlloc).
 
 %-----------------------------------------------------------------------------%
Index: compiler/livemap.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/livemap.m,v
retrieving revision 1.63
diff -u -b -r1.63 livemap.m
--- compiler/livemap.m	22 Mar 2005 06:40:03 -0000	1.63
+++ compiler/livemap.m	28 Aug 2005 01:06:21 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1995-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -30,11 +32,12 @@
 	% giving the set of live non-field lvals at each label.
 	%
 	% We can compute this set only if the procedure contains no C code.
-
+    %
 :- pred livemap__build(list(instruction)::in, maybe(livemap)::out) is det.
 
 :- implementation.
 
+:- import_module parse_tree__error_util.
 :- import_module ll_backend__opt_util.
 
 :- import_module bool.
@@ -82,7 +85,7 @@
 	% so agreement only on the set of labels in Livemap1 is useless.
 	% The domain of Livemap2 should always be every label in the procedure.
 	% as should the domain of Livemap1 in every call after the first.
-
+    %
 :- pred livemap__equal_livemaps(livemap::in, livemap::in) is semidet.
 
 livemap__equal_livemaps(Livemap1, Livemap2) :-
@@ -105,7 +108,7 @@
 
 	% Build up a map of what lvals are live at each label.
 	% The input instruction sequence is reversed.
-
+    %
 :- pred livemap__build_livemap(list(instruction)::in, lvalset::in,
 	bool::in, bool::out, livemap::in, livemap::out) is det.
 
@@ -127,10 +130,11 @@
 		Uinstr0 = comment(_)
 	;
 		Uinstr0 = livevals(_),
-		error("livevals found in backward scan in build_livemap")
+        unexpected(this_file,
+            "livevals found in backward scan in build_livemap")
 	;
 		Uinstr0 = block(_, _, _),
-		error("block found in backward scan in build_livemap")
+        unexpected(this_file, "block found in backward scan in build_livemap")
 	;
 		Uinstr0 = assign(Lval, Rval),
 
@@ -160,7 +164,7 @@
 		( Found = yes ->
 			true
 		; CodeAddr = label(Label) ->
-			livemap__insert_label_livevals([Label], !.Livemap,
+            livemap__insert_label_livevals(!.Livemap, Label,
 				set__init, !:Livevals)
 		;
 			( CodeAddr = do_redo
@@ -170,23 +174,24 @@
 		->
 			true
 		;
-			error("unknown label type in build_livemap")
+            unexpected(this_file, "unknown label type in build_livemap")
 		),
 		livemap__special_code_addr(CodeAddr, MaybeSpecial),
-		( MaybeSpecial = yes(Special) ->
+        (
+            MaybeSpecial = yes(Special),
 			set__insert(!.Livevals, Special, !:Livevals)
 		;
-			true
+            MaybeSpecial = no
 		)
 	;
 		Uinstr0 = computed_goto(Rval, Labels),
 		livemap__make_live_in_rvals([Rval], set__init, !:Livevals),
-		livemap__insert_label_livevals(Labels, !.Livemap, !Livevals)
+        list__foldl(livemap__insert_label_livevals(!.Livemap), Labels,
+            !Livevals)
 	;
 		Uinstr0 = if_val(Rval, CodeAddr),
 		Livevals0 = !.Livevals,
-		livemap__look_for_livevals(!Instrs, !Livevals, "if_val",
-			no, Found),
+        livemap__look_for_livevals(!Instrs, !Livevals, "if_val", no, Found),
 		(
 			Found = yes,
 			% This if_val was put here by middle_rec.
@@ -200,17 +205,17 @@
 			Found = no,
 			livemap__make_live_in_rvals([Rval], !Livevals),
 			( CodeAddr = label(Label) ->
-				livemap__insert_label_livevals([Label],
-					!.Livemap, !Livevals)
+                livemap__insert_label_livevals(!.Livemap, Label, !Livevals)
 			;
 				true
 			)
 		),
 		livemap__special_code_addr(CodeAddr, MaybeSpecial),
-		( MaybeSpecial = yes(Special) ->
+        (
+            MaybeSpecial = yes(Special),
 			set__insert(!.Livevals, Special, !:Livevals)
 		;
-			true
+            MaybeSpecial = no
 		)
 	;
 		Uinstr0 = incr_hp(Lval, _, _, Rval, _),
@@ -339,15 +344,14 @@
 		Instrs = Instrs2,
 		Found = yes
 	; Compulsory = yes ->
-		string__append(Site, " not preceded by livevals", Msg),
-		error(Msg)
+        unexpected(this_file, Site ++ " not preceded by livevals")
 	;
 		Instrs = Instrs1,
 		Found = no
 	).
 
 	% What lval (if any) is consulted when we branch to a code address?
-
+    %
 :- pred livemap__special_code_addr(code_addr::in, maybe(lval)::out) is det.
 
 livemap__special_code_addr(label(_), no).
@@ -373,10 +377,10 @@
 	livemap__make_live_in_rval(Rval, !Live),
 	livemap__make_live_in_rvals(Rvals, !Live).
 
-	% Set all lvals found in this rval to live, with the exception of
-	% fields, since they are treated specially (the later stages consider
-	% them to be live even if they are not explicitly in the live set).
-
+    % Set all lvals found in this rval to live, with the exception of fields,
+    % since they are treated specially (the later stages consider them
+    % to be live even if they are not explicitly in the live set).
+    %
 :- pred livemap__make_live_in_rval(rval::in, lvalset::in, lvalset::out) is det.
 
 livemap__make_live_in_rval(lval(Lval), !Live) :-
@@ -397,7 +401,7 @@
 	livemap__make_live_in_rval(Rval1, !Live),
 	livemap__make_live_in_rval(Rval2, !Live).
 livemap__make_live_in_rval(var(_), _, _) :-
-	error("var rval should not propagate to the optimizer").
+    unexpected(this_file, "var rval should not propagate to the optimizer").
 livemap__make_live_in_rval(mem_addr(MemRef), !Live) :-
 	livemap__make_live_in_mem_ref(MemRef, !Live).
 
@@ -419,18 +423,16 @@
 	set__init(Livevals1),
 	livemap__insert_proper_livevals(Livelist, Livevals1, Livevals).
 
-:- pred livemap__insert_label_livevals(list(label)::in, livemap::in,
+:- pred livemap__insert_label_livevals(livemap::in, label::in,
 	lvalset::in, lvalset::out) is det.
 
-livemap__insert_label_livevals([], _, !Livevals).
-livemap__insert_label_livevals([Label | Labels], Livemap, !Livevals) :-
+livemap__insert_label_livevals(Livemap, Label, !Livevals) :-
 	( map__search(Livemap, Label, LabelLivevals) ->
 		set__to_sorted_list(LabelLivevals, Livelist),
 		livemap__insert_proper_livevals(Livelist, !Livevals)
 	;
 		true
-	),
-	livemap__insert_label_livevals(Labels, Livemap, !Livevals).
+    ).
 
 :- pred livemap__insert_proper_livevals(list(lval)::in, lvalset::in,
 	lvalset::out) is det.
@@ -441,7 +443,7 @@
 	livemap__insert_proper_livevals(Livelist, !Livevals).
 
 	% Don't insert references to locations on the heap.
-
+    %
 :- pred livemap__insert_proper_liveval(lval::in, lvalset::in, lvalset::out)
 	is det.
 
@@ -453,4 +455,9 @@
 	).
 
 %-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "livemap.m".
+
 %-----------------------------------------------------------------------------%
Index: compiler/liveness.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/liveness.m,v
retrieving revision 1.135
diff -u -b -r1.135 liveness.m
--- compiler/liveness.m	22 Jul 2005 12:31:56 -0000	1.135
+++ compiler/liveness.m	28 Aug 2005 02:45:16 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1994-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -162,15 +164,14 @@
 :- import_module io.
 :- import_module set.
 
-	% Add liveness annotations to the goal of the procedure.
-	% This consists of the {pre,post}{birth,death} sets and
-	% resume point information.
-
+    % Add liveness annotations to the goal of the procedure. This consists of
+    % the {pre,post}{birth,death} sets and resume point information.
+    %
 :- pred detect_liveness_proc(pred_id::in, proc_id::in, module_info::in,
 	proc_info::in, proc_info::out, io::di, io::uo) is det.
 
 	% Return the set of variables live at the start of the procedure.
-
+    %
 :- pred initial_liveness(proc_info::in, pred_id::in, module_info::in,
 	set(prog_var)::out) is det.
 
@@ -180,6 +181,7 @@
 :- implementation.
 
 % Parse tree modules
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__prog_util.
 
 % HLDS modules
@@ -241,8 +243,7 @@
 		DebugLiveness, PredIdInt, Goal1, VarSet, ModuleInfo, !IO),
 
 	initial_deadness(!.ProcInfo, LiveInfo, ModuleInfo, Deadness0),
-	detect_deadness_in_goal(Goal1, Goal2, Deadness0, _,
-		Liveness0, LiveInfo),
+    detect_deadness_in_goal(Goal1, Goal2, Deadness0, _, Liveness0, LiveInfo),
 	maybe_write_progress_message("\nafter deadness",
 		DebugLiveness, PredIdInt, Goal2, VarSet, ModuleInfo, !IO),
 
@@ -255,8 +256,7 @@
 	->
 		delay_death_proc_body(Goal2, Goal3, VarSet, Liveness0),
 		maybe_write_progress_message("\nafter delay death",
-			DebugLiveness, PredIdInt, Goal3, VarSet, ModuleInfo,
-			!IO)
+            DebugLiveness, PredIdInt, Goal3, VarSet, ModuleInfo, !IO)
 	;
 		Goal3 = Goal2
 	),
@@ -283,8 +283,7 @@
 	( DebugLiveness = PredIdInt ->
 		io__write_string(Message, !IO),
 		io__write_string(":\n", !IO),
-		hlds_out__write_goal(Goal, ModuleInfo, VarSet, yes, 0, "\n",
-			!IO)
+        hlds_out__write_goal(Goal, ModuleInfo, VarSet, yes, 0, "\n", !IO)
 	;
 		true
 	).
@@ -311,8 +310,7 @@
 		set__init(Births0),
 		find_value_giving_occurrences(NewVarsList, LiveInfo,
 			InstMapDelta, Births0, Births1),
-		set__difference(CompletedNonLocals, BaseNonLocals,
-			TypeInfos),
+        set__difference(CompletedNonLocals, BaseNonLocals, TypeInfos),
 		set__difference(TypeInfos, Liveness0, NewTypeInfos),
 		set__union(Births1, NewTypeInfos, Births)
 	),
@@ -325,11 +323,9 @@
 	;
 		PreDeaths = Empty,
 		PreBirths = Empty,
-		detect_liveness_in_goal_2(Goal0, Goal,
-			Liveness0, ActualLiveness, CompletedNonLocals,
-			LiveInfo),
-		set__intersect(CompletedNonLocals, ActualLiveness,
-			NonLocalLiveness),
+        detect_liveness_in_goal_2(Goal0, Goal, Liveness0, ActualLiveness,
+            CompletedNonLocals, LiveInfo),
+        set__intersect(CompletedNonLocals, ActualLiveness, NonLocalLiveness),
 		set__union(NonLocalLiveness, Liveness0, FinalLiveness),
 		set__difference(FinalLiveness, Liveness, PostDeaths),
 		set__difference(Liveness, FinalLiveness, PostBirths)
@@ -337,13 +333,13 @@
 	set__union(Liveness0, Births, Liveness),
 		% We initialize all the fields in order to obliterate any
 		% annotations left by a previous invocation of this module.
-	goal_info_initialize_liveness_info(GoalInfo0, PreBirths, PostBirths,
-		PreDeaths, PostDeaths, no_resume_point, GoalInfo).
+    goal_info_initialize_liveness_info(PreBirths, PostBirths,
+        PreDeaths, PostDeaths, no_resume_point, GoalInfo0, GoalInfo).
 
 %-----------------------------------------------------------------------------%
 
 	% Here we process each of the different sorts of goals.
-
+    %
 :- pred detect_liveness_in_goal_2(hlds_goal_expr::in, hlds_goal_expr::out,
 	set(prog_var)::in, set(prog_var)::out, set(prog_var)::in,
 	live_info::in) is det.
@@ -376,14 +372,11 @@
 detect_liveness_in_goal_2(if_then_else(Vars, Cond0, Then0, Else0),
 		if_then_else(Vars, Cond, Then, Else),
 		Liveness0, Liveness, NonLocals, LiveInfo) :-
-	detect_liveness_in_goal(Cond0, Cond, Liveness0, LivenessCond,
-		LiveInfo),
+    detect_liveness_in_goal(Cond0, Cond, Liveness0, LivenessCond, LiveInfo),
 
-	%
 	% If the condition cannot succeed, any variables which become live
 	% in the else part should be put in the post-birth set of the then part
 	% by add_liveness_after_goal, and the other sets should be empty.
-	%
 	Cond = _ - CondInfo,
 	goal_info_get_instmap_delta(CondInfo, CondDelta),
 	( instmap_delta_is_unreachable(CondDelta) ->
@@ -394,8 +387,7 @@
 			LivenessCond, LivenessThen, LiveInfo)
 	),
 
-	detect_liveness_in_goal(Else0, Else1, Liveness0, LivenessElse,
-		LiveInfo),
+    detect_liveness_in_goal(Else0, Else1, Liveness0, LivenessElse, LiveInfo),
 
 	set__union(LivenessThen, LivenessElse, Liveness),
 	set__intersect(Liveness, NonLocals, NonLocalLiveness),
@@ -411,20 +403,20 @@
 	detect_liveness_in_goal(Goal0, Goal, !Liveness, LiveInfo).
 
 detect_liveness_in_goal_2(generic_call(_, _, _, _), _, _, _, _, _) :-
-	error("higher-order-call in detect_liveness_in_goal_2").
+    unexpected(this_file, "higher-order-call in detect_liveness_in_goal_2").
 
 detect_liveness_in_goal_2(call(_, _, _, _, _, _), _, _, _, _, _) :-
-	error("call in detect_liveness_in_goal_2").
+    unexpected(this_file, "call in detect_liveness_in_goal_2").
 
 detect_liveness_in_goal_2(unify(_, _, _, _, _), _, _, _, _, _) :-
-	error("unify in detect_liveness_in_goal_2").
+    unexpected(this_file, "unify in detect_liveness_in_goal_2").
 
 detect_liveness_in_goal_2(foreign_proc(_, _, _, _, _, _),
 		_, _, _, _, _) :-
-	error("foreign_proc in detect_liveness_in_goal_2").
+    unexpected(this_file, "foreign_proc in detect_liveness_in_goal_2").
 
 detect_liveness_in_goal_2(shorthand(_), _, _, _, _, _) :-
-	error("shorthand in detect_liveness_in_goal_2").
+    unexpected(this_file, "shorthand in detect_liveness_in_goal_2").
 
 %-----------------------------------------------------------------------------%
 
@@ -475,8 +467,7 @@
 
 detect_liveness_in_cases([], [], _Liveness, _NonLocals, _LiveInfo, !Union).
 detect_liveness_in_cases([case(Cons, Goal0) | Goals0],
-		[case(Cons, Goal) | Goals], Liveness0, NonLocals, LiveInfo,
-		!Union) :-
+        [case(Cons, Goal) | Goals], Liveness0, NonLocals, LiveInfo, !Union) :-
 	detect_liveness_in_goal(Goal0, Goal1, Liveness0, Liveness1, LiveInfo),
 	set__union(Liveness1, !Union),
 	detect_liveness_in_cases(Goals0, Goals, Liveness0, NonLocals, LiveInfo,
@@ -536,13 +527,13 @@
 			!Deadness, !.Liveness, LiveInfo)
 	),
 	set__union(PostDeaths0, NewPostDeaths, PostDeaths),
-	goal_info_set_post_deaths(GoalInfo0, PostDeaths, GoalInfo),
+    goal_info_set_post_deaths(PostDeaths, GoalInfo0, GoalInfo),
 
 	set__difference(!.Deadness, PreBirths0, !:Deadness),
 	set__union(PreDeaths0, !Deadness).
 
 	% Here we process each of the different sorts of goals.
-
+    %
 :- pred detect_deadness_in_goal_2(hlds_goal_expr::in, hlds_goal_expr::out,
 	hlds_goal_info::in, set(prog_var)::in, set(prog_var)::out,
 	set(prog_var)::in, live_info::in) is det.
@@ -628,11 +619,9 @@
 		set__intersect(Deadness, CompletedNonLocals,
 			CompletedNonLocalDeadness),
 		add_branch_pre_deaths(DeadnessCond, Deadness0,
-			CompletedNonLocalDeadness, CondThenInstmapReachable,
-			Cond1, Cond),
+            CompletedNonLocalDeadness, CondThenInstmapReachable, Cond1, Cond),
 		add_branch_pre_deaths(DeadnessElse, Deadness0,
-			CompletedNonLocalDeadness, ElseInstmapReachable,
-			Else1, Else)
+            CompletedNonLocalDeadness, ElseInstmapReachable, Else1, Else)
 	;
 		set__union(DeadnessCond, DeadnessElse, Deadness),
 		set__intersect(Deadness, CompletedNonLocals,
@@ -648,20 +637,20 @@
 	detect_deadness_in_goal(Goal0, Goal, !Deadness, Liveness0, LiveInfo).
 
 detect_deadness_in_goal_2(generic_call(_,_,_,_), _, _, _, _, _, _) :-
-	error("higher-order-call in detect_deadness_in_goal_2").
+    unexpected(this_file, "higher-order-call in detect_deadness_in_goal_2").
 
 detect_deadness_in_goal_2(call(_,_,_,_,_,_), _, _, _, _, _, _) :-
-	error("call in detect_deadness_in_goal_2").
+    unexpected(this_file, "call in detect_deadness_in_goal_2").
 
 detect_deadness_in_goal_2(unify(_,_,_,_,_), _, _, _, _, _, _) :-
-	error("unify in detect_deadness_in_goal_2").
+    unexpected(this_file, "unify in detect_deadness_in_goal_2").
 
 detect_deadness_in_goal_2(foreign_proc(_, _, _, _, _, _),
 		_, _, _, _, _, _) :-
-	error("foreign_proc in detect_deadness_in_goal_2").
+    unexpected(this_file, "foreign_proc in detect_deadness_in_goal_2").
 
 detect_deadness_in_goal_2(shorthand(_), _, _, _, _, _, _) :-
-	error("shorthand in detect_deadness_in_goal_2").
+    unexpected(this_file, "shorthand in detect_deadness_in_goal_2").
 
 %-----------------------------------------------------------------------------%
 
@@ -676,14 +665,12 @@
 	goal_info_get_instmap_delta(GoalInfo, InstmapDelta),
 	( instmap_delta_is_unreachable(InstmapDelta) ->
 		Goals = Goals0,
-		detect_deadness_in_goal(Goal0, Goal, !Deadness,
-			Liveness0, LiveInfo)
+        detect_deadness_in_goal(Goal0, Goal, !Deadness, Liveness0, LiveInfo)
 	;
 		update_liveness_goal(Goal0, LiveInfo, Liveness0, LivenessGoal),
 		detect_deadness_in_conj(Goals0, Goals, !Deadness,
 			LivenessGoal, LiveInfo),
-		detect_deadness_in_goal(Goal0, Goal, !Deadness,
-			Liveness0, LiveInfo)
+        detect_deadness_in_goal(Goal0, Goal, !Deadness, Liveness0, LiveInfo)
 	).
 
 %-----------------------------------------------------------------------------%
@@ -697,8 +684,7 @@
 		_LiveInfo, !Union, CompletedNonLocalUnion) :-
 	set__intersect(!.Union, CompletedNonLocals, CompletedNonLocalUnion).
 detect_deadness_in_disj([Goal0 | Goals0], [Goal | Goals], Deadness0, Liveness0,
-		CompletedNonLocals, LiveInfo, !Union,
-		CompletedNonLocalUnion) :-
+        CompletedNonLocals, LiveInfo, !Union, CompletedNonLocalUnion) :-
 	detect_deadness_in_goal(Goal0, Goal1, Deadness0, DeadnessGoal,
 		Liveness0, LiveInfo),
 	Goal1 = _ - GoalInfo1,
@@ -708,11 +694,9 @@
 	;
 		InstmapReachable = no
 	),
-	union_branch_deadness(DeadnessGoal, Deadness0, InstmapReachable,
-		!Union),
+    union_branch_deadness(DeadnessGoal, Deadness0, InstmapReachable, !Union),
 	detect_deadness_in_disj(Goals0, Goals, Deadness0, Liveness0,
-		CompletedNonLocals, LiveInfo, !Union,
-		CompletedNonLocalUnion),
+        CompletedNonLocals, LiveInfo, !Union, CompletedNonLocalUnion),
 	add_branch_pre_deaths(DeadnessGoal, Deadness0, CompletedNonLocalUnion,
 		InstmapReachable, Goal1, Goal).
 
@@ -723,16 +707,14 @@
 	set(prog_var)::in, set(prog_var)::out, set(prog_var)::out) is det.
 
 detect_deadness_in_cases(SwitchVar, [], [], _Deadness0, _Liveness,
-		CompletedNonLocals, _LiveInfo, !Union,
-		CompletedNonLocalUnion) :-
+        CompletedNonLocals, _LiveInfo, !Union, CompletedNonLocalUnion) :-
 		% If the switch variable does not become dead in a case,
 		% it must be put in the pre-death set of that case.
 	set__insert(!.Union, SwitchVar, !:Union),
 	set__intersect(!.Union, CompletedNonLocals, CompletedNonLocalUnion).
 detect_deadness_in_cases(SwitchVar, [case(Cons, Goal0) | Goals0],
 		[case(Cons, Goal) | Goals], Deadness0, Liveness0,
-		CompletedNonLocals, LiveInfo, !Union,
-		CompletedNonLocalUnion) :-
+        CompletedNonLocals, LiveInfo, !Union, CompletedNonLocalUnion) :-
 	detect_deadness_in_goal(Goal0, Goal1, Deadness0, DeadnessGoal,
 		Liveness0, LiveInfo),
 	Goal1 = _ - GoalInfo1,
@@ -742,8 +724,7 @@
 	;
 		InstmapReachable = no
 	),
-	union_branch_deadness(DeadnessGoal, Deadness0, InstmapReachable,
-		!Union),
+    union_branch_deadness(DeadnessGoal, Deadness0, InstmapReachable, !Union),
 	detect_deadness_in_cases(SwitchVar, Goals0, Goals, Deadness0,
 		Liveness0, CompletedNonLocals, LiveInfo, !Union,
 		CompletedNonLocalUnion),
@@ -767,7 +748,7 @@
 		Liveness0, NonLocals, LiveInfo, !Union),
 	set__intersect(!.Union, NonLocals, NonLocalUnion),
 	set__difference(NonLocalUnion, Deadness1, Residue),
-	add_deadness_before_goal(Goal1, Residue, Goal).
+    add_deadness_before_goal(Residue, Goal1, Goal).
 
 %-----------------------------------------------------------------------------%
 
@@ -804,30 +785,29 @@
 :- pred union_branch_deadness(set(prog_var)::in, set(prog_var)::in,
 	bool::in, set(prog_var)::in, set(prog_var)::out) is det.
 
-union_branch_deadness(DeadnessGoal, Deadness0, InstmapReachable,
-		Union0, Union) :-
+union_branch_deadness(DeadnessGoal, Deadness0, InstmapReachable, !Union) :-
 	(
 		InstmapReachable = yes,
-		set__union(Union0, DeadnessGoal, Union)
+        set__union(!.Union, DeadnessGoal, !:Union)
 	;
 		InstmapReachable = no,
 		set__difference(DeadnessGoal, Deadness0, FilteredDeadnessGoal),
-		set__union(Union0, FilteredDeadnessGoal, Union)
+        set__union(!.Union, FilteredDeadnessGoal, !:Union)
 	).
 
 :- pred add_branch_pre_deaths(set(prog_var)::in, set(prog_var)::in,
 	set(prog_var)::in, bool::in, hlds_goal::in, hlds_goal::out) is det.
 
 add_branch_pre_deaths(DeadnessGoal, Deadness0, CompletedNonLocalUnion,
-		InstmapReachable, Goal0, Goal) :-
+        InstmapReachable, !Goal) :-
 	set__difference(CompletedNonLocalUnion, DeadnessGoal, PreDeaths),
 	(
 		InstmapReachable = yes,
-		add_deadness_before_goal(Goal0, PreDeaths, Goal)
+        add_deadness_before_goal(PreDeaths, !Goal)
 	;
 		InstmapReachable = no,
 		set__difference(PreDeaths, Deadness0, FilteredPreDeaths),
-		add_deadness_before_goal(Goal0, FilteredPreDeaths, Goal)
+        add_deadness_before_goal(FilteredPreDeaths, !Goal)
 	).
 
 %-----------------------------------------------------------------------------%
@@ -904,7 +884,7 @@
 update_liveness_expr(scope(_, Goal), _, LiveInfo, !Liveness) :-
 	update_liveness_goal(Goal, LiveInfo, !Liveness).
 update_liveness_expr(shorthand(_), _, _, _, _) :-
-	error("update_liveness_expr: shorthand").
+    unexpected(this_file, "update_liveness_expr: shorthand").
 
 :- pred update_liveness_conj(list(hlds_goal)::in, live_info::in,
 	set(prog_var)::in, set(prog_var)::out) is det.
@@ -966,7 +946,7 @@
 	Goal1 = GoalExpr - GoalInfo1,
 	goal_info_get_post_deaths(GoalInfo1, PostDeaths1),
 	set__union(PostDeaths1, DelayedDead, PostDeaths),
-	goal_info_set_post_deaths(GoalInfo1, PostDeaths, GoalInfo),
+    goal_info_set_post_deaths(PostDeaths, GoalInfo1, GoalInfo),
 	Goal = GoalExpr - GoalInfo.
 
 :- pred delay_death_goal(hlds_goal::in, hlds_goal::out,
@@ -983,7 +963,7 @@
 	set__divide(var_is_named(VarSet), PreDeaths0,
 		PreDelayedDead, UnnamedPreDeaths),
 	set__union(PreDelayedDead, !DelayedDead),
-	goal_info_set_pre_deaths(GoalInfo0, UnnamedPreDeaths, GoalInfo1),
+    goal_info_set_pre_deaths(UnnamedPreDeaths, GoalInfo0, GoalInfo1),
 
 	delay_death_goal_expr(GoalExpr0, GoalExpr, GoalInfo1, GoalInfo2,
 		!BornVars, !DelayedDead, VarSet),
@@ -995,10 +975,9 @@
 	set__divide(var_is_named(VarSet), PostDeaths2,
 		PostDelayedDead, UnnamedPostDeaths),
 	set__union(PostDelayedDead, !DelayedDead),
-	set__divide_by_set(BornVars0, !.DelayedDead, !:DelayedDead,
-		ToBeKilled),
+    set__divide_by_set(BornVars0, !.DelayedDead, !:DelayedDead, ToBeKilled),
 	set__union(UnnamedPostDeaths, ToBeKilled, PostDeaths),
-	goal_info_set_post_deaths(GoalInfo2, PostDeaths, GoalInfo).
+    goal_info_set_post_deaths(PostDeaths, GoalInfo2, GoalInfo).
 
 :- pred var_is_named(prog_varset::in, prog_var::in) is semidet.
 
@@ -1021,8 +1000,7 @@
 		!.GoalExpr = foreign_proc(_, _, _, _, _, _)
 	;
 		!.GoalExpr = conj(Goals0),
-		delay_death_conj(Goals0, Goals, !BornVars, !DelayedDead,
-			VarSet),
+        delay_death_conj(Goals0, Goals, !BornVars, !DelayedDead, VarSet),
 		!:GoalExpr = conj(Goals)
 	;
 		!.GoalExpr = par_conj(Goals0),
@@ -1031,14 +1009,11 @@
 		!:GoalExpr = par_conj(Goals)
 	;
 		!.GoalExpr = disj(Goals0),
-		delay_death_disj(Goals0, GoalDeaths,
-			!.BornVars, !.DelayedDead, VarSet,
-			MaybeBornVarsDelayedDead),
+        delay_death_disj(Goals0, GoalDeaths, !.BornVars, !.DelayedDead,
+            VarSet, MaybeBornVarsDelayedDead),
 		(
-			MaybeBornVarsDelayedDead =
-				yes(!:BornVars - !:DelayedDead),
-			Goals = list__map(
-				kill_excess_delayed_dead_goal(!.DelayedDead),
+            MaybeBornVarsDelayedDead = yes(!:BornVars - !:DelayedDead),
+            Goals = list__map(kill_excess_delayed_dead_goal(!.DelayedDead),
 				GoalDeaths),
 			!:GoalExpr = disj(Goals)
 		;
@@ -1048,14 +1023,11 @@
 		)
 	;
 		!.GoalExpr = switch(Var, CanFail, Cases0),
-		delay_death_cases(Cases0, CaseDeaths,
-			!.BornVars, !.DelayedDead, VarSet,
-			MaybeBornVarsDelayedDead),
+        delay_death_cases(Cases0, CaseDeaths, !.BornVars, !.DelayedDead,
+            VarSet, MaybeBornVarsDelayedDead),
 		(
-			MaybeBornVarsDelayedDead =
-				yes(!:BornVars - !:DelayedDead),
-			Cases = list__map(
-				kill_excess_delayed_dead_case(!.DelayedDead),
+            MaybeBornVarsDelayedDead = yes(!:BornVars - !:DelayedDead),
+            Cases = list__map(kill_excess_delayed_dead_case(!.DelayedDead),
 				CaseDeaths),
 			!:GoalExpr = switch(Var, CanFail, Cases)
 		;
@@ -1064,8 +1036,7 @@
 		)
 	;
 		!.GoalExpr = not(Goal0),
-		delay_death_goal(Goal0, Goal, !.BornVars, _, !DelayedDead,
-			VarSet),
+        delay_death_goal(Goal0, Goal, !.BornVars, _, !DelayedDead, VarSet),
 		!:GoalExpr = not(Goal)
 	;
 		!.GoalExpr = if_then_else(QuantVars, Cond0, Then0, Else0),
@@ -1088,8 +1059,7 @@
 		!:GoalExpr = if_then_else(QuantVars, Cond, Then, Else)
 	;
 		!.GoalExpr = scope(Reason, Goal0),
-		delay_death_goal(Goal0, Goal, !.BornVars, _, !DelayedDead,
-			VarSet),
+        delay_death_goal(Goal0, Goal, !.BornVars, _, !DelayedDead, VarSet),
 		!:GoalExpr = scope(Reason, Goal)
 	;
 		!.GoalExpr = shorthand(_),
@@ -1127,15 +1097,13 @@
 
 delay_death_disj([], [], _, _, _, no).
 delay_death_disj([Goal0 | Goals0], [Goal - DelayedDeadGoal | Goals],
-		BornVars0, DelayedDead0, VarSet,
-		yes(BornVars - DelayedDead)) :-
+        BornVars0, DelayedDead0, VarSet, yes(BornVars - DelayedDead)) :-
 	delay_death_goal(Goal0, Goal, BornVars0, BornVarsGoal,
 		DelayedDead0, DelayedDeadGoal, VarSet),
 	delay_death_disj(Goals0, Goals, BornVars0, DelayedDead0, VarSet,
 		MaybeBornVarsDelayedDead),
 	(
-		MaybeBornVarsDelayedDead =
-			yes(BornVarsGoals - DelayedDeadGoals),
+        MaybeBornVarsDelayedDead = yes(BornVarsGoals - DelayedDeadGoals),
 		set__intersect(BornVarsGoal, BornVarsGoals, BornVars),
 		set__intersect(DelayedDeadGoal, DelayedDeadGoals, DelayedDead)
 	;
@@ -1151,15 +1119,13 @@
 delay_death_cases([], [], _, _, _, no).
 delay_death_cases([case(ConsId, Goal0) | Cases0],
 		[case(ConsId, Goal) - DelayedDeadGoal | Cases],
-		BornVars0, DelayedDead0, VarSet,
-		yes(BornVars - DelayedDead)) :-
+        BornVars0, DelayedDead0, VarSet, yes(BornVars - DelayedDead)) :-
 	delay_death_goal(Goal0, Goal, BornVars0, BornVarsGoal,
 		DelayedDead0, DelayedDeadGoal, VarSet),
 	delay_death_cases(Cases0, Cases, BornVars0, DelayedDead0, VarSet,
 		MaybeBornVarsDelayedDead),
 	(
-		MaybeBornVarsDelayedDead =
-			yes(BornVarsCases - DelayedDeadCases),
+        MaybeBornVarsDelayedDead = yes(BornVarsCases - DelayedDeadCases),
 		set__intersect(BornVarsGoal, BornVarsCases, BornVars),
 		set__intersect(DelayedDeadGoal, DelayedDeadCases, DelayedDead)
 	;
@@ -1180,7 +1146,7 @@
 	Goal0 = GoalExpr - GoalInfo0,
 	goal_info_get_post_deaths(GoalInfo0, PostDeath0),
 	set__union(PostDeath0, ToBeKilled, PostDeath),
-	goal_info_set_post_deaths(GoalInfo0, PostDeath, GoalInfo),
+    goal_info_set_post_deaths(PostDeath, GoalInfo0, GoalInfo),
 	Goal = GoalExpr - GoalInfo.
 
 :- func kill_excess_delayed_dead_case(set(prog_var),
@@ -1192,7 +1158,7 @@
 	Goal0 = GoalExpr - GoalInfo0,
 	goal_info_get_post_deaths(GoalInfo0, PostDeath0),
 	set__union(PostDeath0, ToBeKilled, PostDeath),
-	goal_info_set_post_deaths(GoalInfo0, PostDeath, GoalInfo),
+    goal_info_set_post_deaths(PostDeath, GoalInfo0, GoalInfo),
 	Goal = GoalExpr - GoalInfo.
 
 %-----------------------------------------------------------------------------%
@@ -1252,8 +1218,8 @@
 		if_then_else(Vars, Cond, Then, Else), Liveness0, LivenessThen,
 		GoalInfo0, LiveInfo, ResumeVars0) :-
 
-	% compute the set of variables that may be needed at the start
-	% of the else part and attach this set to the condition
+    % Compute the set of variables that may be needed at the start
+    % of the else part and attach this set to the condition.
 	Else0 = _ElseExpr0 - ElseInfo0,
 	goal_info_get_pre_deaths(ElseInfo0, ElsePreDeath0),
 	set__difference(Liveness0, ElsePreDeath0, CondResumeVars0),
@@ -1297,7 +1263,7 @@
 	% Attach the set of variables needed after the condition
 	% as the resume point set of the condition.
 	CondResume = resume_point(CondResumeVars, CondResumeLocs),
-	goal_set_resume_point(Cond1, CondResume, Cond),
+    goal_set_resume_point(CondResume, Cond1, Cond),
 
 	require_equal(LivenessThen, LivenessElse, "if-then-else", LiveInfo).
 
@@ -1331,7 +1297,7 @@
 	% Attach the set of variables alive after the negation
 	% as the resume point set of the negated goal.
 	Resume = resume_point(ResumeVars1, ResumeLocs),
-	goal_set_resume_point(Goal1, Resume, Goal).
+    goal_set_resume_point(Resume, Goal1, Goal).
 
 detect_resume_points_in_goal_2(Goal @ generic_call(_, _, _, _), Goal,
 		!Liveness, _, _, _).
@@ -1346,8 +1312,9 @@
 		!Liveness, _, _, _).
 
 detect_resume_points_in_goal_2(shorthand(_), _, _, _, _, _, _) :-
-	% these should have been expanded out by now
-	error("detect_resume_points_in_goal_2: unexpected shorthand").
+    % These should have been expanded out by now.
+    unexpected(this_file,
+        "detect_resume_points_in_goal_2: unexpected shorthand").
 
 :- pred detect_resume_points_in_conj(list(hlds_goal)::in, list(hlds_goal)::out,
 	set(prog_var)::in, set(prog_var)::out,
@@ -1361,12 +1328,11 @@
 	detect_resume_points_in_conj(Goals0, Goals, !Liveness,
 		LiveInfo, ResumeVars0).
 
-	% There are only two differences in the handling of pruned disjs
-	% versus nondet disjs. First, for nondet disjunctions we always
-	% generate code for all disjuncts, whereas for pruned disjunctions
-	% we stop generating code after the first cannot_fail disjunct.
-	% Second, an empty pruned disjunction is legal, while an empty
-	% nondet disjunction isn't.
+    % There are only two differences in the handling of pruned disjs versus
+    % nondet disjs. First, for nondet disjunctions we always generate code
+    % for all disjuncts, whereas for pruned disjunctions we stop generating
+    % code after the first cannot_fail disjunct. Second, an empty pruned
+    % disjunction is legal, while an empty nondet disjunction isn't.
 	%
 	% For both kinds of disjunctions, the resume points to be attached to
 	% the non-last disjuncts must be completed with the required typeinfos
@@ -1375,7 +1341,7 @@
 	% perform this completion when we return the set of variables needed by
 	% the last disjunct, and when we add to this set the set of variables
 	% needed by a non-last disjunct.
-
+    %
 :- pred detect_resume_points_in_non_disj(list(hlds_goal)::in,
 	list(hlds_goal)::out, set(prog_var)::in, set(prog_var)::out,
 	live_info::in, set(prog_var)::in, set(prog_var)::out) is det.
@@ -1422,8 +1388,7 @@
 		Goals0 = [_ | _]
 	->
 		detect_resume_points_in_pruned_disj(Goals0, Goals,
-			Liveness0, LivenessRest, LiveInfo,
-			ResumeVars0, NeededRest),
+            Liveness0, LivenessRest, LiveInfo, ResumeVars0, NeededRest),
 		detect_resume_points_in_non_last_disjunct(Goal0, Goal, yes,
 			Liveness0, LivenessRest, LiveInfo, ResumeVars0,
 			Liveness, NeededRest, Needed)
@@ -1441,9 +1406,8 @@
 detect_resume_points_in_non_last_disjunct(Goal0, Goal, MayUseOrigOnly,
 		Liveness0, LivenessRest, LiveInfo, ResumeVars0,
 		Liveness, NeededRest, Needed) :-
-	% we must save a variable across this disjunct if it is
-	% needed in a later disjunct or in an enclosing resume point
-
+    % We must save a variable across this disjunct if it is needed
+    % in a later disjunct or in an enclosing resume point
 	set__union(NeededRest, ResumeVars0, ResumeVars1),
 	detect_resume_points_in_goal(Goal0, Goal1, Liveness0, Liveness,
 		LiveInfo, ResumeVars1),
@@ -1467,7 +1431,7 @@
 	% Attach the set of variables needed in the following disjuncts
 	% as the resume point set of this disjunct.
 	Resume = resume_point(ResumeVars1, ResumeLocs),
-	goal_set_resume_point(Goal1, Resume, Goal),
+    goal_set_resume_point(Resume, Goal1, Goal),
 
 	Goal = _ - GoalInfo,
 	goal_info_get_pre_deaths(GoalInfo, PreDeaths),
@@ -1490,8 +1454,7 @@
 	Goal = _ - GoalInfo,
 	goal_info_get_pre_deaths(GoalInfo, PreDeaths),
 	set__difference(Liveness0, PreDeaths, Needed),
-	liveness__maybe_complete_with_typeinfos(LiveInfo, Needed,
-		CompletedNeeded).
+    liveness__maybe_complete_with_typeinfos(LiveInfo, Needed, CompletedNeeded).
 
 :- pred detect_resume_points_in_cases(list(case)::in, list(case)::out,
 	set(prog_var)::in, set(prog_var)::out,
@@ -1503,11 +1466,13 @@
 		LiveInfo, ResumeVars0) :-
 	detect_resume_points_in_goal(Goal0, Goal, Liveness0, LivenessFirst,
 		LiveInfo, ResumeVars0),
-	( Cases0 = [_ | _] ->
+    (
+        Cases0 = [_ | _],
 		detect_resume_points_in_cases(Cases0, Cases,
 			Liveness0, LivenessRest, LiveInfo, ResumeVars0),
 		require_equal(LivenessFirst, LivenessRest, "switch", LiveInfo)
 	;
+        Cases0 = [],
 		Cases = Cases0
 	).
 
@@ -1527,46 +1492,37 @@
 	live_info::in) is det.
 
 require_equal(LivenessFirst, LivenessRest, GoalType, LiveInfo) :-
-	(
-		set__equal(LivenessFirst, LivenessRest)
-	->
+    ( set__equal(LivenessFirst, LivenessRest) ->
 		true
 	;
 		VarSet = LiveInfo ^ varset,
 		set__to_sorted_list(LivenessFirst, FirstVarsList),
 		set__to_sorted_list(LivenessRest, RestVarsList),
-		list__map(varset__lookup_name(VarSet),
-			FirstVarsList, FirstVarNames),
-		list__map(varset__lookup_name(VarSet),
-			RestVarsList, RestVarNames),
-		Pad = (pred(S0::in, S::out) is det :-
-			string__append(S0, " ", S)),
+        list__map(varset__lookup_name(VarSet), FirstVarsList, FirstVarNames),
+        list__map(varset__lookup_name(VarSet), RestVarsList, RestVarNames),
+        Pad = (pred(S0::in, S::out) is det :- string__append(S0, " ", S)),
 		list__map(Pad, FirstVarNames, PaddedFirstNames),
 		list__map(Pad, RestVarNames, PaddedRestNames),
 		string__append_list(PaddedFirstNames, FirstNames),
 		string__append_list(PaddedRestNames, RestNames),
-		string__append_list(["branches of ", GoalType,
-			" disagree on liveness\nFirst: ",
-			FirstNames, "\nRest:  ", RestNames], Msg),
+        Msg = "branches of " ++ GoalType ++ " disagree on liveness\n" ++
+            "First: " ++ FirstNames ++ "\n" ++ "Rest:  " ++ RestNames ++ "\n",
 		error(Msg)
 	).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
-initial_liveness(ProcInfo, PredId, ModuleInfo, Liveness) :-
+initial_liveness(ProcInfo, PredId, ModuleInfo, !:Liveness) :-
 	proc_info_headvars(ProcInfo, Vars),
 	proc_info_argmodes(ProcInfo, Modes),
 	proc_info_vartypes(ProcInfo, VarTypes),
 	map__apply_to_list(Vars, VarTypes, Types),
-	set__init(Liveness0),
-	(
-		initial_liveness_2(Vars, Modes, Types, ModuleInfo,
-			Liveness0, Liveness1)
-	->
-		Liveness2 = Liveness1
+    set__init(!:Liveness),
+    ( initial_liveness_2(Vars, Modes, Types, ModuleInfo, !Liveness) ->
+        true
 	;
-		error("initial_liveness: list length mismatch")
+        unexpected(this_file, "initial_liveness: list length mismatch")
 	),
 
 		% If a variable is unused in the goal, it shouldn't be
@@ -1584,16 +1540,14 @@
 	body_should_use_typeinfo_liveness(PredInfo, Globals, TypeinfoLiveness),
 	proc_info_maybe_complete_with_typeinfo_vars(NonLocals0,
 		TypeinfoLiveness, VarTypes, RttiVarMaps, NonLocals),
-	set__intersect(Liveness2, NonLocals, Liveness).
+    set__intersect(!.Liveness, NonLocals, !:Liveness).
 
 :- pred initial_liveness_2(list(prog_var)::in, list(mode)::in, list(type)::in,
 	module_info::in, set(prog_var)::in, set(prog_var)::out) is semidet.
 
 initial_liveness_2([], [], [], _ModuleInfo, !Liveness).
 initial_liveness_2([V | Vs], [M | Ms], [T | Ts], ModuleInfo, !Liveness) :-
-	(
-		mode_to_arg_mode(ModuleInfo, M, T, top_in)
-	->
+    ( mode_to_arg_mode(ModuleInfo, M, T, top_in) ->
 		set__insert(!.Liveness, V, !:Liveness)
 	;
 		true
@@ -1604,7 +1558,7 @@
 
 	% Return the set of variables whose values are needed beyond the end
 	% of the procedure (i.e. its output arguments).
-
+    %
 :- pred initial_deadness(proc_info::in, live_info::in, module_info::in,
 	set(prog_var)::out) is det.
 
@@ -1612,8 +1566,8 @@
 		% The output arguments are all in the initial deadness.
 	arg_info__partition_proc_args(ProcInfo, ModuleInfo, _, Deadness0, _),
 
-		% If doing typeinfo liveness, the corresponding
-		% typeinfos need to be added to these.
+    % If doing typeinfo liveness, the corresponding typeinfos need to be added
+    % to these.
 	proc_info_vartypes(ProcInfo, VarTypes),
 	proc_info_rtti_varmaps(ProcInfo, RttiVarMaps),
 	proc_info_maybe_complete_with_typeinfo_vars(Deadness0,
@@ -1628,23 +1582,23 @@
 add_liveness_after_goal(Goal - GoalInfo0, Residue, Goal - GoalInfo) :-
 	goal_info_get_post_births(GoalInfo0, PostBirths0),
 	set__union(PostBirths0, Residue, PostBirths),
-	goal_info_set_post_births(GoalInfo0, PostBirths, GoalInfo).
+    goal_info_set_post_births(PostBirths, GoalInfo0, GoalInfo).
 
-:- pred add_deadness_before_goal(hlds_goal::in, set(prog_var)::in,
-	hlds_goal::out) is det.
+:- pred add_deadness_before_goal(set(prog_var)::in,
+    hlds_goal::in, hlds_goal::out) is det.
 
-add_deadness_before_goal(Goal - GoalInfo0, Residue, Goal - GoalInfo) :-
+add_deadness_before_goal(Residue, Goal - GoalInfo0, Goal - GoalInfo) :-
 	goal_info_get_pre_deaths(GoalInfo0, PreDeaths0),
 	set__union(PreDeaths0, Residue, PreDeaths),
-	goal_info_set_pre_deaths(GoalInfo0, PreDeaths, GoalInfo).
+    goal_info_set_pre_deaths(PreDeaths, GoalInfo0, GoalInfo).
 
-:- pred add_deadness_after_goal(hlds_goal::in, set(prog_var)::in,
-	hlds_goal::out) is det.
+:- pred add_deadness_after_goal(set(prog_var)::in,
+    hlds_goal::in, hlds_goal::out) is det.
 
-add_deadness_after_goal(Goal - GoalInfo0, Residue, Goal - GoalInfo) :-
+add_deadness_after_goal(Residue, Goal - GoalInfo0, Goal - GoalInfo) :-
 	goal_info_get_post_deaths(GoalInfo0, PostDeaths0),
 	set__union(PostDeaths0, Residue, PostDeaths),
-	goal_info_set_post_deaths(GoalInfo0, PostDeaths, GoalInfo).
+    goal_info_set_post_deaths(PostDeaths, GoalInfo0, GoalInfo).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
@@ -1656,7 +1610,7 @@
 	% of value-given vars.
 	%
 	% We don't handle the aliasing part yet.
-
+    %
 :- pred find_value_giving_occurrences(list(prog_var)::in, live_info::in,
 	instmap_delta::in, set(prog_var)::in, set(prog_var)::out) is det.
 
@@ -1716,5 +1670,11 @@
 
 live_info_init(ModuleInfo, TypeInfoLiveness, VarTypes, RttiVarMaps, VarSet,
 	live_info(ModuleInfo, TypeInfoLiveness, VarTypes, RttiVarMaps, VarSet)).
+
+%-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "liveness.m".
 
 %-----------------------------------------------------------------------------%
Index: compiler/magic.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/magic.m,v
retrieving revision 1.54
diff -u -b -r1.54 magic.m
--- compiler/magic.m	27 Aug 2005 09:41:56 -0000	1.54
+++ compiler/magic.m	27 Aug 2005 16:18:03 -0000
@@ -814,7 +814,7 @@
 	{ instmap_delta_from_mode_list(HeadVars, ArgModes,
 		ModuleInfo0, InstMapDelta) },
 	{ proc_info_goal(ProcInfo1, Goal0 - GoalInfo0) },
-	{ goal_info_set_instmap_delta(GoalInfo0, InstMapDelta, GoalInfo) },
+	{ goal_info_set_instmap_delta(InstMapDelta, GoalInfo0, GoalInfo) },
 	{ proc_info_set_goal(Goal0 - GoalInfo, ProcInfo1, ProcInfo2) },
 
 	% All Aditi procedures are considered nondet. The C interface
@@ -1432,8 +1432,8 @@
 			[], IntroducedArgs, [], ExtraGoals),
 		{ goal_info_get_nonlocals(GoalInfo, NonLocals) },
 		{ set__insert_list(NonLocals, IntroducedArgs, NewNonLocals) },
-		{ goal_info_set_nonlocals(GoalInfo,
-			NewNonLocals, NewGoalInfo) },
+		{ goal_info_set_nonlocals(NewNonLocals,
+			GoalInfo, NewGoalInfo) },
 		{ NewCall = call(PredId, B, NewArgs, C, D, E) - NewGoalInfo },
 		{ list__append(ExtraGoals, [NewCall], Goals) }
 	;
@@ -1648,9 +1648,9 @@
 		magic_info_set_proc_info(ProcInfo),
 		{ map__init(Subn0) },
 		{ map__det_insert(Subn0, Arg, NewArg, Subn) },
-		{ goal_util__rename_vars_in_goal(ClosureGoal0,
-			Subn, ClosureGoal) },
-		{ goal_util__rename_vars_in_goal(Goal1, Subn, Goal) },
+		{ goal_util__rename_vars_in_goal(Subn,
+			ClosureGoal0,ClosureGoal) },
+		{ goal_util__rename_vars_in_goal(Subn, Goal1, Goal) },
 		{ ExtraGoals = [ClosureGoal | ExtraGoals1] }
 	;
 		{ ExtraGoals = ExtraGoals1 },
Index: compiler/magic_util.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/magic_util.m,v
retrieving revision 1.49
diff -u -b -r1.49 magic_util.m
--- compiler/magic_util.m	27 Aug 2005 09:41:56 -0000	1.49
+++ compiler/magic_util.m	27 Aug 2005 16:51:53 -0000
@@ -152,18 +152,22 @@
 magic_util__db_call_nonlocals(
 		db_call(MaybeClosures, Call, _, _, _, _, MaybeNegGoals),
 		NonLocals) :-
-	( MaybeClosures = yes(Closures) ->
+	(
+		MaybeClosures = yes(Closures),
 		goal_list_nonlocals(Closures, NonLocals0)
 	;
+		MaybeClosures = no,
 		set__init(NonLocals0)
 	),
 	Call = _ - CallInfo,
 	goal_info_get_nonlocals(CallInfo, NonLocals1),
 	set__union(NonLocals0, NonLocals1, NonLocals2),
-	( MaybeNegGoals = yes(_ - NegGoalInfo) ->
+	(
+		MaybeNegGoals = yes(_ - NegGoalInfo),
 		goal_info_get_nonlocals(NegGoalInfo, NonLocals3),
 		set__union(NonLocals2, NonLocals3, NonLocals)
 	;
+		MaybeNegGoals = no,
 		NonLocals = NonLocals2
 	).
 
@@ -179,21 +183,21 @@
 		Inputs0, Outputs0, MaybeNegGoals0),
 	(
 		MaybeClosures0 = yes(Closures0),
-		goal_util__rename_vars_in_goals(Closures0, no, Subn, Closures),
+		goal_util__rename_vars_in_goals(no, Subn, Closures0, Closures),
 		MaybeClosures = yes(Closures)
 	;
 		MaybeClosures0 = no,
 		MaybeClosures = no
 	),
-	goal_util__rename_vars_in_goal(Goal0, Subn, Goal),
-	goal_util__rename_var_list(Args0, no, Subn, Args),
-	goal_util__rename_var_list(Inputs0, no, Subn, Inputs),
-	goal_util__rename_var_list(Outputs0, no, Subn, Outputs),
+	goal_util__rename_vars_in_goal(Subn, Goal0, Goal),
+	goal_util__rename_var_list(no, Subn, Args0, Args),
+	goal_util__rename_var_list(no, Subn, Inputs0, Inputs),
+	goal_util__rename_var_list(no, Subn, Outputs0, Outputs),
 	(
 		MaybeNegGoals0 = yes(NegGoals0 - NegGoalInfo0),
-		goal_util__rename_vars_in_goals(NegGoals0, no, Subn, NegGoals),
-		goal_util__rename_vars_in_goal(conj([]) - NegGoalInfo0,
-			Subn, _ - NegGoalInfo),
+		goal_util__rename_vars_in_goals(no, Subn, NegGoals0, NegGoals),
+		goal_util__rename_vars_in_goal(Subn,
+			conj([]) - NegGoalInfo0, _ - NegGoalInfo),
 		MaybeNegGoals = yes(NegGoals - NegGoalInfo)
 	;
 		MaybeNegGoals0 = no,
@@ -414,8 +418,8 @@
 				CallNonLocals1) },
 			magic_util__restrict_nonlocals(CallNonLocals1,
 				CallNonLocals),
-			{ goal_info_set_nonlocals(CallGoalInfo1, CallNonLocals,
-				CallGoalInfo) },
+			{ goal_info_set_nonlocals(CallNonLocals,
+				CallGoalInfo1, CallGoalInfo) },
 			{ CallGoal = call(PredId, ProcId, NewArgs,
 				not_builtin, no, Name) - CallGoalInfo }
 		;
@@ -440,8 +444,8 @@
 		magic_util__restrict_nonlocals(InnerNonLocals1,
 			InnerNonLocals),
 		{ goal_list_instmap_delta(NegGoals, InnerDelta0) },
-		{ instmap_delta_restrict(InnerDelta0,
-			InnerNonLocals, InnerDelta) },
+		{ instmap_delta_restrict(InnerNonLocals,
+			InnerDelta0, InnerDelta) },
 		{ goal_list_determinism(NegGoals, InnerDet) },
 		{ goal_info_init(InnerNonLocals, InnerDelta,
 			InnerDet, pure, InnerInfo) },
@@ -562,8 +566,7 @@
 	magic_info_set_proc_info(ProcInfo),
 
 	% All database predicates are considered nondet after this.
-	{ goal_info_set_determinism(GoalInfo1,
-		nondet, GoalInfo) },
+	{ goal_info_set_determinism(nondet, GoalInfo1, GoalInfo) },
 
 	magic_info_get_scc(SCC),
 	( { list__member(PredProcId0, SCC) } ->
@@ -685,9 +688,9 @@
 	set__delete(CallNonLocals0, Var, CallNonLocals1),
 	set__insert(CallNonLocals1, OutputVar, CallNonLocals),
 	goal_info_get_instmap_delta(CallInfo0, CallDelta0),
-	instmap_delta_insert(CallDelta0, OutputVar, FinalInst, CallDelta),
-	goal_info_set_nonlocals(CallInfo0, CallNonLocals, CallInfo1),
-	goal_info_set_instmap_delta(CallInfo1, CallDelta, CallInfo).
+	instmap_delta_insert(OutputVar, FinalInst, CallDelta0, CallDelta),
+	goal_info_set_nonlocals(CallNonLocals, CallInfo0, CallInfo1),
+	goal_info_set_instmap_delta(CallDelta, CallInfo1, CallInfo).
 
 %-----------------------------------------------------------------------------%
 
@@ -867,8 +870,8 @@
 		% Construct a goal_info.
 		{ set__list_to_set([InputVar | LambdaInputs], NonLocals) },
 		{ instmap_delta_init_reachable(InstMapDelta0) },
-		{ instmap_delta_insert(InstMapDelta0, InputVar, LambdaInst,
-			InstMapDelta) },
+		{ instmap_delta_insert(InputVar, LambdaInst,
+			InstMapDelta0, InstMapDelta) },
 		{ goal_info_init(NonLocals, InstMapDelta,
 			det, pure, GoalInfo) },
 
@@ -912,12 +915,12 @@
 		NewArgs, !ProcInfo) },
 	{ map__from_corresponding_lists(SuppOutputArgs, NewArgs, Subn) },
 	{ map__apply_to_list(UnrenamedInputVars, Subn, LambdaVars) },
-	{ goal_util__rename_vars_in_goal(SuppCall, Subn, LambdaGoal0) },
+	{ goal_util__rename_vars_in_goal(Subn, SuppCall, LambdaGoal0) },
 	{ LambdaGoal0 = LambdaExpr - LambdaInfo0 },
 
 	{ list__append(SuppInputArgs, LambdaVars, LambdaNonLocals0) },
 	{ set__list_to_set(LambdaNonLocals0, LambdaNonLocals) },
-	{ goal_info_set_nonlocals(LambdaInfo0, LambdaNonLocals, LambdaInfo) },
+	{ goal_info_set_nonlocals(LambdaNonLocals, LambdaInfo0, LambdaInfo) },
 	{ LambdaGoal = LambdaExpr - LambdaInfo }.
 
 %-----------------------------------------------------------------------------%
@@ -952,9 +955,9 @@
 		Subn0, Subn) },
 	{ Rule = RuleExpr - RuleInfo0 },
 	{ set__list_to_set(RuleArgs, RuleArgSet) },
-	{ goal_info_set_nonlocals(RuleInfo0, RuleArgSet, RuleInfo) },
-	{ goal_util__must_rename_vars_in_goal(RuleExpr - RuleInfo,
-		Subn, ExtraDisjunct) },
+	{ goal_info_set_nonlocals(RuleArgSet, RuleInfo0, RuleInfo) },
+	{ goal_util__must_rename_vars_in_goal(Subn, RuleExpr - RuleInfo,
+		ExtraDisjunct) },
 
 	%
 	% Add in the new disjunct.
@@ -1070,7 +1073,7 @@
 	%
 	{ goal_list_instmap_delta(Goals, Delta0) },
 	{ set__list_to_set(SuppArgs, SuppArgSet) },
-	{ instmap_delta_restrict(Delta0, SuppArgSet, Delta) },
+	{ instmap_delta_restrict(SuppArgSet, Delta0, Delta) },
 	{ goal_info_init(SuppArgSet, Delta, nondet, pure, GoalInfo) },
 
 	%
Index: compiler/make_tags.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/make_tags.m,v
retrieving revision 1.46
diff -u -b -r1.46 make_tags.m
--- compiler/make_tags.m	26 Jul 2005 01:56:24 -0000	1.46
+++ compiler/make_tags.m	28 Aug 2005 05:26:12 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1994-1996, 1998-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -65,13 +67,13 @@
 :- import_module bool.
 :- import_module list.
 
-% assign_constructor_tags(Constructors, TypeCtor, ReservedTagPragma, Globals,
-%		TagValues, IsEnum):
-%	Assign a constructor tag to each constructor for a discriminated
-%	union type, and determine whether the type is an enumeration
-%	type or not.  (`Globals' is passed because exact way in which
-%	this is done is dependent on a compilation option.)
-
+    % assign_constructor_tags(Constructors, TypeCtor, ReservedTagPragma,
+    %   Globals, TagValues, IsEnum):
+    % Assign a constructor tag to each constructor for a discriminated union
+    % type, and determine whether the type is an enumeration type or not.
+    % (`Globals' is passed because exact way in which this is done is
+    % dependent on a compilation option.)
+    %
 :- pred assign_constructor_tags(list(constructor)::in, type_ctor::in, bool::in,
 	globals::in, cons_tag_values::out, bool::out) is det.
 
@@ -90,14 +92,14 @@
 :- import_module map.
 :- import_module require.
 :- import_module std_util.
+:- import_module svmap.
 
 %-----------------------------------------------------------------------------%
 
 assign_constructor_tags(Ctors, TypeCtor, ReservedTagPragma, Globals,
 		CtorTags, IsEnum) :-
 
-		% Work out how many tag bits and reserved addresses
-		% we've got to play with.
+    % Work out how many tag bits and reserved addresses we've got to play with.
 	globals__lookup_int_option(Globals, num_tag_bits, NumTagBits),
 	globals__lookup_int_option(Globals, num_reserved_addresses,
 		NumReservedAddresses),
@@ -105,24 +107,24 @@
 		NumReservedObjects),
 	globals__lookup_bool_option(Globals, highlevel_code, HighLevelCode),
 
-		% Determine if we need to reserve a tag for use by HAL's
-		% Herbrand constraint solver.
-		% (This also disables enumerations and no_tag types.)
+    % Determine if we need to reserve a tag for use by HAL's Herbrand
+    % constraint solver. (This also disables enumerations and no_tag types.)
 	globals__lookup_bool_option(Globals, reserve_tag, GlobalReserveTag),
 	ReserveTag = GlobalReserveTag `or` ReservedTagPragma,
 
-	( ReserveTag = yes ->
+    (
+        ReserveTag = yes,
 		InitTag = 1
 	;
+        ReserveTag = no,
 		InitTag = 0
 	),
 
-		% now assign them
+    % Now assign them.
 	map__init(CtorTags0),
 	(
-			% Try representing the type as an enumeration:
-			% all the constructors must be constant, and we
-			% must be allowed to make unboxed enums.
+        % Try representing the type as an enumeration: all the constructors
+        % must be constant, and we must be allowed to make unboxed enums.
 		globals__lookup_bool_option(Globals, unboxed_enums, yes),
 		ctors_are_all_constants(Ctors),
 		ReserveTag = no
@@ -132,13 +134,12 @@
 	;
 		IsEnum = no,
 		(
-				% Try representing it as a no-tag type
-			type_constructors_should_be_no_tag(Ctors,
-				ReserveTag, Globals,
+            % Try representing it as a no-tag type.
+            type_constructors_should_be_no_tag(Ctors, ReserveTag, Globals,
 				SingleFunc, SingleArg, _)
 		->
-			SingleConsId = make_cons_id_from_qualified_sym_name(
-				SingleFunc, [SingleArg]),
+            SingleConsId = make_cons_id_from_qualified_sym_name(SingleFunc,
+                [SingleArg]),
 			map__set(CtorTags0, SingleConsId, no_tag, CtorTags)
 		;
 			NumTagBits = 0
@@ -146,25 +147,20 @@
 			(
 				ReserveTag = yes,
 				% XXX Need to fix this.
-				% This occurs for the .NET and Java backends
-				sorry("make_tags",
-					"--reserve-tag with num_tag_bits = 0")
+                % This occurs for the .NET and Java backends.
+                sorry("make_tags", "--reserve-tag with num_tag_bits = 0")
 			;
 				ReserveTag = no
 			),
-			% assign reserved addresses to the constants,
-			% if possible
+            % Assign reserved addresses to the constants, if possible.
 			separate_out_constants(Ctors, Constants, Functors),
-			assign_reserved_numeric_addresses(Constants,
-				LeftOverConstants0, CtorTags0, CtorTags1,
-				0, NumReservedAddresses),
+            assign_reserved_numeric_addresses(Constants, LeftOverConstants0,
+                CtorTags0, CtorTags1, 0, NumReservedAddresses),
 			(
 				HighLevelCode = yes,
 				assign_reserved_symbolic_addresses(
-					LeftOverConstants0,
-					LeftOverConstants, TypeCtor,
-					CtorTags1, CtorTags2,
-					0, NumReservedObjects)
+                    LeftOverConstants0, LeftOverConstants, TypeCtor,
+                    CtorTags1, CtorTags2, 0, NumReservedObjects)
 			;
 				HighLevelCode = no,
 				% reserved symbolic addresses are not
@@ -172,19 +168,19 @@
 				LeftOverConstants = LeftOverConstants0,
 				CtorTags2 = CtorTags1
 			),
-			% assign shared_with_reserved_address(...)
-			% representations for the remaining constructors
+            % Assign shared_with_reserved_address(...) representations
+            % for the remaining constructors.
 			RemainingCtors = LeftOverConstants ++ Functors,
 			ReservedAddresses = list__filter_map(
 				(func(reserved_address(RA)) = RA is semidet),
 				map__values(CtorTags2)),
-			assign_unshared_tags(RemainingCtors, 0, 0,
-				ReservedAddresses, CtorTags2, CtorTags)
+            assign_unshared_tags(RemainingCtors, 0, 0, ReservedAddresses,
+                CtorTags2, CtorTags)
 		;
 			MaxTag = max_num_tags(NumTagBits) - 1,
 			separate_out_constants(Ctors, Constants, Functors),
-			assign_constant_tags(Constants, CtorTags0,
-				CtorTags1, InitTag, NextTag),
+            assign_constant_tags(Constants, CtorTags0, CtorTags1,
+                InitTag, NextTag),
 			assign_unshared_tags(Functors, NextTag, MaxTag, [],
 				CtorTags1, CtorTags)
 		)
@@ -198,12 +194,13 @@
 	Ctor = ctor(_ExistQVars, _Constraints, Name, Args),
 	ConsId = make_cons_id_from_qualified_sym_name(Name, Args),
 	Tag = int_constant(Val),
-	map__set(!.CtorTags, ConsId, Tag, !:CtorTags),
+    svmap__set(ConsId, Tag, !CtorTags),
 	assign_enum_constants(Rest, Val + 1, !CtorTags).
 
-	% assign the representations null_pointer, small_pointer(1),
+    % Assign the representations null_pointer, small_pointer(1),
 	% small_pointer(2), ..., small_pointer(N) to the constructors,
 	% until N >= NumReservedAddresses.
+    %
 :- pred assign_reserved_numeric_addresses(
 	list(constructor)::in, list(constructor)::out,
 	cons_tag_values::in, cons_tag_values::out, int::in, int::in) is det.
@@ -221,13 +218,14 @@
 		;
 			Tag = reserved_address(small_pointer(Address))
 		),
-		map__set(!.CtorTags, ConsId, Tag, !:CtorTags),
+        svmap__set(ConsId, Tag, !CtorTags),
 		assign_reserved_numeric_addresses(Rest, LeftOverConstants,
 			!CtorTags, Address + 1, NumReservedAddresses)
 	).
 
-	% assign reserved_object(CtorName, CtorArity) representations
-	% to the specified constructors
+    % Assign reserved_object(CtorName, CtorArity) representations
+    % to the specified constructors.
+    %
 :- pred assign_reserved_symbolic_addresses(
 	list(constructor)::in, list(constructor)::out, type_ctor::in,
 	cons_tag_values::in, cons_tag_values::out, int::in, int::in) is det.
@@ -242,7 +240,7 @@
 		Arity = list__length(Args),
 		Tag = reserved_address(reserved_object(TypeCtor, Name, Arity)),
 		ConsId = make_cons_id_from_qualified_sym_name(Name, Args),
-		map__set(!.CtorTags, ConsId, Tag, !:CtorTags),
+        svmap__set(ConsId, Tag, !CtorTags),
 		assign_reserved_symbolic_addresses(Ctors, LeftOverConstants,
 			TypeCtor, !CtorTags, Num + 1, Max)
 	).
@@ -250,16 +248,15 @@
 :- pred assign_constant_tags(list(constructor)::in, cons_tag_values::in,
 	cons_tag_values::out, int::in, int::out) is det.
 
-	% If there's no constants, don't do anything.  Otherwise,
-	% allocate the first tag for the constants, and give
-	% them all shared local tags with that tag as the
-	% primary tag, and different secondary tags starting from
-	% zero.
+    % If there's no constants, don't do anything. Otherwise, allocate the
+    % first tag for the constants, and give them all shared local tags
+    % with that tag as the primary tag, and different secondary tags
+    % starting from zero.
+    %
 	% Note that if there's a single constant, we still give it a
-	% shared_local_tag rather than a unshared_tag.  That's
-	% because deconstruction of the shared_local_tag
-	% is more efficient.
-
+    % shared_local_tag rather than a unshared_tag. That's because
+    % deconstruction of the shared_local_tag is more efficient.
+    %
 assign_constant_tags(Constants, !CtorTags, InitTag, NextTag) :-
 	(
 		Constants = [],
@@ -267,8 +264,7 @@
 	;
 		Constants = [_ | _],
 		NextTag = InitTag + 1,
-		assign_shared_local_tags(Constants,
-			InitTag, 0, !CtorTags)
+        assign_shared_local_tags(Constants, InitTag, 0, !CtorTags)
 	).
 
 :- pred assign_unshared_tags(list(constructor)::in, int::in, int::in,
@@ -283,21 +279,26 @@
 	% If there's only one functor,
 	% give it the "single_functor" (untagged)
 	% representation, rather than giving it unshared_tag(0).
-	( Val = 0, Rest = [] ->
-		Tag = maybe_add_reserved_addresses(ReservedAddresses,
-			single_functor),
-		map__set(!.CtorTags, ConsId, Tag, !:CtorTags)
-	% if we're about to run out of unshared tags, start assigning
-	% shared remote tags instead
-	; Val = MaxTag, Rest = [_ | _] ->
-		assign_shared_remote_tags([Ctor | Rest], MaxTag, 0,
-			ReservedAddresses, !CtorTags)
+    (
+        Val = 0,
+        Rest = []
+    ->
+        Tag = maybe_add_reserved_addresses(ReservedAddresses, single_functor),
+        svmap__set(ConsId, Tag, !CtorTags)
+    ;
+        % If we're about to run out of unshared tags, start assigning
+        % shared remote tags instead.
+        Val = MaxTag,
+        Rest = [_ | _]
+    ->
+        assign_shared_remote_tags([Ctor | Rest], MaxTag, 0, ReservedAddresses,
+            !CtorTags)
 	;
 		Tag = maybe_add_reserved_addresses(ReservedAddresses,
 			unshared_tag(Val)),
-		map__set(!.CtorTags, ConsId, Tag, !:CtorTags),
-		assign_unshared_tags(Rest, Val + 1, MaxTag,
-			ReservedAddresses, !CtorTags)
+        svmap__set(ConsId, Tag, !CtorTags),
+        assign_unshared_tags(Rest, Val + 1, MaxTag, ReservedAddresses,
+            !CtorTags)
 	).
 
 :- pred assign_shared_remote_tags(list(constructor)::in, int::in, int::in,
@@ -311,7 +312,7 @@
 	ConsId = make_cons_id_from_qualified_sym_name(Name, Args),
 	Tag = maybe_add_reserved_addresses(ReservedAddresses,
 		shared_remote_tag(PrimaryVal, SecondaryVal)),
-	map__set(!.CtorTags, ConsId, Tag, !:CtorTags),
+    svmap__set(ConsId, Tag, !CtorTags),
 	SecondaryVal1 = SecondaryVal + 1,
 	assign_shared_remote_tags(Rest, PrimaryVal, SecondaryVal1,
 		ReservedAddresses, !CtorTags).
@@ -324,7 +325,7 @@
 	Ctor = ctor(_ExistQVars, _Constraints, Name, Args),
 	ConsId = make_cons_id_from_qualified_sym_name(Name, Args),
 	Tag = shared_local_tag(PrimaryVal, SecondaryVal),
-	map__set(!.CtorTags, ConsId, Tag, !:CtorTags),
+    svmap__set(ConsId, Tag, !CtorTags),
 	SecondaryVal1 = SecondaryVal + 1,
 	assign_shared_local_tags(Rest, PrimaryVal, SecondaryVal1, !CtorTags).
 
Index: compiler/ml_code_gen.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/ml_code_gen.m,v
retrieving revision 1.152
diff -u -b -r1.152 ml_code_gen.m
--- compiler/ml_code_gen.m	27 Aug 2005 09:41:56 -0000	1.152
+++ compiler/ml_code_gen.m	27 Aug 2005 14:33:23 -0000
@@ -1151,7 +1151,7 @@
 	goal_info_get_code_gen_nonlocals(GoalInfo0, NonLocals0),
 	set__list_to_set(HeadVars, HeadVarsSet),
 	set__intersect(HeadVarsSet, NonLocals0, NonLocals),
-	goal_info_set_code_gen_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+	goal_info_set_code_gen_nonlocals(NonLocals, GoalInfo0, GoalInfo),
 	Goal = GoalExpr - GoalInfo,
 
 	goal_info_get_context(GoalInfo, Context),
Index: compiler/mode_util.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/mode_util.m,v
retrieving revision 1.169
diff -u -b -r1.169 mode_util.m
--- compiler/mode_util.m	27 Aug 2005 09:41:57 -0000	1.169
+++ compiler/mode_util.m	27 Aug 2005 14:53:02 -0000
@@ -952,7 +952,7 @@
     (
         RecomputeAtomic = no,
         goal_is_atomic(Goal0),
-        Goal0 \= unify(_,lambda_goal(_,_,_,_,_,_,_,_,_),_,_,_)
+        Goal0 \= unify(_, lambda_goal(_,_,_,_,_,_,_,_,_), _, _, _)
             % Lambda expressions always need to be processed.
     ->
         Goal = Goal0,
@@ -961,15 +961,15 @@
         recompute_instmap_delta_2(RecomputeAtomic, Goal0, GoalInfo0,
             Goal, VarTypes, InstMap0, InstMapDelta0, !RI),
         goal_info_get_nonlocals(GoalInfo0, NonLocals),
-        instmap_delta_restrict(InstMapDelta0, NonLocals, InstMapDelta1),
-        goal_info_set_instmap_delta(GoalInfo0, InstMapDelta1, GoalInfo1)
+        instmap_delta_restrict(NonLocals, InstMapDelta0, InstMapDelta1),
+        goal_info_set_instmap_delta(InstMapDelta1, GoalInfo0, GoalInfo1)
     ),
 
     % If the initial instmap is unreachable so is the final instmap.
     ( instmap__is_unreachable(InstMap0) ->
         instmap_delta_init_unreachable(UnreachableInstMapDelta),
-        goal_info_set_instmap_delta(GoalInfo1,
-            UnreachableInstMapDelta, GoalInfo)
+        goal_info_set_instmap_delta(UnreachableInstMapDelta,
+            GoalInfo1, GoalInfo)
     ;
         GoalInfo = GoalInfo1
     ),
@@ -1113,8 +1113,8 @@
         ExtraArgs = [_ | _],
         goal_info_get_instmap_delta(GoalInfo, OldInstMapDelta),
         ExtraArgVars = list__map(foreign_arg_var, ExtraArgs),
-        instmap_delta_restrict(OldInstMapDelta,
-            set__list_to_set(ExtraArgVars), ExtraArgsInstMapDelta),
+        instmap_delta_restrict(set__list_to_set(ExtraArgVars),
+            OldInstMapDelta, ExtraArgsInstMapDelta),
         instmap_delta_apply_instmap_delta(InstMapDelta0,
             ExtraArgsInstMapDelta, large_base, InstMapDelta)
     ).
@@ -1439,8 +1439,8 @@
     ( Inst = Inst0 ->
         GoalInfo = GoalInfo0
     ;
-        instmap_delta_set(InstMapDelta0, Var, Inst, InstMapDelta),
-        goal_info_set_instmap_delta(GoalInfo0, InstMapDelta, GoalInfo)
+        instmap_delta_set(Var, Inst, InstMapDelta0, InstMapDelta),
+        goal_info_set_instmap_delta(InstMapDelta, GoalInfo0, GoalInfo)
     ),
     Goal = GoalExpr - GoalInfo.
 
Index: compiler/modecheck_unify.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/modecheck_unify.m,v
retrieving revision 1.84
diff -u -b -r1.84 modecheck_unify.m
--- compiler/modecheck_unify.m	27 Aug 2005 09:41:58 -0000	1.84
+++ compiler/modecheck_unify.m	27 Aug 2005 14:53:29 -0000
@@ -108,7 +108,7 @@
         modes__construct_initialisation_call(X, VarType, any_inst,
             context_init, no, InitXGoal, !ModeInfo),
         MaybeInitX = yes(InitXGoal),
-        instmap__set(InstMap0, X, any_inst, InstMap),
+        instmap__set(X, any_inst, InstMap0, InstMap),
         InstOfX    = any_inst,
         InstOfY    = InstOfY0
     ;
@@ -329,8 +329,8 @@
     ->
         make_shared_inst_list(NonLocalInsts, SharedNonLocalInsts,
             ModuleInfo2, ModuleInfo3),
-        instmap__set_vars(InstMap1, NonLocalsList, SharedNonLocalInsts,
-            InstMap2),
+        instmap__set_vars(NonLocalsList, SharedNonLocalInsts,
+            InstMap1, InstMap2),
         mode_info_set_module_info(ModuleInfo3, !ModeInfo),
         mode_info_set_instmap(InstMap2, !ModeInfo),
 
@@ -356,8 +356,8 @@
         % Ensure that the non-local vars are shared OUTSIDE the
         % lambda unification as well as inside.
 
-        instmap__set_vars(InstMap0, NonLocalsList, SharedNonLocalInsts,
-            InstMap11),
+        instmap__set_vars(NonLocalsList, SharedNonLocalInsts,
+            InstMap0, InstMap11),
         mode_info_set_instmap(InstMap11, !ModeInfo),
 
         % Now modecheck the unification of X with the lambda-expression.
@@ -797,8 +797,8 @@
     % but that shouldn't cause any problems.
     %
     set__list_to_set([Var0, Var], NonLocals),
-    goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo1),
-    goal_info_set_context(GoalInfo1, Context, GoalInfo2),
+    goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo1),
+    goal_info_set_context(Context, GoalInfo1, GoalInfo2),
 
     %
     % Look up the map(tvar, type_info_locn) in the proc_info,
Index: compiler/modes.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/modes.m,v
retrieving revision 1.308
diff -u -b -r1.308 modes.m
--- compiler/modes.m	27 Aug 2005 09:41:58 -0000	1.308
+++ compiler/modes.m	27 Aug 2005 14:53:56 -0000
@@ -898,8 +898,8 @@
             instmap__from_assoc_list(HeadVarFinalInsts, FinalInstMap),
             compute_instmap_delta(InstMap0, FinalInstMap, BodyNonLocals,
                 DeltaInstMap),
-            goal_info_set_instmap_delta(BodyGoalInfo0, DeltaInstMap,
-                BodyGoalInfo),
+            goal_info_set_instmap_delta(DeltaInstMap,
+                BodyGoalInfo0, BodyGoalInfo),
             Body = NewGoalExpr - BodyGoalInfo,
             ArgFinalInsts = ArgFinalInsts0
         ;
@@ -1255,7 +1255,7 @@
     modecheck_goal_expr(Goal0, GoalInfo0, Goal, !ModeInfo, !IO),
     compute_goal_instmap_delta(InstMap0, Goal, GoalInfo0, GoalInfo, !ModeInfo).
 
-compute_goal_instmap_delta(InstMap0, Goal, GoalInfo0, GoalInfo, !ModeInfo) :-
+compute_goal_instmap_delta(InstMap0, Goal, !GoalInfo, !ModeInfo) :-
     ( Goal = conj([]) ->
         %
         % When modecheck_unify.m replaces a unification with a
@@ -1268,11 +1268,11 @@
         instmap_delta_init_reachable(DeltaInstMap),
         mode_info_set_instmap(InstMap0, !ModeInfo)
     ;
-        goal_info_get_nonlocals(GoalInfo0, NonLocals),
+        goal_info_get_nonlocals(!.GoalInfo, NonLocals),
         mode_info_get_instmap(!.ModeInfo, InstMap),
         compute_instmap_delta(InstMap0, InstMap, NonLocals, DeltaInstMap)
     ),
-    goal_info_set_instmap_delta(GoalInfo0, DeltaInstMap, GoalInfo).
+    goal_info_set_instmap_delta(DeltaInstMap, !GoalInfo).
 
 modecheck_goal_expr(conj(List0), GoalInfo0, Goal, !ModeInfo, !IO) :-
     mode_checkpoint(enter, "conj", !ModeInfo, !IO),
@@ -1663,7 +1663,7 @@
         set__difference(NewArgVars, OldArgVars, IntroducedVars),
         set__union(NonLocals0, IntroducedVars, OutsideVars),
         set__intersect(OutsideVars, NewArgVars, NonLocals),
-        goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+        goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
 
         % combine the main goal and the extra goals into a conjunction
         Goal0 = MainGoal - GoalInfo,
@@ -1713,7 +1713,7 @@
 handle_extra_goals_contexts([Goal0 | Goals0], Context, [Goal | Goals]) :-
     Goal0 = Expr - GoalInfo0,
     Goal  = Expr - GoalInfo,
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     handle_extra_goals_contexts(Goals0, Context, Goals).
 
 %-----------------------------------------------------------------------------%
@@ -1812,7 +1812,7 @@
     Goal0 = GoalExpr0 - GoalInfo0,
     hlds_goal__goal_info_get_nonlocals(GoalInfo0, NonLocals0),
     NonLocals = set__union(InitedVars, NonLocals0),
-    hlds_goal__goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+    hlds_goal__goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
     ( GoalExpr0 = disj(Disjs0) ->
         Disjs = list__map(append_init_calls_to_goal(InitedVars, InitCalls),
                 Disjs0),
@@ -1852,7 +1852,7 @@
 
 set_vars_to_inst_any([], InstMap) = InstMap.
 set_vars_to_inst_any([Var | Vars], InstMap0) = InstMap :-
-    instmap__set(InstMap0, Var, any_inst, InstMap1),
+    instmap__set(Var, any_inst, InstMap0, InstMap1),
     InstMap = set_vars_to_inst_any(Vars, InstMap1).
 
 %-----------------------------------------------------------------------------%
@@ -2968,7 +2968,7 @@
             % the only thing we can have done is lose uniqueness.
             inst_matches_initial(Inst0, Inst, Type, ModuleInfo)
         ->
-            instmap__set(InstMap0, Var0, Inst, InstMap),
+            instmap__set(Var0, Inst, InstMap0, InstMap),
             mode_info_set_instmap(InstMap, !ModeInfo)
         ;
             % We must have either added some information,
@@ -3001,7 +3001,7 @@
             mode_info_error(WaitingVars,
                 mode_error_bind_var(Reason0, Var0, Inst0, Inst), !ModeInfo)
         ;
-            instmap__set(InstMap0, Var0, Inst, InstMap),
+            instmap__set(Var0, Inst, InstMap0, InstMap),
             mode_info_set_instmap(InstMap, !ModeInfo),
             mode_info_get_delay_info(!.ModeInfo, DelayInfo0),
             delay_info__bind_var(Var0, DelayInfo0, DelayInfo),
@@ -3184,9 +3184,9 @@
     polymorphism__create_poly_info_for_new_call(ModuleInfo0, PredInfo0,
         ProcInfo0, VarSet0, VarTypes0, PolyInfo0),
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo1),
-    goal_info_set_nonlocals(GoalInfo1, NonLocals, GoalInfo2),
-    goal_info_set_instmap_delta(GoalInfo2, InstmapDelta, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo1),
+    goal_info_set_nonlocals(NonLocals, GoalInfo1, GoalInfo2),
+    goal_info_set_instmap_delta(InstmapDelta, GoalInfo2, GoalInfo),
     polymorphism__process_new_call(PredId, ProcId, ArgVars, not_builtin,
         CallUnifyContext, qualified(ModuleName, PredName),
         GoalInfo, Goal, PolyInfo0, PolyInfo),
Index: compiler/pd_debug.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/pd_debug.m,v
retrieving revision 1.13
diff -u -b -r1.13 pd_debug.m
--- compiler/pd_debug.m	22 Mar 2005 06:40:17 -0000	1.13
+++ compiler/pd_debug.m	28 Aug 2005 02:50:47 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1998-2005 University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -96,8 +98,7 @@
 		MaybeVersion = version(more_general, PredProcId, Version,
 			_, _),
 		io__write_string("More general version.\n", !IO),
-		pd_debug__output_version(ModuleInfo, PredProcId, Version, no,
-			!IO)
+        pd_debug__output_version(ModuleInfo, PredProcId, Version, no, !IO)
 	).
 
 %-----------------------------------------------------------------------------%
@@ -144,7 +145,7 @@
 	goal_info_get_nonlocals(GoalInfo, NonLocals),
 	module_info_pred_proc_info(ModuleInfo, PredId, ProcId, _, ProcInfo),
 	proc_info_varset(ProcInfo, VarSet),
-	instmap__restrict(InstMap, NonLocals, InstMap1),
+    instmap__restrict(NonLocals, InstMap, InstMap1),
 	io__write_string(" args: ", !IO),
 	mercury_output_vars(Args, VarSet, yes, !IO),
 	io__nl(!IO),
@@ -162,8 +163,7 @@
 		WriteUnfoldedGoal = yes,
 		proc_info_goal(ProcInfo, ProcGoal),
 		io__write_string("Unfolded goal\n", !IO),
-		hlds_out__write_goal(ProcGoal,
-			ModuleInfo, VarSet, yes, 1, "\n", !IO),
+        hlds_out__write_goal(ProcGoal, ModuleInfo, VarSet, yes, 1, "\n", !IO),
 		io__nl(!IO)
 	;
 		WriteUnfoldedGoal = no
@@ -213,7 +213,7 @@
 	pd_info_get_module_info(PDInfo, ModuleInfo),
 	io__write_string(Msg, !IO),
 	goal_util__goal_vars(GoalExpr - GoalInfo, Vars),
-	instmap__restrict(InstMap, Vars, InstMap1),
+    instmap__restrict(Vars, InstMap, InstMap1),
 	hlds_out__write_instmap(InstMap1, VarSet, yes, 1, !IO),
 	io__nl(!IO),
 	hlds_out__write_goal(GoalExpr - GoalInfo, ModuleInfo, VarSet,
Index: compiler/pd_util.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/pd_util.m,v
retrieving revision 1.39
diff -u -b -r1.39 pd_util.m
--- compiler/pd_util.m	27 Aug 2005 09:41:58 -0000	1.39
+++ compiler/pd_util.m	28 Aug 2005 05:45:10 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1998-2005 University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -29,96 +31,104 @@
 :- import_module std_util.
 
 	% Pick out the pred_proc_ids of the calls in a list of atomic goals.
+    %
 :- pred pd_util__goal_get_calls(hlds_goal::in, list(pred_proc_id)::out) is det.
 
 	% Call constraint.m to transform a goal so that goals which
 	% can fail are executed as early as possible.
+    %
 :- pred pd_util__propagate_constraints(hlds_goal::in, hlds_goal::out,
 	pd_info::in, pd_info::out, io::di, io::uo) is det.
 
 	% Apply simplify.m to the goal.
+    %
 :- pred pd_util__simplify_goal(list(simplification)::in, hlds_goal::in,
 	hlds_goal::out, pd_info::in, pd_info::out) is det.
 
 	% Apply unique_modes.m to the goal.
+    %
 :- pred pd_util__unique_modecheck_goal(hlds_goal::in, hlds_goal::out,
 	list(mode_error_info)::out, pd_info::in, pd_info::out,
 	io::di, io::uo) is det.
 
 	% Apply unique_modes.m to the goal.
+    %
 :- pred pd_util__unique_modecheck_goal(set(prog_var)::in,
 	hlds_goal::in, hlds_goal::out, list(mode_error_info)::out,
 	pd_info::in, pd_info::out, io::di, io::uo) is det.
 
 	% Find out which arguments of the procedure are interesting
 	% for deforestation.
+    %
 :- pred pd_util__get_branch_vars_proc(pred_proc_id::in, proc_info::in,
 	pd_arg_info::in, pd_arg_info::out,
 	module_info::in, module_info::out) is det.
 
 	% Find out which variables of the goal are interesting
 	% for deforestation.
+    %
 :- pred pd_util__get_branch_vars_goal(hlds_goal::in,
 	maybe(pd_branch_info(prog_var))::out, pd_info::in, pd_info::out)
 	is det.
 
 	% Recompute the non-locals of the goal.
+    %
 :- pred pd_util__requantify_goal(set(prog_var)::in,
 	hlds_goal::in, hlds_goal::out, pd_info::in, pd_info::out) is det.
 
 	% Apply mode_util__recompute_instmap_delta to the goal.
+    %
 :- pred pd_util__recompute_instmap_delta(hlds_goal::in, hlds_goal::out,
 	pd_info::in, pd_info::out) is det.
 
 	% Convert from information about the argument positions to
 	% information about the argument variables.
+    %
 :- pred pd_util__convert_branch_info(pd_branch_info(int)::in,
 	list(prog_var)::in, pd_branch_info(prog_var)::out) is det.
 
 	% inst_MSG(InstA, InstB, InstC):
-	% 	Take the most specific generalisation of two insts.
-	%       The information in InstC is the minimum of the
-	%       information in InstA and InstB.  Where InstA and
-	%       InstB specify a binding (free or bound), it must be
-	%       the same in both.
-	% 	The uniqueness of the final inst is taken from InstB.
-	% 	The difference between inst_merge and inst_MSG is that the
-	% 	msg of `bound([functor, []])' and `bound([another_functor, []])'
-	%	is `ground' rather than `bound([functor, another_functor])'.
-	% 	Also the msgs are not tabled, so the module_info is not
-	% 	threaded through.
-	% 	If an inst is "rounded off", it must not contain `any' insts
-	% 	and must be completely unique or completely non-unique.
-	% 	This is used in generalisation to avoid non-termination
-	% 	of deforestation - InstA is the inst in an old version,
-	% 	we are taking the msg with to avoid non-termination,
-	% 	InstB is the inst in the new version we want to create.
-	%	It is always safe for inst_MSG to fail - this will just
-	% 	result in less optimization.
-	% 	Mode analysis should be run on the goal to
-	%	check that this doesn't introduce mode errors, since
-	% 	the information that was removed may actually have been
-	%	necessary for mode correctness.
+    %
+    % Take the most specific generalisation of two insts. The information
+    % in InstC is the minimum of the information in InstA and InstB.
+    % Where InstA and InstB specify a binding (free or bound), it must be
+    % the same in both. The uniqueness of the final inst is taken from InstB.
+    % The difference between inst_merge and inst_MSG is that the msg of
+    % `bound([functor, []])' and `bound([another_functor, []])' is `ground'
+    % rather than `bound([functor, another_functor])'. Also the msgs are not
+    % tabled, so the module_info is not threaded through.
+    % If an inst is "rounded off", it must not contain `any' insts and must be
+    % completely unique or completely non-unique. This is used in
+    % generalisation to avoid non-termination of deforestation -
+    % InstA is the inst in an old version, we are taking the msg with
+    % to avoid non-termination, InstB is the inst in the new version
+    % we want to create.
+    %
+    % It is always safe for inst_MSG to fail - this will just result
+    % in less optimization. Mode analysis should be run on the goal to check
+    % that this doesn't introduce mode errors, since the information that was
+    % removed may actually have been necessary for mode correctness.
+    %
 :- pred inst_MSG((inst)::in, (inst)::in, module_info::in, (inst)::out)
 	is semidet.
 
-	% Produce an estimate of the size of an inst, based on the
-	% number of nodes in the inst. The inst is expanded down
-	% to the first repeat of an already expanded inst_name.
+    % Produce an estimate of the size of an inst, based on the number of nodes
+    % in the inst. The inst is expanded down to the first repeat of an already
+    % expanded inst_name.
+    %
 :- pred pd_util__inst_size(module_info::in, (inst)::in, int::out) is det.
 :- pred pd_util__inst_list_size(module_info::in, list(inst)::in,
 		int::out) is det.
 
 	% pd_util__goals_match(ModuleInfo, OldGoal, OldArgs, OldArgTypes,
-	%		NewGoal, NewArgTypes,
-	% 		OldToNewVarRenaming, OldToNewTypeSubst)
+    %   NewGoal, NewArgTypes, OldToNewVarRenaming, OldToNewTypeSubst):
 	%
-	% Check the shape of the goals, and return a mapping from
-	% variables in the old goal to variables in the new and
-	% a substitution to apply to the types. This only
-	% attempts to match `simple' lists of goals, which contain
-	% only conj, some, not and atomic goals, since deforest.m
+    % Check the shape of the goals, and return a mapping from variables
+    % in the old goal to variables in the new and a substitution to apply
+    % to the types. This only attempts to match `simple' lists of goals,
+    % which contain only conj, some, not and atomic goals, since deforest.m
 	% only attempts to optimize those types of conjunctions.
+    %
 :- pred pd_util__goals_match(module_info::in, hlds_goal::in, list(prog_var)::in,
 	list(type)::in, hlds_goal::in, vartypes::in,
 	map(prog_var, prog_var)::out, tsubst::out) is semidet.
@@ -130,6 +140,7 @@
 	% - the goals are not impure
 	% - any possible change in termination behaviour is allowed
 	% 	according to the semantics options.
+    %
 :- pred pd_util__can_reorder_goals(module_info::in, bool::in,
 	hlds_goal::in, hlds_goal::in) is semidet.
 
@@ -154,6 +165,7 @@
 :- import_module hlds__quantification.
 :- import_module libs__globals.
 :- import_module libs__options.
+:- import_module parse_tree__error_util.
 :- import_module transform_hlds__constraint.
 :- import_module transform_hlds__pd_cost.
 :- import_module transform_hlds__pd_debug.
@@ -164,6 +176,8 @@
 :- import_module require.
 :- import_module set.
 :- import_module term.
+:- import_module svmap.
+:- import_module svset.
 
 pd_util__goal_get_calls(Goal0, CalledPreds) :-
 	goal_to_conj_list(Goal0, GoalList),
@@ -175,27 +189,25 @@
 
 %-----------------------------------------------------------------------------%
 
-pd_util__propagate_constraints(Goal0, Goal, !PDInfo, !IO) :-
+pd_util__propagate_constraints(!Goal, !PDInfo, !IO) :-
 	globals__io_lookup_bool_option(local_constraint_propagation,
 		ConstraintProp, !IO),
 	(
 		ConstraintProp = yes,
+        Goal0 = !.Goal,
 		pd_debug__message("%% Propagating constraints\n", [], !IO),
-		pd_debug__output_goal(!.PDInfo, "before constraints\n", Goal0,
-			!IO),
+        pd_debug__output_goal(!.PDInfo, "before constraints\n", Goal0, !IO),
 		pd_info_get_module_info(!.PDInfo, ModuleInfo0),
 		pd_info_get_proc_info(!.PDInfo, ProcInfo0),
 		pd_info_get_instmap(!.PDInfo, InstMap),
 		proc_info_vartypes(ProcInfo0, VarTypes0),
 		proc_info_varset(ProcInfo0, VarSet0),
-		constraint_info_init(ModuleInfo0, VarTypes0,
-			VarSet0, InstMap, CInfo0),
+        constraint_info_init(ModuleInfo0, VarTypes0, VarSet0, InstMap, CInfo0),
 		Goal0 = _ - GoalInfo0,
 		goal_info_get_nonlocals(GoalInfo0, NonLocals),
-		constraint__propagate_constraints_in_goal(Goal0, Goal1,
-			CInfo0, CInfo),
-		constraint_info_deconstruct(CInfo, ModuleInfo,
-			VarTypes, VarSet, Changed),
+        constraint__propagate_constraints_in_goal(!Goal, CInfo0, CInfo),
+        constraint_info_deconstruct(CInfo, ModuleInfo, VarTypes, VarSet,
+            Changed),
 		pd_info_set_module_info(ModuleInfo, !PDInfo),
 		proc_info_set_vartypes(VarTypes, ProcInfo0, ProcInfo1),
 		proc_info_set_varset(VarSet, ProcInfo1, ProcInfo),
@@ -203,45 +215,34 @@
 		(
 			Changed = yes,
 			pd_debug__output_goal(!.PDInfo,
-				"after constraints, before recompute\n",
-				Goal1, !IO),
-			pd_util__requantify_goal(NonLocals, Goal1, Goal2,
-				!PDInfo),
-			pd_util__recompute_instmap_delta(Goal2, Goal3,
-				!PDInfo),
-			pd_util__rerun_det_analysis(Goal3, Goal4,
-				!PDInfo, !IO),
+                "after constraints, before recompute\n", !.Goal, !IO),
+            pd_util__requantify_goal(NonLocals, !Goal, !PDInfo),
+            pd_util__recompute_instmap_delta(!Goal, !PDInfo),
+            pd_util__rerun_det_analysis(!Goal, !PDInfo, !IO),
 		        module_info_globals(ModuleInfo, Globals),
-		        simplify__find_simplifications(no,
-				Globals, Simplifications),
-			pd_util__simplify_goal(Simplifications, Goal4, Goal,
-				!PDInfo)
-		;
-			% Use Goal0 rather than Goal1 because
-			% constraint propagation can make the
-			% quantification information more
-			% conservative even if it doesn't
-			% optimize anything.
+            simplify__find_simplifications(no, Globals, Simplifications),
+            pd_util__simplify_goal(Simplifications, !Goal, !PDInfo)
+        ;
+            % Use Goal0 rather than the output of propagate_constraints_in_goal
+            % because constraint propagation can make the % quantification
+            % information more conservative even if it doesn't optimize
+            % anything.
 			Changed = no,
-			Goal = Goal0
+            !:Goal = Goal0
 		)
 	;
-		ConstraintProp = no,
-		Goal = Goal0
+        ConstraintProp = no
 	).
 
 %-----------------------------------------------------------------------------%
 
 pd_util__simplify_goal(Simplifications, Goal0, Goal, !PDInfo) :-
-	%
 	% Construct a simplify_info.
-	%
 	pd_info_get_module_info(!.PDInfo, ModuleInfo0),
 	module_info_globals(ModuleInfo0, Globals),
 	pd_info_get_pred_proc_id(!.PDInfo, proc(PredId, ProcId)),
 	proc_info_vartypes(ProcInfo0, VarTypes0),
-	det_info_init(ModuleInfo0, VarTypes0, PredId, ProcId, Globals,
-		DetInfo0),
+    det_info_init(ModuleInfo0, VarTypes0, PredId, ProcId, Globals, DetInfo0),
 	pd_info_get_instmap(!.PDInfo, InstMap0),
 	pd_info_get_proc_info(!.PDInfo, ProcInfo0),
 	simplify_info_init(DetInfo0, Simplifications, InstMap0, ProcInfo0,
@@ -249,9 +250,7 @@
 
 	simplify__process_goal(Goal0, Goal, SimplifyInfo0, SimplifyInfo),
 
-	%
 	% Deconstruct the simplify_info.
-	%
 	simplify_info_get_module_info(SimplifyInfo, ModuleInfo),
 	simplify_info_get_varset(SimplifyInfo, VarSet),
 	simplify_info_get_var_types(SimplifyInfo, VarTypes),
@@ -273,10 +272,7 @@
 		!PDInfo, !IO).
 
 pd_util__unique_modecheck_goal(LiveVars, Goal0, Goal, Errors, !PDInfo, !IO) :-
-
-	%
 	% Construct a mode_info.
-	%
 	pd_info_get_pred_proc_id(!.PDInfo, PredProcId),
 	PredProcId = proc(PredId, ProcId),
 	pd_info_get_module_info(!.PDInfo, ModuleInfo0),
@@ -287,13 +283,11 @@
 	module_info_set_pred_proc_info(PredId, ProcId, PredInfo0, ProcInfo0,
 		ModuleInfo0, ModuleInfo1),
 
-	% If we perform generalisation, we shouldn't change any called
-	% procedures, since that could cause a less efficient version to
-	% be chosen.
+    % If we perform generalisation, we shouldn't change any called procedures,
+    % since that could cause a less efficient version to be chosen.
 	MayChangeCalledProc = may_not_change_called_proc,
-	mode_info_init(ModuleInfo1, PredId, ProcId, Context,
-		LiveVars, InstMap0, check_unique_modes,
-		MayChangeCalledProc, ModeInfo0),
+    mode_info_init(ModuleInfo1, PredId, ProcId, Context, LiveVars, InstMap0,
+        check_unique_modes, MayChangeCalledProc, ModeInfo0),
 
 	unique_modes__check_goal(Goal0, Goal, ModeInfo0, ModeInfo1, !IO),
 	globals__io_lookup_bool_option(debug_pd, Debug, !IO),
@@ -306,9 +300,7 @@
 	),
 	mode_info_get_errors(ModeInfo, Errors),
 
-	%
 	% Deconstruct the mode_info.
-	%
 	mode_info_get_module_info(ModeInfo, ModuleInfo),
 	mode_info_get_varset(ModeInfo, VarSet),
 	mode_info_get_var_types(ModeInfo, VarTypes),
@@ -320,40 +312,41 @@
 	proc_info_set_vartypes(VarTypes, ProcInfo2, ProcInfo),
 	pd_info_set_proc_info(ProcInfo, !PDInfo).
 
-	% Work out which vars are live later in the computation based
-	% on which of the non-local variables are not clobbered by the goal.
+    % Work out which vars are live later in the computation based on
+    % which of the non-local variables are not clobbered by the goal.
+    %
 :- pred pd_util__get_goal_live_vars(pd_info::in, hlds_goal::in,
 	set(prog_var)::out) is det.
 
-pd_util__get_goal_live_vars(PDInfo, _ - GoalInfo, Vars) :-
+pd_util__get_goal_live_vars(PDInfo, _ - GoalInfo, !:Vars) :-
 	pd_info_get_module_info(PDInfo, ModuleInfo),
 	goal_info_get_instmap_delta(GoalInfo, InstMapDelta),
 	pd_info_get_instmap(PDInfo, InstMap),
 	goal_info_get_nonlocals(GoalInfo, NonLocals),
 	set__to_sorted_list(NonLocals, NonLocalsList),
-	set__init(Vars0),
+    set__init(!:Vars),
 	get_goal_live_vars_2(ModuleInfo, NonLocalsList, InstMap, InstMapDelta,
-		Vars0, Vars).
+        !Vars).
 
 :- pred pd_util__get_goal_live_vars_2(module_info::in, list(prog_var)::in,
 	instmap::in, instmap_delta::in,
 	set(prog_var)::in, set(prog_var)::out) is det.
 
-pd_util__get_goal_live_vars_2(_, [], _, _, Vars, Vars).
+pd_util__get_goal_live_vars_2(_, [], _, _, !Vars).
 pd_util__get_goal_live_vars_2(ModuleInfo, [NonLocal | NonLocals],
-		InstMap, InstMapDelta, Vars0, Vars) :-
+        InstMap, InstMapDelta, !Vars) :-
 	( instmap_delta_search_var(InstMapDelta, NonLocal, FinalInst0) ->
 		FinalInst = FinalInst0
 	;
 		instmap__lookup_var(InstMap, NonLocal, FinalInst)
 	),
 	( inst_is_clobbered(ModuleInfo, FinalInst) ->
-		Vars1 = Vars0
+        true
 	;
-		set__insert(Vars0, NonLocal, Vars1)
+        svset__insert(NonLocal, !Vars)
 	),
-	pd_util__get_goal_live_vars_2(ModuleInfo, NonLocals,
-		InstMap, InstMapDelta, Vars1, Vars).
+    pd_util__get_goal_live_vars_2(ModuleInfo, NonLocals, InstMap, InstMapDelta,
+        !Vars).
 
 %-----------------------------------------------------------------------------%
 
@@ -379,14 +372,11 @@
 
 	module_info_globals(ModuleInfo, Globals),
 	proc_info_vartypes(ProcInfo, VarTypes),
-	det_info_init(ModuleInfo, VarTypes, PredId, ProcId,
-		Globals, DetInfo),
+    det_info_init(ModuleInfo, VarTypes, PredId, ProcId, Globals, DetInfo),
 	pd_info_get_instmap(!.PDInfo, InstMap),
 	det_infer_goal(Goal0, Goal, InstMap, SolnContext, DetInfo, _, Msgs),
 
-	%
 	% Make sure there were no errors.
-	%
 	disable_det_warnings(OptionsToRestore, !IO),
 	det_report_msgs(Msgs, ModuleInfo, _, ErrCnt, !IO),
 	restore_det_warnings(OptionsToRestore, !IO),
@@ -399,8 +389,7 @@
 	ArgInfo = pd_branch_info(ArgMap, LeftArgs, OpaqueArgs),
 	map__to_assoc_list(ArgMap, ArgList),
 	map__init(BranchVarMap0),
-	pd_util__convert_branch_info_2(ArgList, Args,
-		BranchVarMap0, BranchVarMap),
+    pd_util__convert_branch_info_2(ArgList, Args, BranchVarMap0, BranchVarMap),
 
 	set__to_sorted_list(LeftArgs, LeftArgNos),
 	list__map(list__index1_det(Args), LeftArgNos, LeftVars0),
@@ -419,15 +408,13 @@
 pd_util__convert_branch_info_2([ArgNo - Branches | ArgInfos], Args,
 		!VarInfo) :-
 	list__index1_det(Args, ArgNo, Arg),
-	map__set(!.VarInfo, Arg, Branches, !:VarInfo),
+    svmap__set(Arg, Branches, !VarInfo),
 	pd_util__convert_branch_info_2(ArgInfos, Args, !VarInfo).
 
 %-----------------------------------------------------------------------------%
 
 :- type pd_var_info 	==	branch_info_map(prog_var).
 
-	% Find out which arguments of the procedure are interesting
-	% for deforestation.
 pd_util__get_branch_vars_proc(PredProcId, ProcInfo, !ArgInfo, !ModuleInfo) :-
 	proc_info_goal(ProcInfo, Goal),
 	proc_info_vartypes(ProcInfo, VarTypes),
@@ -446,17 +433,16 @@
 			ThisProcArgMap0, ThisProcArgMap1,
 			ThisProcLeftArgs0, ThisProcLeftArgs),
 		set__init(OpaqueArgs0),
-		BranchInfo0 = pd_branch_info(ThisProcArgMap1,
-				ThisProcLeftArgs, OpaqueArgs0),
-		map__set(!.ArgInfo, PredProcId, BranchInfo0, !:ArgInfo),
+        BranchInfo0 = pd_branch_info(ThisProcArgMap1, ThisProcLeftArgs,
+            OpaqueArgs0),
+        svmap__set(PredProcId, BranchInfo0, !ArgInfo),
 
 			% Look for opportunities for deforestation in
 			% the sub-branches of the top-level goal.
 		pd_util__get_sub_branch_vars_goal(!.ArgInfo, GoalList,
 			VarTypes, InstMap0, Vars, AllVars, !ModuleInfo),
 		pd_util__get_extra_info_headvars(HeadVars, 1, LeftVars0,
-			AllVars, ThisProcArgMap0, ThisProcArgMap,
-			ThisProcLeftArgs0, _),
+            AllVars, ThisProcArgMap0, ThisProcArgMap, ThisProcLeftArgs0, _),
 
 		proc_info_argmodes(ProcInfo, ArgModes),
 		pd_util__get_opaque_args(!.ModuleInfo, 1, ArgModes,
@@ -464,7 +450,7 @@
 
 		BranchInfo = pd_branch_info(ThisProcArgMap, ThisProcLeftArgs,
 			OpaqueArgs),
-		map__set(!.ArgInfo, PredProcId, BranchInfo, !:ArgInfo)
+        svmap__set(PredProcId, BranchInfo, !ArgInfo)
 	;
 		true
 	).
@@ -473,6 +459,7 @@
 	% such as io__states. If a later goal in a conjunction depends
 	% on one of these, it is unlikely that the deforestation will
 	% be able to successfully fold to give a recursive definition.
+    %
 :- pred pd_util__get_opaque_args(module_info::in, int::in, list(mode)::in,
 	branch_info_map(int)::in, set(int)::in, set(int)::out) is det.
 
@@ -491,9 +478,10 @@
 	pd_util__get_opaque_args(ModuleInfo, NextArg, ArgModes,
 		ExtraInfoArgs, !OpaqueArgs).
 
-	% From the information about variables for which we have extra
-	% information in the branches, compute the argument numbers
-	% for which we have extra information.
+    % From the information about variables for which we have extra information
+    % in the branches, compute the argument numbers for which we have extra
+    % information.
+    %
 :- pred pd_util__get_extra_info_headvars(list(prog_var)::in, int::in,
 	set(prog_var)::in, pd_var_info::in,
 	branch_info_map(int)::in, branch_info_map(int)::out,
@@ -503,13 +491,12 @@
 pd_util__get_extra_info_headvars([HeadVar | HeadVars], ArgNo,
 		LeftVars, VarInfo, !ThisProcArgs, !ThisProcLeftVars) :-
 	( map__search(VarInfo, HeadVar, ThisVarInfo) ->
-		map__det_insert(!.ThisProcArgs, ArgNo, ThisVarInfo,
-			!:ThisProcArgs)
+        svmap__det_insert(ArgNo, ThisVarInfo, !ThisProcArgs)
 	;
 		true
 	),
 	( set__member(HeadVar, LeftVars) ->
-		set__insert(!.ThisProcLeftVars, ArgNo, !:ThisProcLeftVars)
+        svset__insert(ArgNo, !ThisProcLeftVars)
 	;
 		true
 	),
@@ -538,8 +525,7 @@
 
 			% OpaqueVars is only filled in for calls.
 		set__init(OpaqueVars),
-		MaybeBranchInfo = yes(
-			pd_branch_info(Vars, LeftVars, OpaqueVars)
+        MaybeBranchInfo = yes(pd_branch_info(Vars, LeftVars, OpaqueVars)
 		)
 	;
 		MaybeBranchInfo = no
@@ -561,8 +547,8 @@
 		% since deforestation of goals with more than one is
 		% likely to be less productive.
 		!.FoundBranch = no,
-		pd_util__get_branch_vars(ModuleInfo, Goal,
-			InstMapDeltas, InstMap, 1, !Vars),
+        pd_util__get_branch_vars(ModuleInfo, Goal, InstMapDeltas, InstMap,
+            1, !Vars),
 		pd_util__get_left_vars(Goal, !LeftVars),
 		!:FoundBranch = yes
 	;
@@ -576,8 +562,7 @@
 	list(instmap_delta)::out) is semidet.
 
 pd_util__get_branch_instmap_deltas(Goal, [CondDelta, ThenDelta, ElseDelta]) :-
-	Goal = if_then_else(_, _ - CondInfo, _ - ThenInfo,
-		_ - ElseInfo) - _,
+    Goal = if_then_else(_, _ - CondInfo, _ - ThenInfo, _ - ElseInfo) - _,
 	goal_info_get_instmap_delta(CondInfo, CondDelta),
 	goal_info_get_instmap_delta(ThenInfo, ThenDelta),
 	goal_info_get_instmap_delta(ElseInfo, ElseDelta).
@@ -599,6 +584,7 @@
 	% Get the variables for which we can do unfolding if the goals to
 	% the left supply the top-level functor. Eventually this should
 	% also check for if-then-elses with simple conditions.
+    %
 :- pred pd_util__get_left_vars(hlds_goal::in,
 	set(prog_var)::in, set(prog_var)::out) is det.
 
@@ -619,14 +605,11 @@
 	AddExtraInfoVars =
 		(pred(ChangedVar::in, Vars0::in, Vars::out) is det :-
 			(
-				instmap__lookup_var(InstMap, ChangedVar,
-					VarInst),
-				instmap_delta_search_var(InstMapDelta,
-					ChangedVar, DeltaVarInst),
-				inst_is_bound_to_functors(ModuleInfo,
-					DeltaVarInst, [_]),
-				\+ inst_is_bound_to_functors(ModuleInfo,
-					VarInst, [_])
+                instmap__lookup_var(InstMap, ChangedVar, VarInst),
+                instmap_delta_search_var(InstMapDelta, ChangedVar,
+                    DeltaVarInst),
+                inst_is_bound_to_functors(ModuleInfo, DeltaVarInst, [_]),
+                \+ inst_is_bound_to_functors(ModuleInfo, VarInst, [_])
 			->
 				( map__search(Vars0, ChangedVar, Set0) ->
 					set__insert(Set0, BranchNo, Set)
@@ -650,7 +633,7 @@
 		;
 			set__singleton_set(SwitchVarSet, BranchNo)
 		),
-		map__set(!.ExtraVars, SwitchVar, SwitchVarSet, !:ExtraVars)
+        svmap__set(SwitchVar, SwitchVarSet, !ExtraVars)
 	;
 		true
 	),
@@ -659,6 +642,7 @@
 		NextBranch, !ExtraVars).
 
 	% Look at the goals in the branches for extra information.
+    %
 :- pred pd_util__get_sub_branch_vars_goal(pd_arg_info::in,
 	list(hlds_goal)::in, vartypes::in, instmap::in,
 	branch_info_map(prog_var)::in, branch_info_map(prog_var)::out,
@@ -713,8 +697,7 @@
 
 pd_util__examine_case_list(_, _, _, [], _, _, !Vars, !ModuleInfo).
 pd_util__examine_case_list(ProcArgInfo, BranchNo, Var,
-		[case(ConsId, Goal) | Goals], VarTypes, InstMap,
-		!Vars, !ModuleInfo) :-
+        [case(ConsId, Goal) | Goals], VarTypes, InstMap, !Vars, !ModuleInfo) :-
 	map__lookup(VarTypes, Var, Type),
 	instmap__bind_var_to_functor(Var, Type, ConsId, InstMap, InstMap1,
 		!ModuleInfo),
@@ -730,15 +713,11 @@
 	branch_info_map(prog_var)::in, branch_info_map(prog_var)::out) is det.
 
 pd_util__examine_branch(_, _, _, [], _, _, !Vars).
-pd_util__examine_branch(ModuleInfo, ProcArgInfo, BranchNo,
-		[Goal | Goals], VarTypes, InstMap, !Vars) :-
+pd_util__examine_branch(ModuleInfo, ProcArgInfo, BranchNo, [Goal | Goals],
+        VarTypes, InstMap, !Vars) :-
 	( Goal = call(PredId, ProcId, Args, _, _, _) - _ ->
-		(
-			map__search(ProcArgInfo, proc(PredId, ProcId),
-				ThisProcArgInfo)
-		->
-			pd_util__convert_branch_info(ThisProcArgInfo,
-				Args, BranchInfo),
+        ( map__search(ProcArgInfo, proc(PredId, ProcId), ThisProcArgInfo) ->
+            pd_util__convert_branch_info(ThisProcArgInfo, Args, BranchInfo),
 			BranchInfo = pd_branch_info(!:Vars, _, _),
 			map__keys(!.Vars, ExtraVars1),
 			combine_vars(BranchNo, ExtraVars1, !Vars)
@@ -769,10 +748,10 @@
 combine_vars(BranchNo, [ExtraVar | ExtraVars], !Vars) :-
 	( map__search(!.Vars, ExtraVar, Branches0) ->
 		set__insert(Branches0, BranchNo, Branches),
-		map__det_update(!.Vars, ExtraVar, Branches, !:Vars)
+        svmap__det_update(ExtraVar, Branches, !Vars)
 	;
 		set__singleton_set(Branches, BranchNo),
-		map__det_insert(!.Vars, ExtraVar, Branches, !:Vars)
+        svmap__det_insert(ExtraVar, Branches, !Vars)
 	),
 	combine_vars(BranchNo, ExtraVars, !Vars).
 
@@ -800,15 +779,6 @@
 
 %-----------------------------------------------------------------------------%
 
-	% inst_MSG(InstA, InstB, InstC):
-	%       The information in InstC is the minimum of the
-	%       information in InstA and InstB.  Where InstA and
-	%       InstB specify a binding (free or bound), it must be
-	%       the same in both.
-	% 	Round off bindings to different constructors to ground.
-	%	When in doubt, fail. This will only result in less
-	% 	optimization, not loss of correctness.
-
 inst_MSG(InstA, InstB, ModuleInfo, Inst) :-
 	set__init(Expansions),
 	inst_MSG_1(InstA, InstB, Expansions, ModuleInfo, Inst).
@@ -822,8 +792,8 @@
 	( InstA = InstB ->
 		Inst = InstA
 	;
-		% We don't do recursive MSGs (we could,
-		% but it's probably not worth it).
+        % We don't do recursive MSGs
+        % (we could, but it's probably not worth it).
 		\+ set__member(InstA - InstB, Expansions),
 		inst_expand(ModuleInfo, InstA, InstA2),
 		inst_expand(ModuleInfo, InstB, InstB2),
@@ -831,8 +801,7 @@
 		( InstB2 = not_reached ->
 			Inst = InstA2
 		;
-			inst_MSG_2(InstA2, InstB2, Expansions1,
-				ModuleInfo, Inst)
+            inst_MSG_2(InstA2, InstB2, Expansions1, ModuleInfo, Inst)
 		)
 	).
 
@@ -848,7 +817,7 @@
 		ModuleInfo, UniqB, ListB, Inst).
 inst_MSG_2(bound(_, _), ground(UniqB, InfoB), _, _, ground(UniqB, InfoB)).
 
-	% fail here, since the increasing inst size could
+    % Fail here, since the increasing inst size could
 	% cause termination problems for deforestation.
 inst_MSG_2(ground(_, _), bound(_UniqB, _ListB), _, _, _) :- fail.
 inst_MSG_2(ground(_, _), ground(UniqB, InfoB), _, _, ground(UniqB, InfoB)).
@@ -867,6 +836,7 @@
 	inst_list_MSG(ArgsA, ArgsB, Expansions, ModuleInfo, Args).
 
 	% bound_inst_list_MSG(Xs, Ys, ModuleInfo, Zs):
+    %
 	% The two input lists Xs and Ys must already be sorted.
 	% If any of the functors in Xs are not in Ys or vice
 	% versa, the final inst is ground, unless either of the insts
@@ -874,7 +844,7 @@
 	% unique (or non-unique), in which case we fail, since
 	% the msg operation could introduce mode errors.
 	% Otherwise, the take the msg of the argument insts.
-
+    %
 :- pred bound_inst_list_MSG(list(bound_inst)::in, list(bound_inst)::in,
 	expansions::in, module_info::in, uniqueness::in,
 	list(bound_inst)::in, (inst)::out) is semidet.
@@ -905,8 +875,7 @@
 		(
 			Uniq = shared,
 			inst_is_ground(ModuleInfo, bound(shared, List)),
-			inst_is_not_partly_unique(ModuleInfo,
-				bound(shared, List))
+            inst_is_not_partly_unique(ModuleInfo, bound(shared, List))
 		;
 			Uniq = unique,
 			inst_is_unique(ModuleInfo, bound(unique, List))
@@ -952,8 +921,7 @@
 pd_util__bound_inst_size(_, [], _, Size, Size).
 pd_util__bound_inst_size(ModuleInfo, [functor(_, ArgInsts) | Insts],
 		Expansions, Size0, Size) :-
-	pd_util__inst_list_size(ModuleInfo, ArgInsts,
-		Expansions, Size0, Size1),
+    pd_util__inst_list_size(ModuleInfo, ArgInsts, Expansions, Size0, Size1),
 	Size2 = Size1 + 1,
 	pd_util__bound_inst_size(ModuleInfo, Insts, Expansions, Size2, Size).
 
@@ -982,10 +950,8 @@
 	pd_util__goals_match_2(OldGoalList, NewGoalList,
 		OldNewRenaming0, OldNewRenaming),
 
-	%
 	% Check that the goal produces a superset of the outputs of the
 	% version we are searching for.
-	%
 	Search = (pred(K1::in, V1::out) is semidet :-
 			map__search(OldNewRenaming, K1, V1)
 	),
@@ -995,8 +961,7 @@
 	set__delete_list(NewNonLocals, NewArgs, UnmatchedNonLocals),
 	set__empty(UnmatchedNonLocals),
 
-	% Check that argument types of NewGoal are subsumed by
-	% those of OldGoal.
+    % Check that argument types of NewGoal are subsumed by those of OldGoal.
 	pd_util__collect_matching_arg_types(OldArgs, OldArgTypes,
 		OldNewRenaming, [], MatchingArgTypes),
 	map__apply_to_list(NewArgs, NewVarTypes, NewArgTypes),
@@ -1005,31 +970,31 @@
 :- pred pd_util__collect_matching_arg_types(list(prog_var)::in, list(type)::in,
 	map(prog_var, prog_var)::in, list(type)::in, list(type)::out) is det.
 
-pd_util__collect_matching_arg_types([], [], _, Types0, Types) :-
-	list__reverse(Types0, Types).
-pd_util__collect_matching_arg_types([_|_], [], _, _, _) :-
-	error("pd_util__collect_matching_arg_types").
-pd_util__collect_matching_arg_types([], [_|_], _, _, _) :-
-	error("pd_util__collect_matching_arg_types").
+pd_util__collect_matching_arg_types([], [], _, !MatchingTypes) :-
+    list__reverse(!MatchingTypes).
+pd_util__collect_matching_arg_types([_ | _], [], _, !MatchingTypes) :-
+    unexpected(this_file, "pd_util__collect_matching_arg_types").
+pd_util__collect_matching_arg_types([], [_ | _], _, !MatchingTypes) :-
+    unexpected(this_file, "pd_util__collect_matching_arg_types").
 pd_util__collect_matching_arg_types([Arg | Args], [Type | Types],
-		Renaming, MatchingTypes0, MatchingTypes) :-
+        Renaming, !MatchingTypes) :-
 	( map__contains(Renaming, Arg) ->
-		MatchingTypes1 = [Type | MatchingTypes0]
+        !:MatchingTypes = [Type | !.MatchingTypes]
 	;
-		MatchingTypes1 = MatchingTypes0
+        true
 	),
 	pd_util__collect_matching_arg_types(Args, Types,
-		Renaming, MatchingTypes1, MatchingTypes).
+        Renaming, !MatchingTypes).
 
-	% Check that the shape of the goals matches, and that there
-	% is a mapping from the variables in the old goal to the
-	% variables in the new goal.
+    % Check that the shape of the goals matches, and that there is a mapping
+    % from the variables in the old goal to the variables in the new goal.
+    %
 :- pred pd_util__goals_match_2(list(hlds_goal)::in, list(hlds_goal)::in,
 	map(prog_var, prog_var)::in, map(prog_var, prog_var)::out) is semidet.
 
-pd_util__goals_match_2([], [], R, R).
+pd_util__goals_match_2([], [], !ONRenaming).
 pd_util__goals_match_2([OldGoal | OldGoals], [NewGoal | NewGoals],
-		ONRenaming0, ONRenaming) :-
+        !ONRenaming) :-
 	(
 		(
 			OldGoal = unify(_, _, _, OldUnification, _) - _,
@@ -1045,17 +1010,17 @@
 				OldArgs = [OldVar1, OldVar2],
 				NewArgs = [NewVar1, NewVar2]
 			;
-				OldUnification = construct(OldVar, ConsId,
-						OldArgs1, _, _, _, _),
-				NewUnification = construct(NewVar, ConsId,
-						NewArgs1, _, _, _, _),
+                OldUnification = construct(OldVar, ConsId, OldArgs1,
+                    _, _, _, _),
+                NewUnification = construct(NewVar, ConsId, NewArgs1,
+                    _, _, _, _),
 				OldArgs = [OldVar | OldArgs1],
 				NewArgs = [NewVar | NewArgs1]
 			;
-				OldUnification = deconstruct(OldVar, ConsId,
-							OldArgs1, _, _, _),
-				NewUnification = deconstruct(NewVar, ConsId,
-							NewArgs1, _, _, _),
+                OldUnification = deconstruct(OldVar, ConsId, OldArgs1,
+                    _, _, _),
+                NewUnification = deconstruct(NewVar, ConsId, NewArgs1,
+                    _, _, _),
 				OldArgs = [OldVar | OldArgs1],
 				NewArgs = [NewVar | NewArgs1]
 			)
@@ -1063,25 +1028,19 @@
 			OldGoal = call(PredId, ProcId, OldArgs, _, _, _) - _,
 			NewGoal = call(PredId, ProcId, NewArgs, _, _, _) - _
 		;
-			% We don't need to check the modes here -
-			% if the goals match and the insts of the argument
-			% variables match, the modes of the call must
-			% be the same.
-			OldGoal = generic_call(OldGenericCall, OldArgs1,
-					_, Det) - _,
-			NewGoal = generic_call(NewGenericCall, NewArgs1,
-					_, Det) - _,
+            % We don't need to check the modes here - if the goals match
+            % and the insts of the argument variables match, the modes
+            % of the call must be the same.
+            OldGoal = generic_call(OldGenericCall, OldArgs1, _, Det) - _,
+            NewGoal = generic_call(NewGenericCall, NewArgs1, _, Det) - _,
 			match_generic_call(OldGenericCall, NewGenericCall),
-			goal_util__generic_call_vars(OldGenericCall,
-				OldArgs0),
-			goal_util__generic_call_vars(NewGenericCall,
-				NewArgs0),
+            goal_util__generic_call_vars(OldGenericCall, OldArgs0),
+            goal_util__generic_call_vars(NewGenericCall, NewArgs0),
 			list__append(OldArgs0, OldArgs1, OldArgs),
 			list__append(NewArgs0, NewArgs1, NewArgs)
 		)
 	->
-		assoc_list__from_corresponding_lists(OldArgs,
-			NewArgs, ONArgsList),
+        assoc_list__from_corresponding_lists(OldArgs, NewArgs, ONArgsList),
 		MapInsert =
 			(pred(KeyValue::in, Map0::in, Map::out) is semidet :-
 				KeyValue = Key - Value,
@@ -1092,7 +1051,7 @@
 					map__det_insert(Map0, Key, Value, Map)
 				)
 			),
-		list__foldl(MapInsert, ONArgsList, ONRenaming0, ONRenaming1)
+        list__foldl(MapInsert, ONArgsList, !ONRenaming)
 	;
 		(
 			OldGoal = not(OldSubGoal) - _,
@@ -1104,15 +1063,14 @@
 	->
 		goal_to_conj_list(OldSubGoal, OldSubGoalList),
 		goal_to_conj_list(NewSubGoal, NewSubGoalList),
-		pd_util__goals_match_2(OldSubGoalList, NewSubGoalList,
-			ONRenaming0, ONRenaming1)
+        pd_util__goals_match_2(OldSubGoalList, NewSubGoalList, !ONRenaming)
 	;
 		fail
 	),
-	pd_util__goals_match_2(OldGoals, NewGoals,
-		ONRenaming1, ONRenaming).
+    pd_util__goals_match_2(OldGoals, NewGoals, !ONRenaming).
 
 	% Check that two `generic_call' goals are equivalent.
+    %
 :- pred match_generic_call(generic_call::in, generic_call::in) is semidet.
 
 match_generic_call(higher_order(_, Purity, PredOrFunc, Arity),
@@ -1124,6 +1082,7 @@
 	match_aditi_builtin(Builtin1, Builtin2).
 
 	% Check that two `aditi_builtin' goals are equivalent.
+    %
 :- pred match_aditi_builtin(aditi_builtin::in, aditi_builtin::in) is semidet.
 
 	% The other fields are all implied by the pred_proc_id.
@@ -1142,9 +1101,9 @@
 	goal_info_get_determinism(EarlierGoalInfo, EarlierDetism),
 	goal_info_get_determinism(LaterGoalInfo, LaterDetism),
 
-	% Check that the reordering would not violate determinism
-	% correctness by moving a goal out of a single solution context
-	% by placing a goal which can fail after it.
+    % Check that the reordering would not violate determinism correctness
+    % by moving a goal out of a single solution context by placing a goal
+    % which can fail after it.
 	(
 		determinism_components(EarlierDetism, can_fail, _)
 	=>
@@ -1158,19 +1117,14 @@
 	goal_util__reordering_maintains_termination(ModuleInfo, FullyStrict,
 		EarlierGoal, LaterGoal),
 
-	%
-	% Don't reorder the goals if the later goal depends
-	% on the outputs of the current goal.
-	%
+    % Don't reorder the goals if the later goal depends on the outputs
+    % of the current goal.
 	\+ goal_depends_on_goal(EarlierGoal, LaterGoal),
 
-	%
-	% Don't reorder the goals if the later goal changes the
-	% instantiatedness of any of the non-locals of the earlier
-	% goal. This is necessary if the later goal clobbers any
-	% of the non-locals of the earlier goal, and avoids rerunning
-	% full mode analysis in other cases.
-	%
+    % Don't reorder the goals if the later goal changes the instantiatedness
+    % of any of the non-locals of the earlier goal. This is necessary if the
+    % later goal clobbers any of the non-locals of the earlier goal, and
+    % avoids rerunning full mode analysis in other cases.
 	\+ goal_depends_on_goal(LaterGoal, EarlierGoal).
 
 :- pred goal_depends_on_goal(hlds_goal::in, hlds_goal::in) is semidet.
@@ -1183,4 +1137,9 @@
 	\+ set__empty(Intersection).
 
 %-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "pd_util.m".
+
 %-----------------------------------------------------------------------------%
Index: compiler/polymorphism.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/polymorphism.m,v
retrieving revision 1.269
diff -u -b -r1.269 polymorphism.m
--- compiler/polymorphism.m	16 Aug 2005 15:36:18 -0000	1.269
+++ compiler/polymorphism.m	27 Aug 2005 14:54:05 -0000
@@ -1187,7 +1187,7 @@
 			ArgVars, LambdaVars, Modes, Det, LambdaGoal),
                 goal_info_get_nonlocals(GoalInfo0, NonLocals0),
 		set__union(NonLocals0, NonLocalTypeInfos, NonLocals),
-		goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+		goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
 
 		%
 		% Complicated (in-in) argument unifications are impossible
@@ -1244,7 +1244,7 @@
 	%
 	goal_info_get_nonlocals(!.GoalInfo, NonLocals0),
 	set__insert_list(NonLocals0, TypeInfoVars, NonLocals),
-	goal_info_set_nonlocals(!.GoalInfo, NonLocals, !:GoalInfo),
+	goal_info_set_nonlocals(NonLocals, !GoalInfo),
 
 	%
 	% Also save those type_info vars into a field in the complicated_unify,
@@ -1362,7 +1362,7 @@
 		list__append(ExtraVars, ArgVars0, ArgVars),
 		goal_info_get_nonlocals(GoalInfo0, NonLocals0),
 		set__insert_list(NonLocals0, ExtraVars, NonLocals),
-		goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo1),
+		goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo1),
 
 		%
 		% Some of the argument unifications may be complicated
@@ -1425,13 +1425,13 @@
 	set__intersect(OutsideVars, InsideVars, LambdaNonLocals),
 	goal_info_get_goal_path(GoalInfo0, GoalPath),
 	goal_info_init(LambdaGoalInfo0),
-	goal_info_set_context(LambdaGoalInfo0, Context,
-		LambdaGoalInfo1),
-	goal_info_set_nonlocals(LambdaGoalInfo1, LambdaNonLocals,
-		LambdaGoalInfo2),
-	add_goal_info_purity_feature(LambdaGoalInfo2, Purity,
-		LambdaGoalInfo3),
-	goal_info_set_goal_path(LambdaGoalInfo3, GoalPath, LambdaGoalInfo),
+	goal_info_set_context(Context,
+		LambdaGoalInfo0, LambdaGoalInfo1),
+	goal_info_set_nonlocals(LambdaNonLocals,
+		LambdaGoalInfo1, LambdaGoalInfo2),
+	add_goal_info_purity_feature(Purity,
+		LambdaGoalInfo2, LambdaGoalInfo3),
+	goal_info_set_goal_path(GoalPath, LambdaGoalInfo3, LambdaGoalInfo),
 	LambdaGoal = LambdaGoalExpr - LambdaGoalInfo,
 
 	%
@@ -1447,9 +1447,11 @@
 		error("convert_pred_to_lambda_goal: list__drop failed")
 	),
 	proc_info_declared_determinism(ProcInfo, MaybeDet),
-	( MaybeDet = yes(Det) ->
+	(
+		MaybeDet = yes(Det),
 		LambdaDet = Det
 	;
+		MaybeDet = no,
 		error("Sorry, not implemented: determinism inference " ++
 			"for higher-order predicate terms")
 	),
@@ -1912,7 +1914,7 @@
 		%
 		goal_info_get_nonlocals(GoalInfo0, NonLocals0),
 		set__insert_list(NonLocals0, ExtraVars, NonLocals),
-		goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo)
+		goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo)
 	).
 
 %-----------------------------------------------------------------------------%
@@ -1972,7 +1974,7 @@
 	goal_info_get_nonlocals(GoalInfo0, NonLocals0),
 	NonLocals1 = set__list_to_set(ExtraArgs),
 	NonLocals = set__union(NonLocals0, NonLocals1),
-	goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+	goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
 	CallGoalExpr = call(PredId, ProcId, CallArgs, BuiltinState,
 		MaybeCallUnifyContext, SymName),
 	CallGoal = CallGoalExpr - GoalInfo,
@@ -2461,7 +2463,7 @@
 	% create a goal_info for the unification
 	goal_info_init(GoalInfo0),
 	set__list_to_set([NewVar | NewArgVars], TheNonLocals),
-	goal_info_set_nonlocals(GoalInfo0, TheNonLocals, GoalInfo1),
+	goal_info_set_nonlocals(TheNonLocals, GoalInfo0, GoalInfo1),
 	list__duplicate(NumArgVars, ground(shared, none), ArgInsts),
 		% note that we could perhaps be more accurate than
 		% `ground(shared)', but it shouldn't make any
@@ -2470,8 +2472,8 @@
 	instmap_delta_from_assoc_list(
 		[NewVar - bound(unique, [functor(InstConsId, ArgInsts)])],
 		InstMapDelta),
-	goal_info_set_instmap_delta(GoalInfo1, InstMapDelta, GoalInfo2),
-	goal_info_set_determinism(GoalInfo2, det, GoalInfo),
+	goal_info_set_instmap_delta(InstMapDelta, GoalInfo1, GoalInfo2),
+	goal_info_set_determinism(det, GoalInfo2, GoalInfo),
 
 	TypeClassInfoGoal = Unify - GoalInfo,
 	NewGoals0 = [TypeClassInfoGoal, BaseGoal],
Index: compiler/post_typecheck.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/post_typecheck.m,v
retrieving revision 1.76
diff -u -b -r1.76 post_typecheck.m
--- compiler/post_typecheck.m	27 Aug 2005 09:41:58 -0000	1.76
+++ compiler/post_typecheck.m	27 Aug 2005 13:58:31 -0000
@@ -1636,7 +1636,7 @@
 	% Compute the nonlocals of the goal.
 	set__list_to_set(VarsList, NonLocals1),
 	set__intersect(RestrictNonLocals, NonLocals1, NonLocals),
-	goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+	goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
 	Goal = GoalExpr0 - GoalInfo.
 
 :- pred make_new_vars(list(type)::in, list(prog_var)::out,
Index: compiler/purity.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/purity.m,v
retrieving revision 1.76
diff -u -b -r1.76 purity.m
--- compiler/purity.m	12 Aug 2005 05:14:15 -0000	1.76
+++ compiler/purity.m	27 Aug 2005 14:03:58 -0000
@@ -6,11 +6,10 @@
 % Public License - see the file COPYING in the Mercury distribution.
 %-----------------------------------------------------------------------------%
 %
-% File      : purity.m
-% Authors   : scachte (Peter Schachte)
-%       (main author and designer of purity system)
+% File:     purity.m
+% Authors:  scachte (Peter Schachte, main author and designer of purity system)
 %         trd (modifications for impure functions)
-% Purpose   : handle `impure' and `promise_pure' declarations;
+% Purpose:  handle `impure' and `promise_pure' declarations;
 %         finish off type checking.
 %
 % The main purpose of this module is check the consistency of the
@@ -249,16 +248,15 @@
 %-----------------------------------------------------------------------------%
 
     % Purity-check the code for all the predicates in a module.
-
+    %
 :- pred check_preds_purity(bool::in, bool::out,
     module_info::in, module_info::out, io::di, io::uo) is det.
 
 check_preds_purity(FoundTypeError, PostTypecheckError, !ModuleInfo, !IO) :-
     module_info_predids(!.ModuleInfo, PredIds),
 
-    % Only report error messages for unbound type variables
-    % if we didn't get any type errors already; this avoids
-    % a lot of spurious diagnostics.
+    % Only report error messages for unbound type variables if we didn't get
+    % any type errors already; this avoids a lot of spurious diagnostics.
     ReportTypeErrors = bool__not(FoundTypeError),
     post_typecheck__finish_preds(PredIds, ReportTypeErrors, NumErrors1,
         PostTypecheckError, !ModuleInfo, !IO),
@@ -299,8 +297,6 @@
     ),
     check_preds_purity_2(PredIds, !ModuleInfo, !NumErrors, !IO).
 
-    % Purity-check the code for single predicate, reporting any errors.
-
 %-----------------------------------------------------------------------------%
 %
 % Check purity of a single predicate
@@ -446,15 +442,15 @@
         true
     ).
 
-% Infer the purity of a single (non-pragma c_code) predicate
-
+    % Infer the purity of a single (non-pragma c_code) predicate.
+    %
 :- pred compute_purity(goal_type::in, list(clause)::in, list(clause)::out,
     list(proc_id)::in, purity::in, purity::out,
     purity_info::in, purity_info::out) is det.
 
-compute_purity(_, [], [], _, Purity, Purity, !Info).
+compute_purity(_, [], [], _, !Purity, !Info).
 compute_purity(GoalType, [Clause0 | Clauses0], [Clause | Clauses], ProcIds,
-        Purity0, Purity, !Info) :-
+        !Purity, !Info) :-
     Clause0 = clause(Ids, Body0 - Info0, Lang, Context),
     compute_expr_purity(Body0, Body, Info0, Bodypurity0, !Info),
     % If this clause doesn't apply to all modes of this procedure,
@@ -473,11 +469,10 @@
         Clausepurity = (impure)
     ),
     worst_purity(Bodypurity0, Clausepurity) = Bodypurity,
-    add_goal_info_purity_feature(Info0, Bodypurity, Info),
-    worst_purity(Purity0, Bodypurity) = Purity1,
+    add_goal_info_purity_feature(Bodypurity, Info0, Info),
+    !:Purity = worst_purity(!.Purity, Bodypurity),
     Clause = clause(Ids, Body - Info, Lang, Context),
-    compute_purity(GoalType, Clauses0, Clauses, ProcIds, Purity1, Purity,
-        !Info).
+    compute_purity(GoalType, Clauses0, Clauses, ProcIds, !Purity, !Info).
 
 :- pred applies_to_all_modes(clause::in, list(proc_id)::in) is semidet.
 
@@ -713,7 +708,7 @@
     ).
 
 compute_expr_purity(shorthand(_), _, _, _, !Info) :-
-    % these should have been expanded out by now
+    % These should have been expanded out by now.
     error("compute_expr_purity: unexpected shorthand").
 
 :- pred check_higher_order_purity(hlds_goal_info::in, cons_id::in,
@@ -740,20 +735,16 @@
         CallerPredInfo = !.Info ^ pred_info,
         pred_info_get_markers(CallerPredInfo, CallerMarkers),
         (
-            get_pred_id(calls_are_fully_qualified(CallerMarkers),
-                PName, PredOrFunc, TVarSet, PredArgTypes,
-                ModuleInfo, CalleePredId)
+            get_pred_id(calls_are_fully_qualified(CallerMarkers), PName,
+                PredOrFunc, TVarSet, PredArgTypes, ModuleInfo, CalleePredId)
         ->
-            module_info_pred_info(ModuleInfo,
-                CalleePredId, CalleePredInfo),
+            module_info_pred_info(ModuleInfo, CalleePredId, CalleePredInfo),
             pred_info_get_purity(CalleePredInfo, CalleePurity),
-            check_closure_purity(GoalInfo, TypePurity,
-                CalleePurity, !Info)
+            check_closure_purity(GoalInfo, TypePurity, CalleePurity, !Info)
         ;
-            % If we can't find the type of the function,
-            % it's because typecheck couldn't give it one.
-            % Typechecking gives an error in this case, we
-            % just keep silent.
+            % If we can't find the type of the function, it's because
+            % typecheck couldn't give it one. Typechecking gives an error
+            % in this case, we just keep silent.
             true
         )
     ;
@@ -764,7 +755,7 @@
     % even if it is a unification with an impure higher-order term.
     ActualPurity = pure,
 
-    % Check for a bogus purity annotation on the unification
+    % Check for a bogus purity annotation on the unification.
     infer_goal_info_purity(GoalInfo, DeclaredPurity),
     (
         DeclaredPurity \= pure,
@@ -777,7 +768,7 @@
         true
     ).
 
-    % the possible results of a purity check
+    % The possible results of a purity check.
 :- type purity_check_result
     --->    no_worries                  % All is well.
     ;       insufficient_decl           % Purity decl is less than
@@ -810,10 +801,9 @@
     ->
         PurityCheckResult = inconsistent_promise
     ;
-        % You shouldn't promise pure unnecessarily.
-        % It's OK in the case of foreign_procs though.
-        % There is also no point in warning about compiler-generated
-        % predicates.
+        % You shouldn't promise pure unnecessarily. It's OK in the case
+        % of foreign_procs though. There is also no point in warning about
+        % compiler-generated predicates.
         PromisedPurity \= (impure),
         ActualPurity = PromisedPurity,
         not pred_info_pragma_goal_type(PredInfo),
@@ -835,19 +825,16 @@
             PurityCheckResult = no_worries
         )
     ;
-        % We don't warn about exaggerated impurity decls in
-        % class methods or instance methods --- it just
-        % means that the predicate provided as an
-        % implementation was more pure than necessary.
-        %
-        % We don't warn about exaggerated impurity
-        % decls in c_code -- this is just because we
-        % assume they are pure, but you can declare them
+        % We don't warn about exaggerated impurity decls in class methods
+        % or instance methods --- it just means that the predicate provided
+        % as an implementation was more pure than necessary.
+        %
+        % We don't warn about exaggerated impurity decls in c_code -- this is
+        % just because we assume they are pure, but you can declare them
         % to be impure.
         %
-        % We don't warn about exaggerated impurity declarations
-        % for "stub" procedures, i.e. procedures which
-        % originally had no clauses.
+        % We don't warn about exaggerated impurity declarations for "stub"
+        % procedures, i.e. procedures which originally had no clauses.
 
         pred_info_get_markers(PredInfo, Markers),
         pred_info_get_goal_type(PredInfo, GoalType),
@@ -873,6 +860,7 @@
     %
     % ActualPurity: The inferred purity of the goal
     % DeclaredPurity: The declared purity of the goal
+    %
 :- pred perform_goal_purity_checks(prog_context::in, pred_id::in, purity::in,
     purity::out, purity_info::in, purity_info::out) is det.
 
@@ -891,7 +879,7 @@
         true
     ;
         % The purity of the callee should match the
-        % purity declared at the call
+        % purity declared at the call.
         ActualPurity = DeclaredPurity
     ->
         true
@@ -907,10 +895,9 @@
         purity_info_add_message(
             error(missing_body_impurity_error(Context, PredId)), !Info)
     ;
-        % We don't warn about exaggerated impurity decls in
-        % class methods or instance methods --- it just
-        % means that the predicate provided as an
-        % implementation was more pure than necessary.
+        % We don't warn about exaggerated impurity decls in class methods
+        % or instance methods --- it just means that the predicate provided
+        % as an implementation was more pure than necessary.
 
         pred_info_get_markers(PredInfo, Markers),
         (
@@ -932,12 +919,12 @@
 
 compute_goal_purity(Goal0 - GoalInfo0, Goal - GoalInfo, Purity, !Info) :-
     compute_expr_purity(Goal0, Goal, GoalInfo0, Purity, !Info),
-    add_goal_info_purity_feature(GoalInfo0, Purity, GoalInfo).
+    add_goal_info_purity_feature(Purity, GoalInfo0, GoalInfo).
 
     % Compute the purity of a list of hlds_goals.  Since the purity of a
     % disjunction is computed the same way as the purity of a conjunction,
     % we use the same code for both
-
+    %
 :- pred compute_goals_purity(list(hlds_goal)::in, list(hlds_goal)::out,
     purity::in, purity::out, purity_info::in, purity_info::out) is det.
 
@@ -959,6 +946,7 @@
 
     % Make sure lambda expressions introduced by the compiler
     % have the correct mode for their `aditi__state' arguments.
+    %
 :- pred fix_aditi_state_modes(bool::in, (mode)::in, list(type)::in,
     list(mode)::in, list(mode)::out) is det.
 
@@ -972,11 +960,9 @@
     ( type_is_aditi_state(Type) ->
         (
             SeenState0 = yes,
-            % The only Aditi builtin which takes a closure
-            % with two `aditi__state' arguments is
-            % `aditi_bulk_modify'.
-            % The second `aditi__state' argument has mode
-            % unused.
+            % The only Aditi builtin which takes a closure with two
+            % `aditi__state' arguments is `aditi_bulk_modify'.
+            % The second `aditi__state' argument has mode unused.
             unused_mode(ArgMode)
         ;
             SeenState0 = no,
Index: compiler/quantification.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/quantification.m,v
retrieving revision 1.93
diff -u -b -r1.93 quantification.m
--- compiler/quantification.m	26 Jul 2005 01:56:25 -0000	1.93
+++ compiler/quantification.m	28 Aug 2005 00:19:08 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1994-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -40,22 +42,19 @@
 :- import_module list.
 :- import_module set.
 
-	% When the compiler performs structure reuse, using
-	% the ordinary non-locals during code generation
-	% causes variables taken from the reused cell in
-	% a reconstruction to be extracted and possibly stored
-	% on the stack unnecessarily.
-	%
-	% For the example below, the variables `B' ... `H' are
-	% extracted from the term and stored on the stack across
-	% the call.
+    % When the compiler performs structure reuse, using the ordinary non-locals
+    % during code generation causes variables taken from the reused cell in
+    % a reconstruction to be extracted and possibly stored on the stack
+    % unnecessarily.
+    %
+    % For the example below, the variables `B' ... `H' are extracted
+    % from the term and stored on the stack across the call.
 	%
 	% To avoid this, the compiler computes a set of `code-gen non-locals'
-	% which are the same as the ordinary non-locals, except that the
-	% variables taken from the reused cell are considered to be local
-	% to the goal. No renaming is performed when computing
-	% the code-gen non-locals to avoid stuffing up the ordinary
-	% non-locals.
+    % which are the same as the ordinary non-locals, except that the variables
+    % taken from the reused cell are considered to be local to the goal.
+    % No renaming is performed when computing the code-gen non-locals
+    % to avoid stuffing up the ordinary non-locals.
 	%
 	% Mode information is always computed using the ordinary non-locals.
 	%
@@ -105,8 +104,11 @@
 :- type quant_warning
 	--->	warn_overlap(list(prog_var), prog_context).
 
-	% quantification__goal_vars(Goal, Vars):
-	% Vars is the set of variables that are free (unquantified) in Goal.
+    % quantification__goal_vars(NonLocalsToRecompute, Goal, Vars):
+    %
+    % Vars is the set of variables that occur free (unquantified)
+    % in Goal, excluding unset fields of reconstructions if
+    % NonLocalsToRecompute is `code_gen_nonlocals'.
 	%
 :- pred quantification__goal_vars(nonlocals_to_recompute::in,
 	hlds_goal::in, set(prog_var)::out) is det.
@@ -121,6 +123,7 @@
 
 :- import_module hlds__goal_util.
 :- import_module hlds__instmap.
+:- import_module parse_tree__error_util.
 
 :- import_module bool.
 :- import_module enum.
@@ -151,13 +154,12 @@
 			warnings		:: list(quant_warning)
 		).
 
-	% Until we have user-specified pretty printing in the
-	% debugger, debugging will be much easier if set_of_var
-	% is just `set(prog_var)'.
-	% None of the calls to the predicates and functions operating
-	% on sets in this module are module qualified so we can switch
-	% representation just by changing this line.
-%:- type set_of_var == set(prog_var).
+    % Until we have user-specified pretty printing in the debugger,
+    % debugging will be much easier if set_of_var is just `set(prog_var)'.
+    % None of the calls to the predicates and functions operating on sets
+    % in this module are module qualified so we can switch representation
+    % just by changing this line.
+% :- type set_of_var == set(prog_var).
 :- type set_of_var == sparse_bitset(prog_var).
 
 	% `OutsideVars' are the variables that have occurred free outside
@@ -226,9 +228,8 @@
 	(
 		RecomputeNonLocals = code_gen_nonlocals,
 
-		% If the goal does not contain a reconstruction,
-		% the code-gen nonlocals and the ordinary non-locals
-		% are the same.
+        % If the goal does not contain a reconstruction, the code-gen nonlocals
+        % and the ordinary non-locals are the same.
 		goal_contains_reconstruction(!.Goal)
 	->
 		implicitly_quantify_goal_2(code_gen_nonlocals, OutsideVars, _,
@@ -261,8 +262,7 @@
 	goal_info_get_context(GoalInfo0, Context),
 	implicitly_quantify_goal_2(Goal0, Goal1, Context, !Info),
 	quantification__get_nonlocals(NonLocalVars, !Info),
-	quantification__get_nonlocals_to_recompute(NonLocalsToRecompute,
-		!Info),
+    quantification__get_nonlocals_to_recompute(NonLocalsToRecompute, !Info),
 	(
 		% If there are any variables that are local to the goal
 		% which we have come across before, then we rename them apart.
@@ -287,8 +287,8 @@
 	% then we may need to likewise shrink the instmap delta.
 	%
 	goal_info_get_instmap_delta(GoalInfo2, InstMapDelta0),
-	instmap_delta_restrict(InstMapDelta0, NonLocalVarsSet, InstMapDelta),
-	goal_info_set_instmap_delta(GoalInfo2, InstMapDelta, GoalInfo).
+    instmap_delta_restrict(NonLocalVarsSet, InstMapDelta0, InstMapDelta),
+    goal_info_set_instmap_delta(InstMapDelta, GoalInfo2, GoalInfo).
 
 :- pred implicitly_quantify_goal_2(hlds_goal_expr::in, hlds_goal_expr::out,
 	prog_context::in, quant_info::in, quant_info::out) is det.
@@ -332,8 +332,7 @@
 	quantification__get_outside(OutsideVars, !Info),
 	quantification__get_lambda_outside(LambdaOutsideVars, !Info),
 	quantification__get_quant_vars(QuantVars, !Info),
-		% Rename apart all the quantified variables that
-		% occur outside this goal.
+    % Rename apart all the quantified variables that occur outside this goal.
 	list_to_set(Vars0, QVars),
 	intersect(OutsideVars, QVars, RenameVars1),
 	intersect(LambdaOutsideVars, QVars, RenameVars2),
@@ -343,11 +342,10 @@
 		Vars = Vars0,
 		Reason = Reason1
 	;
-		quantification__warn_overlapping_scope(RenameVars, Context,
+        quantification__warn_overlapping_scope(RenameVars, Context, !Info),
+        quantification__rename_apart(RenameVars, RenameMap, Goal0, Goal1,
 			!Info),
-		quantification__rename_apart(RenameVars, RenameMap,
-			Goal0, Goal1, !Info),
-		goal_util__rename_var_list(Vars0, no, RenameMap, Vars),
+        goal_util__rename_var_list(no, RenameMap, Vars0, Vars),
 		(
 			Reason1 = exist_quant(_),
 			% We have already handled this case.
@@ -357,8 +355,8 @@
 			Reason = Reason1
 		;
 			Reason1 = promise_equivalent_solutions(PromiseVars0),
-			goal_util__rename_var_list(PromiseVars0, no, RenameMap,
-				PromiseVars),
+            goal_util__rename_var_list(no, RenameMap,
+                PromiseVars0, PromiseVars),
 			Reason = promise_equivalent_solutions(PromiseVars)
 		;
 			Reason1 = commit(_),
@@ -399,9 +397,8 @@
 implicitly_quantify_goal_2(Expr0, Expr, _, !Info) :-
 	Expr0 = switch(Var, Det, Cases0),
 	implicitly_quantify_cases(Cases0, Cases, !Info),
-		% The switch variable is guaranteed to be non-local to the
-		% switch, since it has to be bound elsewhere, so we put it
-		% in the nonlocals here.
+    % The switch variable is guaranteed to be non-local to the switch, since
+    % it has to be bound elsewhere, so we put it in the nonlocals here.
 	quantification__get_nonlocals(NonLocals0, !Info),
 	insert(NonLocals0, Var, NonLocals),
 	quantification__set_nonlocals(NonLocals, !Info),
@@ -409,10 +406,10 @@
 
 implicitly_quantify_goal_2(Expr0, Expr, _, !Info) :-
 	Expr0 = not(Goal0),
-		% quantified variables cannot be pushed inside a negation,
-		% so we insert the quantified vars into the outside vars set,
-		% and initialize the new quantified vars set to be empty
-		% (the lambda outside vars remain unchanged)
+    % Quantified variables cannot be pushed inside a negation, so we insert
+    % the quantified vars into the outside vars set, and initialize the new
+    % quantified vars set to be empty (the lambda outside vars remain
+    % unchanged).
 	quantification__get_quant_vars(QuantVars, !Info),
 	quantification__get_outside(OutsideVars, !Info),
 	union(OutsideVars, QuantVars, OutsideVars1),
@@ -424,10 +421,9 @@
 	quantification__set_outside(OutsideVars, !Info),
 	quantification__set_quant_vars(QuantVars, !Info).
 
-	% After this pass, explicit quantifiers are redundant,
-	% since all variables which were explicitly quantified
-	% have been renamed apart.  So we don't keep them.
-	% Thus we replace `if_then_else(Vars, ....)' with
+    % After this pass, explicit quantifiers are redundant, since all variables
+    % which were explicitly quantified have been renamed apart. So we don't
+    % keep them. Thus we replace `if_then_else(Vars, ....)' with
 	% `if_then_else([], ...)'.
 implicitly_quantify_goal_2(Expr0, Expr, Context, !Info) :-
 	Expr0 = if_then_else(Vars0, Cond0, Then0, Else0),
@@ -435,10 +431,8 @@
 	quantification__get_outside(OutsideVars, !Info),
 	quantification__get_lambda_outside(LambdaOutsideVars, !Info),
 	list_to_set(Vars0, QVars),
-		% Rename apart those variables that
-		% are quantified to the cond and then
-		% of the i-t-e that occur outside the
-		% i-t-e.
+    % Rename apart those variables that are quantified to the cond and then
+    % of the i-t-e that occur outside the i-t-e.
 	intersect(OutsideVars, QVars, RenameVars1),
 	intersect(LambdaOutsideVars, QVars, RenameVars2),
 	union(RenameVars1, RenameVars2, RenameVars),
@@ -447,18 +441,16 @@
 		Then1 = Then0,
 		Vars = Vars0
 	;
-		quantification__warn_overlapping_scope(RenameVars, Context,
+        quantification__warn_overlapping_scope(RenameVars, Context, !Info),
+        quantification__rename_apart(RenameVars, RenameMap, Cond0, Cond1,
 			!Info),
-		quantification__rename_apart(RenameVars, RenameMap,
-			Cond0, Cond1, !Info),
-		goal_util__rename_vars_in_goal(Then0, RenameMap, Then1),
-		goal_util__rename_var_list(Vars0, no, RenameMap, Vars)
+        goal_util__rename_vars_in_goal(RenameMap, Then0, Then1),
+        goal_util__rename_var_list(no, RenameMap, Vars0, Vars)
 	),
 	insert_list(QuantVars, Vars, QuantVars1),
-	quantification__get_nonlocals_to_recompute(NonLocalsToRecompute,
-		!Info),
-	quantification__goal_vars(NonLocalsToRecompute,
-		Then1, VarsThen, LambdaVarsThen),
+    quantification__get_nonlocals_to_recompute(NonLocalsToRecompute, !Info),
+    quantification__goal_vars(NonLocalsToRecompute, Then1, VarsThen,
+        LambdaVarsThen),
 	union(OutsideVars, VarsThen, OutsideVars1),
 	union(LambdaOutsideVars, LambdaVarsThen, LambdaOutsideVars1),
 	quantification__set_quant_vars(QuantVars1, !Info),
@@ -524,14 +516,18 @@
 	quantification__get_nonlocals(VarsUnifyRHS, !Info),
 	insert(VarsUnifyRHS, Var, GoalVars0),
 	insert_list(GoalVars0, TypeInfoVars, GoalVars1),
-	( MaybeReuseVar = yes(ReuseVar) ->
+    (
+        MaybeReuseVar = yes(ReuseVar),
 		insert(GoalVars1, ReuseVar, GoalVars2)
 	;
+        MaybeReuseVar = no,
 		GoalVars2 = GoalVars1
 	),
-	( MaybeSizeVar = yes(SizeVar) ->
+    (
+        MaybeSizeVar = yes(SizeVar),
 		insert(GoalVars2, SizeVar, GoalVars)
 	;
+        MaybeSizeVar = no,
 		GoalVars = GoalVars2
 	),
 	quantification__update_seen_vars(GoalVars, !Info),
@@ -549,8 +545,7 @@
 
 implicitly_quantify_goal_2(Expr0, Expr, Context, !Info) :-
 	Expr0 = shorthand(ShorthandGoal),
-	implicitly_quantify_goal_2_shorthand(ShorthandGoal, Context, Expr,
-		!Info).
+    implicitly_quantify_goal_2_shorthand(ShorthandGoal, Context, Expr, !Info).
 
 :- pred implicitly_quantify_goal_2_shorthand(shorthand_goal_expr::in,
 	prog_context::in, hlds_goal_expr::out,
@@ -559,65 +554,62 @@
 implicitly_quantify_goal_2_shorthand(bi_implication(LHS0, RHS0), Context, Goal,
 		!Info) :-
 
-		% get the initial values of various settings
+    % Get the initial values of various settings.
 	quantification__get_quant_vars(QuantVars0, !Info),
 	quantification__get_outside(OutsideVars0, !Info),
 	quantification__get_lambda_outside(LambdaOutsideVars0, !Info),
 
-		% quantified variables cannot be pushed inside a negation,
-		% so we insert the quantified vars into the outside vars set,
-		% and initialize the new quantified vars set to be empty
-		% (the lambda outside vars remain unchanged)
+    % Quantified variables cannot be pushed inside a negation, so we insert
+    % the quantified vars into the outside vars set, and initialize the new
+    % quantified vars set to be empty (the lambda outside vars remain
+    % unchanged).
 	union(OutsideVars0, QuantVars0, OutsideVars1),
 	init(QuantVars1),
 	LambdaOutsideVars1 = LambdaOutsideVars0,
 	quantification__set_quant_vars(QuantVars1, !Info),
 
-		% prepare for quantifying the LHS:
-		% add variables from the RHS to the outside vars
-		% and the outside lambda vars sets.
+    % Prepare for quantifying the LHS: add variables from the RHS to the
+    % outside vars and the outside lambda vars sets.
 	quantification__get_nonlocals_to_recompute(NonLocalsToRecompute, !Info),
 	quantification__goal_vars(NonLocalsToRecompute, RHS0, RHS_Vars,
 		RHS_LambdaVars),
 	union(OutsideVars1, RHS_Vars, LHS_OutsideVars),
 	union(LambdaOutsideVars1, RHS_LambdaVars, LHS_LambdaOutsideVars),
 
-		% quantify the LHS
+    % Quantify the LHS.
 	quantification__set_outside(LHS_OutsideVars, !Info),
 	quantification__set_lambda_outside(LHS_LambdaOutsideVars, !Info),
 	implicitly_quantify_goal(LHS0, LHS, !Info),
 	quantification__get_nonlocals(LHS_NonLocalVars, !Info),
 
-		% prepare for quantifying the RHS:
-		% add nonlocals from the LHS to the outside vars.
-		% (We use the nonlocals rather than the more symmetric
-		% approach of calling quantification__goal_vars on the
-		% LHS goal because it is more efficient.)
+    % Prepare for quantifying the RHS: add nonlocals from the LHS to the
+    % outside vars. (We use the nonlocals rather than the more symmetric
+    % approach of calling quantification__goal_vars on the LHS goal
+    % because it is more efficient.)
 	union(OutsideVars1, LHS_NonLocalVars, RHS_OutsideVars),
 	RHS_LambdaOutsideVars = LambdaOutsideVars1,
 
-		% quantify the RHS
+    % Quantify the RHS.
 	quantification__set_outside(RHS_OutsideVars, !Info),
 	quantification__set_lambda_outside(RHS_LambdaOutsideVars, !Info),
 	implicitly_quantify_goal(RHS0, RHS, !Info),
 	quantification__get_nonlocals(RHS_NonLocalVars, !Info),
 
-		% compute the nonlocals for this goal
+    % Compute the nonlocals for this goal.
 	union(LHS_NonLocalVars, RHS_NonLocalVars, AllNonLocalVars),
 	intersect(AllNonLocalVars, OutsideVars0, NonLocalVarsO),
 	intersect(AllNonLocalVars, LambdaOutsideVars0, NonLocalVarsL),
 	union(NonLocalVarsO, NonLocalVarsL, NonLocalVars),
 	quantification__set_nonlocals(NonLocalVars, !Info),
 
-		% restore the original values of various settings
+    % Restore the original values of various settings.
 	quantification__set_outside(OutsideVars0, !Info),
 	quantification__set_lambda_outside(LambdaOutsideVars0, !Info),
 	quantification__set_quant_vars(QuantVars0, !Info),
 
 		%
 		% We've figured out the quantification.
-		% Now expand the bi-implication according to the usual
-		% rules:
+    % Now expand the bi-implication according to the usual rules:
 		%	LHS <=> RHS
 		% ===>
 		%	(LHS => RHS), (RHS => LHS)
@@ -625,21 +617,17 @@
 		%	(not (LHS, not RHS)), (not (RHS, not LHS))
 		%
 	goal_info_init(GoalInfo0),
-	goal_info_set_context(GoalInfo0, Context, GoalInfo1),
-	quantification__set_goal_nonlocals(LHS_NonLocalVars,
-		GoalInfo1, LHS_GI, !Info),
-	quantification__set_goal_nonlocals(RHS_NonLocalVars,
-		GoalInfo1, RHS_GI, !Info),
-	quantification__set_goal_nonlocals(NonLocalVars,
-		GoalInfo1, GI, !Info),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo1),
+    quantification__set_goal_nonlocals(LHS_NonLocalVars, GoalInfo1, LHS_GI,
+        !Info),
+    quantification__set_goal_nonlocals(RHS_NonLocalVars, GoalInfo1, RHS_GI,
+        !Info),
+    quantification__set_goal_nonlocals(NonLocalVars, GoalInfo1, GI, !Info),
 	NotLHS = not(LHS) - LHS_GI,
 	NotRHS = not(RHS) - RHS_GI,
 	ForwardsImplication = not(conj([LHS, NotRHS]) - GI) - GI,
 
-		%
-		% Rename apart the local variables of the goals
-		% we've just duplicated.
-		%
+    % Rename apart the local variables of the goals we've just duplicated.
 	ReverseImplication0 = not(conj([RHS, NotLHS]) - GI) - GI,
 	quantification__goal_vars_bitset(NonLocalsToRecompute,
 		ReverseImplication0, GoalVars),
@@ -672,8 +660,7 @@
 	quantification__set_nonlocals(Vars, !Info).
 implicitly_quantify_unify_rhs(ReuseArgs, _, !RHS, !Unification, !Info) :-
 	!.RHS = functor(_, _, ArgVars),
-	quantification__get_nonlocals_to_recompute(NonLocalsToRecompute,
-		!Info),
+    quantification__get_nonlocals_to_recompute(NonLocalsToRecompute, !Info),
 	(
 		NonLocalsToRecompute = code_gen_nonlocals,
 		ReuseArgs = yes(SetArgs)
@@ -699,25 +686,22 @@
 	%
 	quantification__get_outside(OutsideVars0, !Info),
 	list_to_set(LambdaVars0, QVars),
-		% Figure out which variables have overlapping scopes because
-		% they occur outside the goal and are also lambda-quantified
-		% vars.
+    % Figure out which variables have overlapping scopes because they occur
+    % outside the goal and are also lambda-quantified vars.
 	intersect(OutsideVars0, QVars, RenameVars0),
 	( empty(RenameVars0) ->
 		true
 	;
-		quantification__warn_overlapping_scope(RenameVars0, Context,
-			!Info)
+        quantification__warn_overlapping_scope(RenameVars0, Context, !Info)
 	),
-		% We need to rename apart any of the lambda vars that
-		% we have already seen, since they are new instances.
+    % We need to rename apart any of the lambda vars that we have already seen,
+    % since they are new instances.
 	quantification__get_seen(Seen0, !Info),
 	intersect(Seen0, QVars, RenameVars1),
 
 	union(RenameVars0, RenameVars1, RenameVars),
-	quantification__rename_apart(RenameVars, RenameMap, Goal0, Goal1,
-		!Info),
-	goal_util__rename_var_list(LambdaVars0, no, RenameMap, LambdaVars),
+    quantification__rename_apart(RenameVars, RenameMap, Goal0, Goal1, !Info),
+    goal_util__rename_var_list(no, RenameMap, LambdaVars0, LambdaVars),
 
 		% Quantified variables cannot be pushed inside a lambda goal,
 		% so we insert the quantified vars into the outside vars set,
@@ -730,17 +714,16 @@
 		% outside of the lambda goal
 	insert_list(OutsideVars1, LambdaVars, OutsideVars),
 	quantification__set_outside(OutsideVars, !Info),
-		% Set the LambdaOutsideVars set to empty, because
-		% variables that occur outside this lambda expression
-		% only in other lambda expressions should not be
-		% considered non-local.
+    % Set the LambdaOutsideVars set to empty, because variables that occur
+    % outside this lambda expression only in other lambda expressions
+    % should not be considered non-local.
 	quantification__get_lambda_outside(LambdaOutsideVars0, !Info),
 	init(LambdaOutsideVars),
 	quantification__set_lambda_outside(LambdaOutsideVars, !Info),
 	implicitly_quantify_goal(Goal1, Goal, !Info),
 
 	quantification__get_nonlocals(NonLocals0, !Info),
-		% lambda-quantified variables are local
+    % Lambda-quantified variables are local.
 	delete_list(NonLocals0, LambdaVars, NonLocals),
 	quantification__set_quant_vars(QuantVars0, !Info),
 	quantification__set_outside(OutsideVars0, !Info),
@@ -778,10 +761,9 @@
 		!:Unification = construct(ConstructVar, ConsId, Args,
 			ArgModes, HowToConstruct, Uniq, Size)
 	;
-		% after mode analysis, unifications with lambda variables
-		% should always be construction unifications, but
-		% quantification gets invoked before mode analysis,
-		% so we need to allow this case...
+        % After mode analysis, unifications with lambda variables should always
+        % be construction unifications, but quantification gets invoked before
+        % mode analysis, so we need to allow this case...
 		true
 	).
 
@@ -789,8 +771,7 @@
 	quant_info::in, quant_info::out) is det.
 
 implicitly_quantify_conj(!Goals, !Info) :-
-	quantification__get_nonlocals_to_recompute(NonLocalsToRecompute,
-		!Info),
+    quantification__get_nonlocals_to_recompute(NonLocalsToRecompute, !Info),
 	get_vars(NonLocalsToRecompute, !.Goals, FollowingVarsList),
 	implicitly_quantify_conj_2(FollowingVarsList, !Goals, !Info).
 
@@ -802,7 +783,7 @@
 	init(NonLocalVars),
 	quantification__set_nonlocals(NonLocalVars, !Info).
 implicitly_quantify_conj_2([], [_ | _], _, _, _) :-
-	error("implicitly_quantify_conj_2: length mismatch").
+    unexpected(this_file, "implicitly_quantify_conj_2: length mismatch").
 implicitly_quantify_conj_2(
 		[FollowingVars - LambdaFollowingVars | FollowingVarsList],
 		[Goal0 | Goals0], [Goal | Goals], !Info) :-
@@ -857,8 +838,8 @@
 
 %-----------------------------------------------------------------------------%
 
-	% insert the given set of variables into the set of `seen' variables.
-
+    % Insert the given set of variables into the set of `seen' variables.
+    %
 :- pred quantification__update_seen_vars(set_of_var::in,
 	quant_info::in, quant_info::out) is det.
 
@@ -869,15 +850,13 @@
 
 %-----------------------------------------------------------------------------%
 
-	% Given a list of goals, produce a corresponding list of
-	% following variables, where the following variables
-	% for each goal are those variables which occur free in any of the
-	% following goals in the list.  The following variables
-	% are divided into a pair of sets: the first set
-	% contains following variables that occur not in lambda goals,
-	% and the second contains following variables that
-	% occur in lambda goals.
-
+    % Given a list of goals, produce a corresponding list of following
+    % variables, where the following variables for each goal are those
+    % variables which occur free in any of the following goals in the list.
+    % The following variables are divided into a pair of sets: the first set
+    % contains following variables that occur not in lambda goals, and the
+    % second contains following variables that occur in lambda goals.
+    %
 :- pred get_vars(nonlocals_to_recompute::in, list(hlds_goal)::in,
 	list(pair(set_of_var))::out) is det.
 
@@ -892,46 +871,35 @@
 get_vars_2(_, [], Set, LambdaSet, []) :-
 	init(Set),
 	init(LambdaSet).
-get_vars_2(NonLocalsToRecompute, [Goal | Goals],
-		Set, LambdaSet, SetPairList) :-
-	get_vars_2(NonLocalsToRecompute, Goals,
-		Set0, LambdaSet0, SetPairList0),
-	quantification__goal_vars(NonLocalsToRecompute,
-		Goal, Set1, LambdaSet1),
+get_vars_2(NonLocalsToRecompute, [Goal | Goals], Set, LambdaSet,
+        SetPairList) :-
+    get_vars_2(NonLocalsToRecompute, Goals, Set0, LambdaSet0, SetPairList0),
+    quantification__goal_vars(NonLocalsToRecompute, Goal, Set1, LambdaSet1),
 	union(Set0, Set1, Set),
 	union(LambdaSet0, LambdaSet1, LambdaSet),
 	SetPairList = [Set0 - LambdaSet0 | SetPairList0].
 
 :- pred goal_list_vars_2(nonlocals_to_recompute::in, list(hlds_goal)::in,
-	set_of_var::in, set_of_var::out, set_of_var::in, set_of_var::out)
-	is det.
+    set_of_var::in, set_of_var::out, set_of_var::in, set_of_var::out) is det.
 
 goal_list_vars_2(_, [], !Set, !LambdaSet).
 goal_list_vars_2(NonLocalsToRecompute, [Goal - _GoalInfo| Goals],
 		!Set, !LambdaSet) :-
-	quantification__goal_vars_2(NonLocalsToRecompute, Goal,
-		!Set, !LambdaSet),
+    quantification__goal_vars_2(NonLocalsToRecompute, Goal, !Set, !LambdaSet),
 	goal_list_vars_2(NonLocalsToRecompute, Goals, !Set, !LambdaSet).
 
 :- pred case_list_vars_2(nonlocals_to_recompute::in, list(case)::in,
-	set_of_var::in, set_of_var::out, set_of_var::in, set_of_var::out)
-	is det.
+    set_of_var::in, set_of_var::out, set_of_var::in, set_of_var::out) is det.
 
 case_list_vars_2(_, [], !Set, !LambdaSet).
 case_list_vars_2(NonLocalsToRecompute, [case(_Cons, Goal - _GoalInfo) | Cases],
 		!Set, !LambdaSet) :-
-	quantification__goal_vars_2(NonLocalsToRecompute, Goal,
-		!Set, !LambdaSet),
+    quantification__goal_vars_2(NonLocalsToRecompute, Goal, !Set, !LambdaSet),
 	case_list_vars_2(NonLocalsToRecompute, Cases, !Set, !LambdaSet).
 
-	% quantification__goal_vars(NonLocalsToRecompute, Goal, Vars):
-	%	Vars is the set of variables that occur free (unquantified)
-	%	in Goal, excluding unset fields of reconstructions if
-	%	NonLocalsToRecompute is `code_gen_nonlocals'.
 quantification__goal_vars(NonLocalsToRecompute, Goal,
 		bitset_to_set(BothSet)) :-
-	quantification__goal_vars_bitset(NonLocalsToRecompute,
-		Goal, BothSet).
+    quantification__goal_vars_bitset(NonLocalsToRecompute, Goal, BothSet).
 
 quantification__goal_vars(Goal, BothSet) :-
 	quantification__goal_vars(ordinary_nonlocals, Goal, BothSet).
@@ -944,15 +912,17 @@
 	BothSet = union(Set, LambdaSet).
 
 	% quantification__goal_vars(Goal, NonLambdaSet, LambdaSet):
-	%	Set is the set of variables that occur free (unquantified)
-	%	in Goal, not counting occurrences in lambda expressions.
-	%	LambdaSet is the set of variables that occur free (unquantified)
-	%	in lambda expressions in Goal.
+    %
+    % Set is the set of variables that occur free (unquantified) in Goal,
+    % not counting occurrences in lambda expressions. LambdaSet is the set
+    % of variables that occur free (unquantified) in lambda expressions
+    % in Goal.
+    %
 :- pred quantification__goal_vars(nonlocals_to_recompute::in,
 	hlds_goal::in, set_of_var::out, set_of_var::out) is det.
 
-quantification__goal_vars(NonLocalsToRecompute, Goal - _GoalInfo,
-		Set, LambdaSet) :-
+quantification__goal_vars(NonLocalsToRecompute, Goal - _GoalInfo, Set,
+        LambdaSet) :-
 	init(Set0),
 	init(LambdaSet0),
 	quantification__goal_vars_2(NonLocalsToRecompute,
@@ -1003,13 +973,11 @@
 
 quantification__goal_vars_2(NonLocalsToRecompute, par_conj(Goals),
 		!Set, !LambdaSet) :-
-	goal_list_vars_2(NonLocalsToRecompute, Goals,
-		!Set, !LambdaSet).
+    goal_list_vars_2(NonLocalsToRecompute, Goals, !Set, !LambdaSet).
 
 quantification__goal_vars_2(NonLocalsToRecompute, disj(Goals),
 		!Set, !LambdaSet) :-
-	goal_list_vars_2(NonLocalsToRecompute, Goals,
-		!Set, !LambdaSet).
+    goal_list_vars_2(NonLocalsToRecompute, Goals, !Set, !LambdaSet).
 
 quantification__goal_vars_2(NonLocalsToRecompute, switch(Var, _Det, Cases),
 		!Set, !LambdaSet) :-
@@ -1018,8 +986,7 @@
 
 quantification__goal_vars_2(NonLocalsToRecompute, scope(Reason, Goal),
 		Set0, !:Set, LambdaSet0, !:LambdaSet) :-
-	quantification__goal_vars(NonLocalsToRecompute,
-		Goal, !:Set, !:LambdaSet),
+    quantification__goal_vars(NonLocalsToRecompute, Goal, !:Set, !:LambdaSet),
 	(
 		Reason = exist_quant(Vars),
 		delete_list(!.Set, Vars, !:Set),
@@ -1041,8 +1008,7 @@
 
 quantification__goal_vars_2(NonLocalsToRecompute, not(Goal - _GoalInfo),
 		!Set, !LambdaSet) :-
-	quantification__goal_vars_2(NonLocalsToRecompute, Goal,
-		!Set, !LambdaSet).
+    quantification__goal_vars_2(NonLocalsToRecompute, Goal, !Set, !LambdaSet).
 
 quantification__goal_vars_2(NonLocalsToRecompute,
 		if_then_else(Vars, Cond, Then, Else),
@@ -1083,8 +1049,7 @@
 
 quantification__goal_vars_2_shorthand(NonLocalsToRecompute,
 		bi_implication(LHS, RHS), !Set, !LambdaSet) :-
-	goal_list_vars_2(NonLocalsToRecompute, [LHS, RHS],
-		!Set, !LambdaSet).
+    goal_list_vars_2(NonLocalsToRecompute, [LHS, RHS], !Set, !LambdaSet).
 
 :- pred quantification__unify_rhs_vars(nonlocals_to_recompute::in,
 	unify_rhs::in, maybe(list(bool))::in, set_of_var::in, set_of_var::out,
@@ -1099,8 +1064,7 @@
 		MaybeSetArgs = yes(SetArgs)
 	->
 		% Ignore the fields taken from the reused cell.
-		quantification__get_updated_fields(SetArgs, ArgVars,
-			ArgsToSet),
+        quantification__get_updated_fields(SetArgs, ArgVars, ArgsToSet),
 		insert_list(!.Set, ArgsToSet, !:Set)
 	;
 		insert_list(!.Set, ArgVars, !:Set)
@@ -1132,9 +1096,9 @@
 
 quantification__get_updated_fields([], [], !ArgsToSet).
 quantification__get_updated_fields([], [_|_], _, _) :-
-	error("quantification__get_updated_fields").
+    unexpected(this_file, "quantification__get_updated_fields").
 quantification__get_updated_fields([_|_], [], _, _) :-
-	error("quantification__get_updated_fields").
+    unexpected(this_file, "quantification__get_updated_fields").
 quantification__get_updated_fields([SetArg | SetArgs], [Arg | Args],
 		!ArgsToSet) :-
 	(
@@ -1168,27 +1132,25 @@
 
 %-----------------------------------------------------------------------------%
 
-% quantification__rename_apart(RenameSet, RenameMap, Goal0, Goal):
-%	For each variable V in RenameSet, create a fresh variable V',
-%	and insert the mapping V->V' into RenameMap.
-%	Apply RenameMap to Goal0 giving Goal.
-
+    % quantification__rename_apart(RenameSet, RenameMap, Goal0, Goal):
+    %
+    % For each variable V in RenameSet, create a fresh variable V',
+    % and insert the mapping V->V' into RenameMap. Apply RenameMap
+    % to Goal0 giving Goal. 
+    %
 :- pred quantification__rename_apart(set_of_var::in,
 	map(prog_var, prog_var)::out, hlds_goal::in, hlds_goal::out,
 	quant_info::in, quant_info::out) is det.
 
 quantification__rename_apart(RenameSet, RenameMap, !Goal, !Info) :-
-	quantification__get_nonlocals_to_recompute(NonLocalsToRecompute,
-		!Info),
+    quantification__get_nonlocals_to_recompute(NonLocalsToRecompute, !Info),
 	(
 		%
-		% Don't rename apart variables when recomputing the
-		% code-gen nonlocals -- that would stuff up the
-		% ordinary non-locals and the mode information.
-		% The ordinary non-locals are always recomputed
-		% before the code-gen nonlocals -- any necessary
-		% renaming will have been done while recomputing
-		% the ordinary non-locals.
+        % Don't rename apart variables when recomputing the code-gen nonlocals
+        % -- that would stuff up the ordinary non-locals and the mode
+        % information. The ordinary non-locals are always recomputed
+        % before the code-gen nonlocals -- any necessary renaming will have
+        % been done while recomputing the ordinary non-locals.
 		%
 		( empty(RenameSet)
 		; NonLocalsToRecompute = code_gen_nonlocals
@@ -1201,10 +1163,8 @@
 		quantification__get_vartypes(VarTypes0, !Info),
 		map__init(RenameMap0),
 		goal_util__create_variables(RenameList, Varset0, VarTypes0,
-							%^ Reference ^Var names
-			Varset0, Varset, VarTypes0, VarTypes,
-			RenameMap0, RenameMap),
-		goal_util__rename_vars_in_goal(!.Goal, RenameMap, !:Goal),
+            Varset0, Varset, VarTypes0, VarTypes, RenameMap0, RenameMap),
+        goal_util__rename_vars_in_goal(RenameMap, !Goal),
 		quantification__set_varset(Varset, !Info),
 		quantification__set_vartypes(VarTypes, !Info)
 
@@ -1225,8 +1185,7 @@
 	quant_info::in, quant_info::out) is det.
 
 quantification__set_goal_nonlocals(NonLocals, !GoalInfo, !Info) :-
-	quantification__set_goal_nonlocals(NonLocals, _, !GoalInfo,
-		!Info).
+    quantification__set_goal_nonlocals(NonLocals, _, !GoalInfo, !Info).
 
 :- pred quantification__set_goal_nonlocals(set_of_var::in, set(prog_var)::out,
 	hlds_goal_info::in, hlds_goal_info::out,
@@ -1234,15 +1193,13 @@
 
 quantification__set_goal_nonlocals(NonLocals0, NonLocals, !GoalInfo, !Info) :-
 	NonLocals = bitset_to_set(NonLocals0),
-	quantification__get_nonlocals_to_recompute(NonLocalsToRecompute,
-		!Info),
+    quantification__get_nonlocals_to_recompute(NonLocalsToRecompute, !Info),
 	(
 		NonLocalsToRecompute = ordinary_nonlocals,
-		goal_info_set_nonlocals(!.GoalInfo, NonLocals, !:GoalInfo)
+        goal_info_set_nonlocals(NonLocals, !GoalInfo)
 	;
 		NonLocalsToRecompute = code_gen_nonlocals,
-		goal_info_set_code_gen_nonlocals(!.GoalInfo, NonLocals,
-			!:GoalInfo)
+        goal_info_set_code_gen_nonlocals(NonLocals, !GoalInfo)
 	).
 
 %-----------------------------------------------------------------------------%
@@ -1262,8 +1219,7 @@
 		Varset, VarTypes, QuantInfo) :-
 	OverlapWarnings = [],
 	QuantInfo = quant_info(RecomputeNonLocals, OutsideVars, QuantVars,
-		LambdaOutsideVars, NonLocals, Seen, Varset, VarTypes,
-		OverlapWarnings),
+        LambdaOutsideVars, NonLocals, Seen, Varset, VarTypes, OverlapWarnings),
 	init(QuantVars),
 	init(NonLocals),
 	init(LambdaOutsideVars),
@@ -1341,4 +1297,9 @@
 quantification__set_warnings(Warnings, Q0, Q0 ^ warnings := Warnings).
 
 %-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "quantification.m".
+
 %-----------------------------------------------------------------------------%
Index: compiler/recompilation.check.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/recompilation.check.m,v
retrieving revision 1.14
diff -u -b -r1.14 recompilation.check.m
--- compiler/recompilation.check.m	29 Aug 2005 03:22:26 -0000	1.14
+++ compiler/recompilation.check.m	29 Aug 2005 06:32:12 -0000
@@ -1443,24 +1443,18 @@
 recompile_reason_message(item_ambiguity(Item, AmbiguousItems), no, Pieces) :-
 	AmbiguousItemPieces = component_lists_to_pieces(
 		list__map(describe_item, AmbiguousItems)),
-	Pieces = append_punctuation(
-		list__condense([
-			[words("addition of ") | describe_item(Item)],
-			[words("could cause an ambiguity with")],
-			AmbiguousItemPieces]),
-		'.').
+	Pieces = [words("addition of ") | describe_item(Item)]
+		++ [words("could cause an ambiguity with")]
+		++ AmbiguousItemPieces ++ [suffix(".")].
 recompile_reason_message(functor_ambiguity(SymName, Arity,
 		Functor, AmbiguousFunctors), no, Pieces) :-
 	FunctorPieces = describe_functor(SymName, Arity, Functor),
 	AmbiguousFunctorPieces = component_lists_to_pieces(
 		list__map(describe_functor(SymName, Arity),
 		AmbiguousFunctors)),
-	Pieces = append_punctuation(
-		list__condense([
-			[words("addition of ") | FunctorPieces],
-			[words("could cause an ambiguity with")],
-			AmbiguousFunctorPieces]),
-		'.').
+	Pieces = [words("addition of ") | FunctorPieces]
+		++ [words("could cause an ambiguity with")]
+		++ AmbiguousFunctorPieces ++ [suffix(".")].
 recompile_reason_message(changed_item(Item), no,
 		list__append(describe_item(Item), [words("was modified.")])).
 recompile_reason_message(removed_item(Item), no,
Index: compiler/rl_block_opt.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/rl_block_opt.m,v
retrieving revision 1.13
diff -u -b -r1.13 rl_block_opt.m
--- compiler/rl_block_opt.m	22 Mar 2005 06:40:22 -0000	1.13
+++ compiler/rl_block_opt.m	27 Aug 2005 16:20:12 -0000
@@ -1162,10 +1162,12 @@
 		VarSet1, VarSet2, VarSet, VarTypes1, VarTypes2, VarTypes,
 		Subn, conj(Goals2) - DummyGoalInfo, RenamedGoal),
 
-	( Outputs2 = yes(OutputArgs2) ->
-		goal_util__rename_var_list(OutputArgs2, yes, Subn, OutputArgs),
+	(
+		Outputs2 = yes(OutputArgs2),
+		goal_util__rename_var_list(yes, Subn, OutputArgs2, OutputArgs),
 		Outputs = yes(OutputArgs)
 	;
+		Outputs2 = no,
 		Outputs = no
 	),
 
Index: compiler/rl_exprn.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/rl_exprn.m,v
retrieving revision 1.52
diff -u -b -r1.52 rl_exprn.m
--- compiler/rl_exprn.m	22 Jul 2005 12:31:59 -0000	1.52
+++ compiler/rl_exprn.m	27 Aug 2005 14:51:26 -0000
@@ -1088,8 +1088,8 @@
 			[functor(OutputTupleConsId, FinalOutputInsts)]) },
 
 	{ instmap__init_reachable(InitialInstMap0) },
-	{ instmap__set(InitialInstMap0, InputTupleVar, InputTupleInst,
-		InitialInstMap) },
+	{ instmap__set(InputTupleVar, InputTupleInst,
+		InitialInstMap0, InitialInstMap) },
 
 	{ instmap_delta_from_assoc_list([OutputTupleVar - OutputTupleInst],
 		GoalInstMapDelta) },
Index: compiler/saved_vars.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/saved_vars.m,v
retrieving revision 1.51
diff -u -b -r1.51 saved_vars.m
--- compiler/saved_vars.m	16 Aug 2005 15:36:19 -0000	1.51
+++ compiler/saved_vars.m	28 Aug 2005 02:45:37 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1996-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -66,8 +68,7 @@
 	module_info_globals(!.ModuleInfo, Globals),
 	module_info_pred_info(!.ModuleInfo, PredId, PredInfo),
 	body_should_use_typeinfo_liveness(PredInfo, Globals, TypeInfoLiveness),
-	saved_vars_proc_no_io(TypeInfoLiveness, ProcInfo0, ProcInfo,
-		!ModuleInfo).
+    saved_vars_proc_no_io(TypeInfoLiveness, ProcInfo0, ProcInfo, !ModuleInfo).
 
 :- pred saved_vars_proc_no_io(bool::in, proc_info::in, proc_info::out,
 	module_info::in, module_info::out) is det.
@@ -87,7 +88,7 @@
 
 	% hlds_out__write_goal(Goal1, !.ModuleInfo, Varset1, 0, "\n"),
 
-	% recompute the nonlocals for each goal
+    % Recompute the nonlocals for each goal.
 	implicitly_quantify_clause_body(HeadVars, _Warnings, Goal1, Goal2,
 		Varset1, Varset, VarTypes1, VarTypes),
 	proc_info_get_initial_instmap(!.ProcInfo, !.ModuleInfo, InstMap0),
@@ -111,13 +112,13 @@
 	(
 		GoalExpr0 = conj(Goals0),
 		goal_info_get_nonlocals(GoalInfo0, NonLocals),
-		saved_vars_in_conj(Goals0, NonLocals, Goals, !SlotInfo),
+        saved_vars_in_conj(Goals0, Goals, NonLocals, !SlotInfo),
 		conj_list_to_goal(Goals, GoalInfo0, Goal)
 	;
 		GoalExpr0 = par_conj(Goals0),
-			% saved_vars_in_disj treats its goal list as
-			% an independent list of goals, so we can use
-			% it to process the list of parallel conjuncts too.
+        % saved_vars_in_disj treats its goal list as an independent list
+        % of goals, so we can use it to process the list of parallel
+        % conjuncts too.
 		saved_vars_in_disj(Goals0, Goals, !SlotInfo),
 		Goal = par_conj(Goals) - GoalInfo0
 	;
@@ -163,40 +164,45 @@
 
 %-----------------------------------------------------------------------------%
 
-% If we find a unification that assigns a constant to a variable,
-% attempt to push it into the following code.
-%
-% We cannot push such a unification if the following goal needs the value
-% of the variable. We also avoid attempting to push the unification into
-% any following similar unifications, since the order of such unifications
-% does not matter, and we would like to avoid "pushing contests" between
-% several such unifications about which one should be closest to a following
-% goal that uses all the variables they define.
-
-:- pred saved_vars_in_conj(list(hlds_goal)::in, set(prog_var)::in,
-	list(hlds_goal)::out, slot_info::in, slot_info::out) is det.
+    % If we find a unification that assigns a constant to a variable,
+    % attempt to push it into the following code.
+    %
+    % We cannot push such a unification if the following goal needs the value
+    % of the variable. We also avoid attempting to push the unification into
+    % any following similar unifications, since the order of such unifications
+    % does not matter, and we would like to avoid "pushing contests" between
+    % several such unifications about which one should be closest to a
+    % following goal that uses all the variables they define.
+    %
+:- pred saved_vars_in_conj(list(hlds_goal)::in, list(hlds_goal)::out,
+    set(prog_var)::in, slot_info::in, slot_info::out) is det.
 
-saved_vars_in_conj([], _, [], !SlotInfo).
-saved_vars_in_conj([Goal0 | Goals0], NonLocals, Goals, !SlotInfo) :-
+saved_vars_in_conj([], [], _, !SlotInfo).
+saved_vars_in_conj([Goal0 | Goals0], Goals, NonLocals, !SlotInfo) :-
 	(
 		Goal0 = unify(_, _, _, Unif, _) - GoalInfo,
 		Unif = construct(Var, _, [], _, _, _, _),
 		goal_info_get_features(GoalInfo, Features),
-		( all [Feature] ( set__member(Feature, Features)
-			=> ok_to_duplicate(Feature) = yes )),
+        ( all [Feature]
+            (
+                set__member(Feature, Features)
+            =>
+                ok_to_duplicate(Feature) = yes
+            )
+        ),
 		\+ slot_info_do_not_duplicate_var(!.SlotInfo, Var),
-		skip_constant_constructs(Goals0, Constants, Others),
-		Others = [First | _Rest],
+        skip_constant_constructs(Goals0, Constants, OtherGoals),
+        OtherGoals = [First | _Rest],
 		can_push(Var, First)
 	->
 		set__is_member(Var, NonLocals, IsNonLocal),
-		saved_vars_delay_goal(Others, Goal0, Var, IsNonLocal,
-			Goals1, !SlotInfo),
+        saved_vars_delay_goal(OtherGoals, Goals1, Goal0, Var, IsNonLocal,
+            !SlotInfo),
 		list__append(Constants, Goals1, Goals2),
-		saved_vars_in_conj(Goals2, NonLocals, Goals, !SlotInfo)
+        saved_vars_in_conj(Goals2, Goals, NonLocals, !SlotInfo)
 	;
 		saved_vars_in_goal(Goal0, Goal1, !SlotInfo),
-		saved_vars_in_conj(Goals0, NonLocals, Goals1, !SlotInfo),
+        saved_vars_in_conj(Goals0, Goals1, NonLocals, !SlotInfo),
 		Goals = [Goal1 | Goals1]
 	).
 
@@ -241,10 +247,9 @@
 		Others = [Goal0 | Goals0]
 	).
 
-	% Decide whether the value of the given variable is needed
-	% immediately in the goal, or whether the unification that
-	% constructs a value for the variable can be usefully pushed
-	% into the goal.
+    % Decide whether the value of the given variable is needed immediately
+    % in the goal, or whether the unification that constructs a value for
+    % the variable can be usefully pushed into the goal.
 	%
 	% NOTE: the logic of this predicate must match the logic of
 	% saved_vars_delay_goal.
@@ -289,10 +294,11 @@
 	% If Var is exported from the conjunction, we include Construct
 	% at the end of the conjunction to give it its value.
 	%
-:- pred saved_vars_delay_goal(list(hlds_goal)::in, hlds_goal::in, prog_var::in,
-	bool::in, list(hlds_goal)::out, slot_info::in, slot_info::out) is det.
+:- pred saved_vars_delay_goal(list(hlds_goal)::in, list(hlds_goal)::out,
+    hlds_goal::in, prog_var::in, bool::in, slot_info::in, slot_info::out)
+    is det.
 
-saved_vars_delay_goal([], Construct, _Var, IsNonLocal, Goals, !SlotInfo) :-
+saved_vars_delay_goal([], Goals, Construct, _Var, IsNonLocal, !SlotInfo) :-
 	(
 		IsNonLocal = yes,
 		Goals = [Construct]
@@ -300,7 +306,7 @@
 		IsNonLocal = no,
 		Goals = []
 	).
-saved_vars_delay_goal([Goal0 | Goals0], Construct, Var, IsNonLocal, Goals,
+saved_vars_delay_goal([Goal0 | Goals0], Goals, Construct, Var, IsNonLocal,
 		!SlotInfo) :-
 	Goal0 = Goal0Expr - Goal0Info,
 	goal_info_get_nonlocals(Goal0Info, Goal0NonLocals),
@@ -308,135 +314,121 @@
 		(
 			Goal0Expr = unify(_, _, _, _, _),
 			rename_var(Var, _NewVar, Subst, !SlotInfo),
-			goal_util__rename_vars_in_goal(Construct, Subst,
-				NewConstruct),
-			goal_util__rename_vars_in_goal(Goal0, Subst, Goal1),
-			saved_vars_delay_goal(Goals0, Construct, Var,
-				IsNonLocal, Goals1, !SlotInfo),
+            goal_util__rename_vars_in_goal(Subst, Construct, NewConstruct),
+            goal_util__rename_vars_in_goal(Subst, Goal0, Goal1),
+            saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                IsNonLocal, !SlotInfo),
 			Goals = [NewConstruct, Goal1 | Goals1]
 		;
 			Goal0Expr = call(_, _, _, _, _, _),
 			rename_var(Var, _NewVar, Subst, !SlotInfo),
-			goal_util__rename_vars_in_goal(Construct, Subst,
-				NewConstruct),
-			goal_util__rename_vars_in_goal(Goal0, Subst, Goal1),
-			saved_vars_delay_goal(Goals0, Construct, Var,
-				IsNonLocal, Goals1, !SlotInfo),
+            goal_util__rename_vars_in_goal(Subst, Construct, NewConstruct),
+            goal_util__rename_vars_in_goal(Subst, Goal0, Goal1),
+            saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                IsNonLocal, !SlotInfo),
 			Goals = [NewConstruct, Goal1 | Goals1]
 		;
 			Goal0Expr = generic_call(_, _, _, _),
 			rename_var(Var, _NewVar, Subst, !SlotInfo),
-			goal_util__rename_vars_in_goal(Construct, Subst,
-				NewConstruct),
-			goal_util__rename_vars_in_goal(Goal0, Subst, Goal1),
-			saved_vars_delay_goal(Goals0, Construct, Var,
-				IsNonLocal, Goals1, !SlotInfo),
+            goal_util__rename_vars_in_goal(Subst, Construct, NewConstruct),
+            goal_util__rename_vars_in_goal(Subst, Goal0, Goal1),
+            saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                IsNonLocal, !SlotInfo),
 			Goals = [NewConstruct, Goal1 | Goals1]
 		;
 			Goal0Expr = foreign_proc(_, _, _, _, _, _),
 			rename_var(Var, _NewVar, Subst, !SlotInfo),
-			goal_util__rename_vars_in_goal(Construct, Subst,
-				NewConstruct),
-			goal_util__rename_vars_in_goal(Goal0, Subst, Goal1),
-			saved_vars_delay_goal(Goals0, Construct, Var,
-				IsNonLocal, Goals1, !SlotInfo),
+            goal_util__rename_vars_in_goal(Subst, Construct, NewConstruct),
+            goal_util__rename_vars_in_goal(Subst, Goal0, Goal1),
+            saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                IsNonLocal, !SlotInfo),
 			Goals = [NewConstruct, Goal1 | Goals1]
 		;
 			Goal0Expr = conj(Conj),
 			list__append(Conj, Goals0, Goals1),
-			saved_vars_delay_goal(Goals1, Construct, Var,
-				IsNonLocal, Goals, !SlotInfo)
+            saved_vars_delay_goal(Goals1, Goals, Construct, Var,
+                IsNonLocal, !SlotInfo)
 		;
 			Goal0Expr = par_conj(_ParConj),
-			saved_vars_delay_goal(Goals0, Construct, Var,
-				IsNonLocal, Goals1, !SlotInfo),
+            saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                IsNonLocal, !SlotInfo),
 			Goals = [Goal0|Goals1]
 		;
 			Goal0Expr = scope(Reason, SomeGoal0),
 			rename_var(Var, NewVar, Subst, !SlotInfo),
-			goal_util__rename_vars_in_goal(Construct, Subst,
-				NewConstruct),
-			goal_util__rename_vars_in_goal(SomeGoal0, Subst,
-				SomeGoal1),
-			push_into_goal(SomeGoal1, NewConstruct, NewVar,
-				SomeGoal, !SlotInfo),
+            goal_util__rename_vars_in_goal(Subst, Construct, NewConstruct),
+            goal_util__rename_vars_in_goal(Subst, SomeGoal0, SomeGoal1),
+            push_into_goal(SomeGoal1, SomeGoal, NewConstruct, NewVar,
+                !SlotInfo),
 			Goal1 = scope(Reason, SomeGoal) - Goal0Info,
-			saved_vars_delay_goal(Goals0, Construct, Var,
-				IsNonLocal, Goals1, !SlotInfo),
+            saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                IsNonLocal, !SlotInfo),
 			Goals = [Goal1 | Goals1]
 		;
 			Goal0Expr = not(NegGoal0),
 			rename_var(Var, NewVar, Subst, !SlotInfo),
-			goal_util__rename_vars_in_goal(Construct, Subst,
-				NewConstruct),
-			goal_util__rename_vars_in_goal(NegGoal0, Subst,
-				NegGoal1),
-			push_into_goal(NegGoal1, NewConstruct, NewVar,
-				NegGoal, !SlotInfo),
+            goal_util__rename_vars_in_goal(Subst, Construct, NewConstruct),
+            goal_util__rename_vars_in_goal(Subst, NegGoal0, NegGoal1),
+            push_into_goal(NegGoal1, NegGoal, NewConstruct, NewVar,
+                !SlotInfo),
 			Goal1 = not(NegGoal) - Goal0Info,
-			saved_vars_delay_goal(Goals0, Construct, Var,
-				IsNonLocal, Goals1, !SlotInfo),
+            saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                IsNonLocal, !SlotInfo),
 			Goals = [Goal1 | Goals1]
 		;
 			Goal0Expr = disj(Disjuncts0),
-			push_into_goals_rename(Disjuncts0, Construct, Var,
-				Disjuncts, !SlotInfo),
+            push_into_goals_rename(Disjuncts0, Disjuncts, Construct, Var,
+                !SlotInfo),
 			Goal1 = disj(Disjuncts) - Goal0Info,
-			saved_vars_delay_goal(Goals0, Construct, Var,
-				IsNonLocal, Goals1, !SlotInfo),
+            saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                IsNonLocal, !SlotInfo),
 			Goals = [Goal1 | Goals1]
 		;
 			Goal0Expr = switch(SwitchVar, CF, Cases0),
 			( SwitchVar = Var ->
-				saved_vars_delay_goal(Goals0, Construct, Var,
-					IsNonLocal, Goals1, !SlotInfo),
+                saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                    IsNonLocal, !SlotInfo),
 				Goals = [Construct, Goal0 | Goals1]
 			;
-				push_into_cases_rename(Cases0, Construct, Var,
-					Cases, !SlotInfo),
-				Goal1 = switch(SwitchVar, CF, Cases)
-					- Goal0Info,
-				saved_vars_delay_goal(Goals0, Construct, Var,
-					IsNonLocal, Goals1, !SlotInfo),
+                push_into_cases_rename(Cases0, Cases, Construct, Var,
+                    !SlotInfo),
+                Goal1 = switch(SwitchVar, CF, Cases) - Goal0Info,
+                saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                    IsNonLocal, !SlotInfo),
 				Goals = [Goal1 | Goals1]
 			)
 		;
 			Goal0Expr = if_then_else(V, Cond0, Then0, Else0),
-			push_into_goal_rename(Cond0, Construct, Var,
-				Cond, !SlotInfo),
-			push_into_goal_rename(Then0, Construct, Var,
-				Then, !SlotInfo),
-			push_into_goal_rename(Else0, Construct, Var,
-				Else, !SlotInfo),
-			Goal1 = if_then_else(V, Cond, Then, Else)
-				- Goal0Info,
-			saved_vars_delay_goal(Goals0, Construct, Var,
-				IsNonLocal, Goals1, !SlotInfo),
+            push_into_goal_rename(Cond0, Cond, Construct, Var, !SlotInfo),
+            push_into_goal_rename(Then0, Then, Construct, Var, !SlotInfo),
+            push_into_goal_rename(Else0, Else, Construct, Var, !SlotInfo),
+            Goal1 = if_then_else(V, Cond, Then, Else) - Goal0Info,
+            saved_vars_delay_goal(Goals0, Goals1, Construct, Var,
+                IsNonLocal, !SlotInfo),
 			Goals = [Goal1 | Goals1]
 		;
 			Goal0Expr = shorthand(_),
-			% these should have been expanded out by now
+            % These should have been expanded out by now.
 			unexpected(this_file,
 				"saved_vars_delay_goal: unexpected shorthand")
 		)
 	;
-		saved_vars_delay_goal(Goals0, Construct, Var, IsNonLocal,
-			Goals1, !SlotInfo),
+        saved_vars_delay_goal(Goals0, Goals1, Construct, Var, IsNonLocal,
+            !SlotInfo),
 		Goals = [Goal0 | Goals1]
 	).
 
-	% Push a non-renamed version of the given construction into the
-	% given goal.  Also traverse the goal looking for further
-	% opportunities.
+    % Push a non-renamed version of the given construction into the given goal.
+    % Also traverse the goal looking for further opportunities.
 	%
-:- pred push_into_goal(hlds_goal::in, hlds_goal::in, prog_var::in,
-	hlds_goal::out, slot_info::in, slot_info::out) is det.
+:- pred push_into_goal(hlds_goal::in, hlds_goal::out, hlds_goal::in,
+    prog_var::in, slot_info::in, slot_info::out) is det.
 
-push_into_goal(Goal0, Construct, Var, Goal, !SlotInfo) :-
+push_into_goal(Goal0, Goal, Construct, Var, !SlotInfo) :-
 	saved_vars_in_goal(Goal0, Goal1, !SlotInfo),
 	Goal1 = _ - Goal1Info,
 	goal_to_conj_list(Goal1, Conj1),
-	saved_vars_delay_goal(Conj1, Construct, Var, no, Conj, !SlotInfo),
+    saved_vars_delay_goal(Conj1, Conj, Construct, Var, no, !SlotInfo),
 	conj_list_to_goal(Conj, Goal1Info, Goal).
 
 	% Push a renamed version of the given construction into the
@@ -444,17 +436,17 @@
 	% by the construction, then this would have no effect, so we
 	% merely traverse the goal looking for other opportunities.
 	%
-:- pred push_into_goal_rename(hlds_goal::in, hlds_goal::in, prog_var::in,
-	hlds_goal::out, slot_info::in, slot_info::out) is det.
+:- pred push_into_goal_rename(hlds_goal::in, hlds_goal::out, hlds_goal::in,
+    prog_var::in, slot_info::in, slot_info::out) is det.
 
-push_into_goal_rename(Goal0, Construct, Var, Goal, !SlotInfo) :-
+push_into_goal_rename(Goal0, Goal, Construct, Var, !SlotInfo) :-
 	Goal0 = _ - GoalInfo0,
 	goal_info_get_nonlocals(GoalInfo0, NonLocals),
 	( set__member(Var, NonLocals) ->
 		rename_var(Var, NewVar, Subst, !SlotInfo),
-		goal_util__rename_vars_in_goal(Construct, Subst, NewConstruct),
-		goal_util__rename_vars_in_goal(Goal0, Subst, Goal1),
-		push_into_goal(Goal1, NewConstruct, NewVar, Goal, !SlotInfo)
+        goal_util__rename_vars_in_goal(Subst, Construct, NewConstruct),
+        goal_util__rename_vars_in_goal(Subst, Goal0, Goal1),
+        push_into_goal(Goal1, Goal, NewConstruct, NewVar, !SlotInfo)
 	;
 		saved_vars_in_goal(Goal0, Goal, !SlotInfo)
 	).
@@ -462,27 +454,26 @@
 	% Push renamed versions of the given construction into each of
 	% several goals.
 	%
-:- pred push_into_goals_rename(list(hlds_goal)::in, hlds_goal::in,
-	prog_var::in, list(hlds_goal)::out, slot_info::in, slot_info::out)
-	is det.
+:- pred push_into_goals_rename(list(hlds_goal)::in, list(hlds_goal)::out,
+    hlds_goal::in, prog_var::in, slot_info::in, slot_info::out) is det.
 
-push_into_goals_rename([], _Construct, _Var, [], !SlotInfo).
-push_into_goals_rename([Goal0 | Goals0], Construct, Var, [Goal | Goals],
+push_into_goals_rename([], [], _Construct, _Var, !SlotInfo).
+push_into_goals_rename([Goal0 | Goals0], [Goal | Goals], Construct, Var,
 		!SlotInfo) :-
-	push_into_goal_rename(Goal0, Construct, Var, Goal, !SlotInfo),
-	push_into_goals_rename(Goals0, Construct, Var, Goals, !SlotInfo).
+    push_into_goal_rename(Goal0, Goal, Construct, Var, !SlotInfo),
+    push_into_goals_rename(Goals0, Goals, Construct, Var, !SlotInfo).
 	
 	% Push renamed versions of the given construction into each of
 	% several cases.
 	%
-:- pred push_into_cases_rename(list(case)::in, hlds_goal::in, prog_var::in,
-	list(case)::out, slot_info::in, slot_info::out) is det.
+:- pred push_into_cases_rename(list(case)::in, list(case)::out, hlds_goal::in,
+    prog_var::in, slot_info::in, slot_info::out) is det.
 
-push_into_cases_rename([], _Construct, _Var, [], !SlotInfo).
-push_into_cases_rename([case(ConsId, Goal0) | Cases0], Construct, Var,
-		[case(ConsId, Goal) | Cases], !SlotInfo) :-
-	push_into_goal_rename(Goal0, Construct, Var, Goal, !SlotInfo),
-	push_into_cases_rename(Cases0, Construct, Var, Cases, !SlotInfo).
+push_into_cases_rename([], [], _Construct, _Var, !SlotInfo).
+push_into_cases_rename([case(ConsId, Goal0) | Cases0],
+        [case(ConsId, Goal) | Cases], Construct, Var, !SlotInfo) :-
+    push_into_goal_rename(Goal0, Goal, Construct, Var, !SlotInfo),
+    push_into_cases_rename(Cases0, Cases, Construct, Var, !SlotInfo).
 
 %-----------------------------------------------------------------------------%
 
@@ -533,8 +524,7 @@
 	slot_info::in, slot_info::out) is det.
 
 rename_var(Var, NewVar, Substitution, !SlotInfo) :-
-	!.SlotInfo = slot_info(Varset0, VarTypes0, RttiVarMaps0,
-		TypeInfoLiveness),
+    !.SlotInfo = slot_info(Varset0, VarTypes0, RttiVarMaps0, TypeInfoLiveness),
 	varset__new_var(Varset0, NewVar, Varset),
 	map__from_assoc_list([Var - NewVar], Substitution),
 	map__lookup(VarTypes0, Var, Type),
Index: compiler/simplify.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/simplify.m,v
retrieving revision 1.150
diff -u -b -r1.150 simplify.m
--- compiler/simplify.m	19 Aug 2005 08:35:57 -0000	1.150
+++ compiler/simplify.m	27 Aug 2005 16:32:15 -0000
@@ -205,7 +205,7 @@
         ; GoalExpr0 = switch(_, _, _)
         )
     ->
-        goal_info_add_feature(GoalInfo0, mode_check_clauses_goal, GoalInfo1),
+        goal_info_add_feature(mode_check_clauses_goal, GoalInfo0, GoalInfo1),
         Goal1 = GoalExpr0 - GoalInfo1
     ;
         Goal1 = Goal0
@@ -494,15 +494,15 @@
         instmap_delta_is_reachable(DeltaInstmap0)
     ->
         instmap_delta_init_unreachable(UnreachableInstMapDelta),
-        goal_info_set_instmap_delta(GoalInfo0, UnreachableInstMapDelta,
-            GoalInfo),
+        goal_info_set_instmap_delta(UnreachableInstMapDelta,
+            GoalInfo0, GoalInfo),
         simplify_info_set_rerun_det(!Info)
     ;
         instmap_delta_is_unreachable(DeltaInstmap0),
         NumSolns0 \= at_most_zero
     ->
         determinism_components(Determinism, CanFail0, at_most_zero),
-        goal_info_set_determinism(GoalInfo0, Determinism, GoalInfo),
+        goal_info_set_determinism(Determinism, GoalInfo0, GoalInfo),
         simplify_info_set_rerun_det(!Info)
     ;
         GoalInfo = GoalInfo0
@@ -516,8 +516,7 @@
 
 simplify__goal_2(conj(Goals0), Goal, GoalInfo0, GoalInfo, !Info) :-
     simplify_info_get_instmap(!.Info, InstMap0),
-    simplify__excess_assigns_in_conj(GoalInfo0,
-        Goals0, Goals1, !Info),
+    simplify__excess_assigns_in_conj(GoalInfo0, Goals0, Goals1, !Info),
     simplify__conj(Goals1, [], Goals, GoalInfo0, !Info),
     simplify_info_set_instmap(InstMap0, !Info),
     (
@@ -543,7 +542,7 @@
             simplify__contains_multisoln_goal(Goals)
         ->
             determinism_components(InnerDetism, CanFail, at_most_many),
-            goal_info_set_determinism(GoalInfo0, InnerDetism, InnerInfo),
+            goal_info_set_determinism(InnerDetism, GoalInfo0, InnerInfo),
             InnerGoal = conj(Goals) - InnerInfo,
             Goal = scope(commit(dont_force_pruning), InnerGoal)
         ;
@@ -597,7 +596,7 @@
             merge_instmap_deltas(InstMap0, NonLocals, VarTypes, InstMaps,
                 NewDelta, ModuleInfo1, ModuleInfo2),
             simplify_info_set_module_info(ModuleInfo2, !Info),
-            goal_info_set_instmap_delta(GoalInfo0, NewDelta, GoalInfo)
+            goal_info_set_instmap_delta(NewDelta, GoalInfo0, GoalInfo)
         )
     ),
     list__length(Disjuncts, DisjunctsLength),
@@ -666,7 +665,7 @@
                 merge_instmap_deltas(InstMap0, NonLocals, VarTypes,
                     InstMaps, NewDelta, ModuleInfo1, ModuleInfo2),
                 simplify_info_set_module_info(ModuleInfo2, !Info),
-                goal_info_set_instmap_delta(GoalInfo0, NewDelta, GoalInfo)
+                goal_info_set_instmap_delta(NewDelta, GoalInfo0, GoalInfo)
             ;
                 simplify__create_test_unification(Var, ConsId, Arity,
                     UnifyGoal, !Info),
@@ -716,7 +715,7 @@
             merge_instmap_deltas(InstMap0, NonLocals, VarTypes, InstMaps,
                 NewDelta, ModuleInfo1, ModuleInfo2),
             simplify_info_set_module_info(ModuleInfo2, !Info),
-            goal_info_set_instmap_delta(GoalInfo0, NewDelta, GoalInfo)
+            goal_info_set_instmap_delta(NewDelta, GoalInfo0, GoalInfo)
         )
     ),
     list__length(Cases0, Cases0Length),
@@ -929,9 +928,9 @@
             ;
                 error("simplify__goal_2: cannot get negated determinism")
             ),
-            goal_info_set_determinism(CondInfo0, NegDetism, NegCondInfo0),
-            goal_info_set_instmap_delta(NegCondInfo0, NegInstMapDelta,
-                NegCondInfo),
+            goal_info_set_determinism(NegDetism, CondInfo0, NegCondInfo0),
+            goal_info_set_instmap_delta(NegInstMapDelta,
+                NegCondInfo0, NegCondInfo),
             Cond = not(Cond0) - NegCondInfo
         ),
         goal_to_conj_list(Else0, ElseList),
@@ -977,7 +976,7 @@
             [CondThenDelta, ElseDelta], NewDelta,
             ModuleInfo0, ModuleInfo1),
         simplify_info_set_module_info(ModuleInfo1, !Info),
-        goal_info_set_instmap_delta(GoalInfo0, NewDelta, GoalInfo1),
+        goal_info_set_instmap_delta(NewDelta, GoalInfo0, GoalInfo1),
         IfThenElse = if_then_else(Vars, Cond, Then, Else),
 
         goal_info_get_determinism(GoalInfo0, IfThenElseDetism0),
@@ -1012,7 +1011,7 @@
             ->
                 determinism_components(InnerDetism,
                     IfThenElseCanFail, at_most_many),
-                goal_info_set_determinism(GoalInfo1, InnerDetism, InnerInfo),
+                goal_info_set_determinism(InnerDetism, GoalInfo1, InnerInfo),
                 Goal = scope(commit(dont_force_pruning),
                     IfThenElse - InnerInfo)
             ;
@@ -1178,7 +1177,7 @@
         CmpGoal0),
     CmpGoal0 = CmpExpr - CmpInfo0,
     goal_info_get_nonlocals(CmpInfo0, CmpNonLocals0),
-    goal_info_set_nonlocals(CmpInfo0, CmpNonLocals0 `insert` R, CmpInfo),
+    goal_info_set_nonlocals(CmpNonLocals0 `insert` R, CmpInfo0, CmpInfo),
     CmpGoal  = CmpExpr - CmpInfo,
 
         % Construct the unification R = Inequality.
@@ -1192,7 +1191,7 @@
                 "replacement of inequality with call to compare/3"), []),
     UfyExpr  = unify(R, RHS, UMode, UKind, UContext),
     goal_info_get_nonlocals(GoalInfo, UfyNonLocals0),
-    goal_info_set_nonlocals(GoalInfo, UfyNonLocals0 `insert` R, UfyInfo),
+    goal_info_set_nonlocals(UfyNonLocals0 `insert` R, GoalInfo, UfyInfo),
     UfyGoal  = UfyExpr - UfyInfo,
 
     (
@@ -1350,8 +1349,8 @@
         simplify_info_get_var_types(!.Info, VarTypes),
         (
             Goal1 = call(_, _, _, _, _, _),
-            const_prop.evaluate_call(PredId, ProcId, Args, GoalInfo0, VarTypes,
-                Instmap0, ModuleInfo2, Goal2, GoalInfo2)
+            const_prop.evaluate_call(PredId, ProcId, Args, VarTypes,
+                Instmap0, ModuleInfo2, Goal2, GoalInfo0, GoalInfo2)
         ->
             Goal = Goal2,
             GoalInfo = GoalInfo2,
@@ -1487,7 +1486,7 @@
     % add the extra type_info vars to the nonlocals for the call
     goal_info_get_nonlocals(GoalInfo0, NonLocals0),
     set__insert_list(NonLocals0, TypeInfoVars, NonLocals),
-    goal_info_set_nonlocals(GoalInfo0, NonLocals, CallGoalInfo).
+    goal_info_set_nonlocals(NonLocals, GoalInfo0, CallGoalInfo).
 
 :- pred simplify__make_type_info_vars(list(type)::in, list(prog_var)::out,
     list(hlds_goal)::out, simplify_info::in, simplify_info::out) is det.
@@ -1800,7 +1799,7 @@
             renaming_transitive_closure(Subn1, Subn),
             list__reverse(RevGoals, Goals1),
             MustSub = no,
-            goal_util__rename_vars_in_goals(Goals1, MustSub, Subn, Goals),
+            goal_util__rename_vars_in_goals(MustSub, Subn, Goals1, Goals),
             map__keys(Subn0, RemovedVars),
             varset__delete_vars(VarSet0, RemovedVars, VarSet),
             simplify_info_set_varset(VarSet, !Info),
@@ -2145,11 +2144,11 @@
         goal_info_get_nonlocals(CondGoalInfo, CondNonLocals),
         goal_info_get_nonlocals(RestGoalInfo, RestNonLocals),
         set__union(CondNonLocals, RestNonLocals, NonLocals),
-        goal_info_set_nonlocals(GoalInfo, NonLocals, NewGoalInfo0),
+        goal_info_set_nonlocals(NonLocals, GoalInfo, NewGoalInfo0),
 
         goal_info_get_instmap_delta(GoalInfo, InstMapDelta0),
-        instmap_delta_restrict(InstMapDelta0, NonLocals, InstMapDelta),
-        goal_info_set_instmap_delta(NewGoalInfo0, InstMapDelta, NewGoalInfo1),
+        instmap_delta_restrict(NonLocals, InstMapDelta0, InstMapDelta),
+        goal_info_set_instmap_delta(InstMapDelta, NewGoalInfo0, NewGoalInfo1),
 
         goal_info_get_determinism(CondGoalInfo, CondDetism),
         goal_info_get_determinism(RestGoalInfo, RestDetism),
@@ -2163,7 +2162,7 @@
             MaxSoln = MaxSoln0
         ),
         determinism_components(Detism, CanFail, MaxSoln),
-        goal_info_set_determinism(NewGoalInfo1, Detism, NewGoalInfo),
+        goal_info_set_determinism(Detism, NewGoalInfo1, NewGoalInfo),
 
         Goal = if_then_else([], Cond, Then, Rest) - NewGoalInfo
     ).
Index: compiler/size_prof.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/size_prof.m,v
retrieving revision 1.19
diff -u -b -r1.19 size_prof.m
--- compiler/size_prof.m	22 Jul 2005 12:32:00 -0000	1.19
+++ compiler/size_prof.m	28 Aug 2005 04:55:02 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 2003-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -89,12 +91,14 @@
 
 :- import_module io.
 
-% Specifies how term sizes are to be measured.
+    % Specifies how term sizes are to be measured.
+    %
 :- type construct_transform
 	--->	term_words
 	;	term_cells.
 
-% Perform the transformation on the specified predicate.
+    % Perform the transformation on the specified predicate.
+    %
 :- pred process_proc_msg(construct_transform::in, pred_id::in, proc_id::in,
 	proc_info::in, proc_info::out, module_info::in, module_info::out,
 	io::di, io::uo) is det.
@@ -105,6 +109,7 @@
 :- implementation.
 
 :- import_module check_hlds__inst_match.
+:- import_module check_hlds__mode_util.
 :- import_module check_hlds__polymorphism.
 :- import_module check_hlds__simplify.
 :- import_module check_hlds__type_util.
@@ -116,10 +121,10 @@
 :- import_module libs__globals.
 :- import_module libs__options.
 :- import_module mdbcomp__prim_data.
-:- import_module check_hlds__mode_util.
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__prog_data.
-:- import_module parse_tree__prog_util.
 :- import_module parse_tree__prog_type.
+:- import_module parse_tree__prog_util.
 :- import_module transform_hlds__term_norm.
 
 :- import_module assoc_list.
@@ -131,6 +136,7 @@
 :- import_module set.
 :- import_module std_util.
 :- import_module string.
+:- import_module svmap.
 :- import_module term.
 :- import_module varset.
 
@@ -193,8 +199,8 @@
 :- type rev_type_ctor_map	== map(prog_var, type_ctor).
 :- type known_size_map		== map(prog_var, int).
 
-:- type size_prof__info --->
-	size_prof_info(
+:- type size_prof__info
+    --->    size_prof_info(
 		type_ctor_map		:: type_ctor_map,
 		type_info_map		:: type_info_map,
 		rev_type_ctor_map	:: rev_type_ctor_map,
@@ -211,15 +217,16 @@
 process_proc_msg(Transform, PredId, ProcId, ProcInfo0, ProcInfo,
 		!ModuleInfo, !IO) :-
 	globals__io_lookup_bool_option(very_verbose, VeryVerbose, !IO),
-	( VeryVerbose = yes ->
+    (
+        VeryVerbose = yes,
 		io__write_string("% Adding typeinfos in ", !IO),
-		hlds_out__write_pred_proc_id(!.ModuleInfo, PredId, ProcId,
-			!IO),
+        hlds_out__write_pred_proc_id(!.ModuleInfo, PredId, ProcId, !IO),
 		io__write_string(": ", !IO),
 		process_proc(Transform, PredId, ProcId, ProcInfo0, ProcInfo,
 			!ModuleInfo),
 		io__write_string("done.\n", !IO)
 	;
+        VeryVerbose = no,
 		process_proc(Transform, PredId, ProcId, ProcInfo0, ProcInfo,
 			!ModuleInfo)
 	).
@@ -275,12 +282,10 @@
 	(
 		GoalExpr0 = unify(LHS, RHS, UniMode, Unify0, UnifyContext),
 		(
-			Unify0 = construct(Var, ConsId, Args, ArgModes, How,
-				Unique, _)
+            Unify0 = construct(Var, ConsId, Args, ArgModes, How, Unique, _)
 		->
-			process_construct(LHS, RHS, UniMode, UnifyContext,
-				Var, ConsId, Args, ArgModes, How, Unique,
-				GoalInfo0, GoalExpr, !Info)
+            process_construct(LHS, RHS, UniMode, UnifyContext, Var, ConsId,
+                Args, ArgModes, How, Unique, GoalInfo0, GoalExpr, !Info)
 		;
 			Unify0 = deconstruct(Var, ConsId, Args, ArgModes,
 				_CanFail, _CanCGC),
@@ -288,8 +293,7 @@
 			% BindingArgModes = [], which is almost 100% likely,
 			% then process_deconstruct would return GoalExpr0 as
 			% GoalExpr anyway, but would take longer.
-			list__filter(binds_arg_in_cell(!.Info), ArgModes,
-				BindingArgModes),
+            list__filter(binds_arg_in_cell(!.Info), ArgModes, BindingArgModes),
 			BindingArgModes \= []
 		->
 			process_deconstruct(Var, ConsId, Args, ArgModes,
@@ -331,9 +335,8 @@
 		RevTypeInfoMap0 = !.Info ^ rev_type_info_map,
 		TypeCtorMap0 = !.Info ^ type_ctor_map,
 		KnownSizeMap0 = !.Info ^ known_size_map,
-		process_par_conj(Goals0, Goals, !Info,
-			TargetTypeInfoMap0, TypeInfoMap0, TypeCtorMap0,
-			KnownSizeMap0),
+        process_par_conj(Goals0, Goals, !Info, TargetTypeInfoMap0,
+            TypeInfoMap0, TypeCtorMap0, KnownSizeMap0),
 		!:Info = !.Info ^ target_type_info_map := TargetTypeInfoMap0,
 		!:Info = !.Info ^ type_info_map := TypeInfoMap0,
 		!:Info = !.Info ^ rev_type_info_map := RevTypeInfoMap0,
@@ -365,7 +368,7 @@
 			Cases = [First | Later]
 		;
 			Cases0 = [],
-			error("size_prof__process_goal: empty switch")
+            unexpected(this_file, "size_prof__process_goal: empty switch")
 		),
 		update_rev_maps(!Info),
 		update_target_map(!Info),
@@ -434,10 +437,8 @@
 		TypeInfoMapElse = !.Info ^ type_info_map,
 		KnownSizeMapElse = !.Info ^ known_size_map,
 
-		TypeInfoMap = map__common_subset(TypeInfoMapThen,
-			TypeInfoMapElse),
-		KnownSizeMap = map__common_subset(KnownSizeMapThen,
-			KnownSizeMapElse),
+        TypeInfoMap = map__common_subset(TypeInfoMapThen, TypeInfoMapElse),
+        KnownSizeMap = map__common_subset(KnownSizeMapThen, KnownSizeMapElse),
 		!:Info = !.Info ^ type_info_map := TypeInfoMap,
 		!:Info = !.Info ^ type_ctor_map := map__init,
 		!:Info = !.Info ^ known_size_map := KnownSizeMap,
@@ -453,10 +454,9 @@
 		RevTypeCtorMap0 = !.Info ^ rev_type_ctor_map,
 		KnownSizeMap0 = !.Info ^ known_size_map,
 		process_goal(NegGoal0, NegGoal, !Info),
-		% Variables constructed in negated goals are not available
-		% after the negated goal fails and the negation succeeds.
-		% The sizes we learn in NegGoal0 don't apply after NegGoal0
-		% fails.
+        % Variables constructed in negated goals are not available after the
+        % negated goal fails and the negation succeeds. The sizes we learn
+        % in NegGoal0 don't apply after NegGoal0 fails.
 		!:Info = !.Info ^ target_type_info_map := TargetTypeInfoMap0,
 		!:Info = !.Info ^ type_info_map := TypeInfoMap0,
 		!:Info = !.Info ^ rev_type_info_map := RevTypeInfoMap0,
@@ -470,7 +470,7 @@
 		GoalExpr = scope(Reason, SomeGoal)
 	;
 		GoalExpr0 = shorthand(_),
-		error("size_prof__process_goal: shorthand")
+        unexpected(this_file, "size_prof__process_goal: shorthand")
 	),
 	Goal = GoalExpr - GoalInfo0.
 
@@ -533,14 +533,11 @@
 		Later0 = [Head0 | Tail0],
 		map__union(select_first, TypeInfoMapFirst,
 			TargetTypeInfoMap, LaterTargetTypeInfoMap),
-		!:Info = !.Info ^ target_type_info_map :=
-			LaterTargetTypeInfoMap,
-		process_disj(Head0, Head, Tail0, Tail, !Info,
-			TargetTypeInfoMap, TypeInfoMap0, RevTypeInfoMap0,
-			TypeCtorMap0, RevTypeCtorMap0,
+        !:Info = !.Info ^ target_type_info_map := LaterTargetTypeInfoMap,
+        process_disj(Head0, Head, Tail0, Tail, !Info, TargetTypeInfoMap,
+            TypeInfoMap0, RevTypeInfoMap0, TypeCtorMap0, RevTypeCtorMap0,
 			TypeInfoMapLater, KnownSizeMap0, KnownSizeMapLater),
-		TypeInfoMap = map__common_subset(TypeInfoMapFirst,
-			TypeInfoMapLater),
+        TypeInfoMap = map__common_subset(TypeInfoMapFirst, TypeInfoMapLater),
 		KnownSizeMap = map__common_subset(KnownSizeMapFirst,
 			KnownSizeMapLater),
 		Later = [Head | Tail]
@@ -576,15 +573,11 @@
 		Later0 = [Head0 | Tail0],
 		map__union(select_first, TargetTypeInfoMap,
 			TypeInfoMapFirst, LaterTargetTypeInfoMap),
-		!:Info = !.Info ^ target_type_info_map :=
-			LaterTargetTypeInfoMap,
-		process_switch(Head0, Head, Tail0, Tail, !Info,
-			TargetTypeInfoMap,
-			TypeInfoMap0, RevTypeInfoMap0,
-			TypeCtorMap0, RevTypeCtorMap0,
+        !:Info = !.Info ^ target_type_info_map := LaterTargetTypeInfoMap,
+        process_switch(Head0, Head, Tail0, Tail, !Info, TargetTypeInfoMap,
+            TypeInfoMap0, RevTypeInfoMap0, TypeCtorMap0, RevTypeCtorMap0,
 			TypeInfoMapLater, KnownSizeMap0, KnownSizeMapLater),
-		TypeInfoMap = map__common_subset(TypeInfoMapFirst,
-			TypeInfoMapLater),
+        TypeInfoMap = map__common_subset(TypeInfoMapFirst, TypeInfoMapLater),
 		KnownSizeMap = map__common_subset(KnownSizeMapFirst,
 			KnownSizeMapLater),
 		Later = [Head | Tail]
@@ -608,8 +601,8 @@
 	( type_to_ctor_and_args(VarType, VarTypeCtorPrime, _VarTypeArgs) ->
 		VarTypeCtor = VarTypeCtorPrime
 	;
-		error("size_prof__process_construct: "
-			++ "constructing term of variable type")
+        unexpected(this_file,
+            "size_prof__process_construct: constructing term of variable type")
 	),
 	type_ctor_module(!.Info ^ module_info, VarTypeCtor, VarTypeCtorModule),
 	type_ctor_name(!.Info ^ module_info, VarTypeCtor, VarTypeCtorName),
@@ -621,48 +614,40 @@
 				ConsId = type_info_cell_constructor(_),
 				Args = [TypeCtorInfoVar | ArgTypeInfoVars]
 			->
-				record_known_type_info(Var, TypeCtorInfoVar,
-					ArgTypeInfoVars, !Info)
+                record_known_type_info(Var, TypeCtorInfoVar, ArgTypeInfoVars,
+                    !Info)
 			;
 				ConsId = type_ctor_info_const(M, N, A)
 			->
-				% When type specialization creates a procedure
-				% with a type substitution such as K=int, it
-				% leaves the type of TypeInfo_for_K as
-				% type_info, not type_ctor_info.
-				record_known_type_ctor_info(Var, M, N, A,
-					!Info)
+                % When type specialization creates a procedure with a type
+                % substitution such as K=int, it leaves the type of
+                % TypeInfo_for_K as type_info, not type_ctor_info.
+                record_known_type_ctor_info(Var, M, N, A, !Info)
 			;
-				error("size_prof__process_construct: "
-					++ "bad type_info")
+                unexpected(this_file, "process_construct: bad type_info")
 			)
 		; VarTypeCtorName = "type_ctor_info" ->
 			( ConsId = type_ctor_info_const(M, N, A) ->
-				record_known_type_ctor_info(Var, M, N, A,
-					!Info)
+                record_known_type_ctor_info(Var, M, N, A, !Info)
 			;
-				error("size_prof__process_construct: "
-					++ "bad type_ctor_info")
+                unexpected(this_file, "process_construct: bad type_ctor_info")
 			)
 		;
 			!:Info = !.Info
 		),
-		Unification = construct(Var, ConsId, Args, ArgModes,
-			How, Unique, no),
+        Unification = construct(Var, ConsId, Args, ArgModes, How, Unique, no),
 		GoalExpr = unify(LHS, RHS, UniMode, Unification, UnifyContext)
 	;
 		ConsId = cons(_Name, _Arity),
-		Args \= []
+        Args = [_ | _]
 	->
-		process_cons_construct(LHS, RHS, UniMode, UnifyContext,
-			Var, VarType, ConsId, Args, ArgModes, How,
-			Unique, GoalInfo, GoalExpr, !Info)
+        process_cons_construct(LHS, RHS, UniMode, UnifyContext, Var, VarType,
+            ConsId, Args, ArgModes, How, Unique, GoalInfo, GoalExpr, !Info)
 	;
 		% All ConsIds other than cons/2 with at least one argument
 		% construct terms that we consider zero-sized.
 		record_known_size(Var, 0, !Info),
-		Unification = construct(Var, ConsId, Args, ArgModes,
-			How, Unique, no),
+        Unification = construct(Var, ConsId, Args, ArgModes, How, Unique, no),
 		GoalExpr = unify(LHS, RHS, UniMode, Unification, UnifyContext)
 	).
 
@@ -677,8 +662,8 @@
 	( type_to_ctor_and_args(VarType, VarTypeCtorPrime, _VarTypeArgs) ->
 		VarTypeCtor = VarTypeCtorPrime
 	;
-		error("size_prof__process_deconstruct: "
-			++ "deconstructing term of variable type")
+        unexpected(this_file,
+            "process_deconstruct: deconstructing term of variable type")
 	),
 	type_ctor_module(!.Info ^ module_info, VarTypeCtor, VarTypeCtorModule),
 	type_ctor_name(!.Info ^ module_info, VarTypeCtor, VarTypeCtorName),
@@ -688,10 +673,9 @@
 		Goal0 = GoalExpr - _
 	;
 		ConsId = cons(_Name, _Arity),
-		Args \= []
+        Args = [_ | _]
 	->
-		process_cons_deconstruct(Var, Args, ArgModes,
-			Goal0, GoalExpr, !Info)
+        process_cons_deconstruct(Var, Args, ArgModes, Goal0, GoalExpr, !Info)
 	;
 		% All ConsIds other than cons/2 deconstruct terms that we
 		% consider zero-sized.
@@ -718,27 +702,28 @@
 		MaybeDynamicSizeVar = no,
 		require(unify(ArgGoals, []),
 			"process_cons_construct: nonempty ArgGoals"),
-		( NonDefinedArgs = [] ->
+        (
+            NonDefinedArgs = [],
 			record_known_size(Var, KnownSize, !Info)
 		;
+            NonDefinedArgs = [_ | _],
 			% The size of the term may change as some of its
 			% currently free arguments become bound.
 			true
 		),
-		Unification = construct(Var, ConsId, Args, ArgModes,
-			How, Unique, yes(known_size(KnownSize))),
+        Unification = construct(Var, ConsId, Args, ArgModes, How, Unique,
+            yes(known_size(KnownSize))),
 		GoalExpr = unify(LHS, RHS, UniMode, Unification, UnifyContext)
 	;
 		MaybeDynamicSizeVar = yes(SizeVar0),
-		generate_size_var(SizeVar0, KnownSize, Context,
-			SizeVar, SizeGoals, !Info),
-		Unification = construct(Var, ConsId, Args, ArgModes,
-			How, Unique, yes(dynamic_size(SizeVar))),
-		UnifyExpr = unify(LHS, RHS, UniMode, Unification,
-			UnifyContext),
+        generate_size_var(SizeVar0, KnownSize, Context, SizeVar, SizeGoals,
+            !Info),
+        Unification = construct(Var, ConsId, Args, ArgModes, How, Unique,
+            yes(dynamic_size(SizeVar))),
+        UnifyExpr = unify(LHS, RHS, UniMode, Unification, UnifyContext),
 		goal_info_get_nonlocals(GoalInfo0, NonLocals0),
 		set__insert(NonLocals0, SizeVar, NonLocals),
-		goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+        goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
 		UnifyGoal = UnifyExpr - GoalInfo,
 		Goals = list__condense([ArgGoals, SizeGoals, [UnifyGoal]]),
 		GoalExpr = conj(Goals)
@@ -763,8 +748,8 @@
 		GoalExpr = GoalExpr0
 	;
 		MaybeDynamicSizeVar = yes(SizeVar0),
-		generate_size_var(SizeVar0, KnownSize, Context,
-			SizeVar, SizeGoals, !Info),
+        generate_size_var(SizeVar0, KnownSize, Context, SizeVar, SizeGoals,
+            !Info),
 		% The increment_size primitive doesn't need Var's type_info,
 		% so we make it a no_type_info_builtin.
 		TermSizeProfBuiltin = mercury_term_size_prof_builtin_module,
@@ -773,22 +758,21 @@
 			[Var, SizeVar], [impure], [], !.Info ^ module_info,
 			Context, UpdateGoal),
 		% Put UnifyGoal first in case it fails.
-		Goals = list__condense([[UnifyGoal], ArgGoals, SizeGoals,
-			[UpdateGoal]]),
+        Goals = [UnifyGoal] ++ ArgGoals ++ SizeGoals ++ [UpdateGoal],
 		GoalExpr = conj(Goals)
 	).
 
 %-----------------------------------------------------------------------------%
 
-% Process the variables representing the fields being bound in a memory cell,
-% computing the contribution they make to the increase in size of that cell.
-% The increase is in two parts: the statically known part, and the part that
-% can be known only at runtime. We record the former in the KnownSize
-% accumulator and the latter in the MaybeSizeVar accumulator. We allocate
-% a variable to hold the dynamically-computed part of the size only if the
-% sum of the arguments' sizes is not static. In that case, the Goals we return
-% will be nonempty.
-
+    % Process the variables representing the fields being bound in a memory
+    % cell, computing the contribution they make to the increase in size of
+    % that cell. The increase is in two parts: the statically known part,
+    % and the part that can be known only at runtime. We record the former
+    % in the KnownSize accumulator and the latter in the MaybeSizeVar
+    % accumulator. We allocate a variable to hold the dynamically-computed part
+    % of the size only if the sum of the arguments' sizes is not static.
+    % In that case, the Goals we return will be nonempty.
+    %
 :- pred process_args(list(prog_var)::in, int::in, int::out,
 	maybe(prog_var)::in, maybe(prog_var)::out, prog_context::in,
 	list(hlds_goal)::out, info::in, info::out) is det.
@@ -802,23 +786,21 @@
 	; zero_size_type(Type, !.Info ^ module_info) ->
 		ArgGoals = []
 	;
-		make_type_info(Context, Type, TypeInfoVar, TypeInfoGoals,
+        make_type_info(Context, Type, TypeInfoVar, TypeInfoGoals, !Info),
+        make_size_goal(TypeInfoVar, Arg, Context, SizeGoal, !MaybeSizeVar,
 			!Info),
-		make_size_goal(TypeInfoVar, Arg, Context, SizeGoal,
-			!MaybeSizeVar, !Info),
 		list__append(TypeInfoGoals, [SizeGoal], ArgGoals)
 	),
-	process_args(Args, !KnownSize, !MaybeSizeVar, Context, LaterGoals,
-		!Info),
+    process_args(Args, !KnownSize, !MaybeSizeVar, Context, LaterGoals, !Info),
 	list__append(ArgGoals, LaterGoals, Goals).
 
 %-----------------------------------------------------------------------------%
 
-% Given that KnownSize is the static part of the sum of sizes of the fields
-% being defined and SizeVar0 is a variable containing the dynamic part,
-% return a variable SizeVar that contains their sum and the Goals needed to
-% compute it.
-
+    % Given that KnownSize is the static part of the sum of sizes of the fields
+    % being defined and SizeVar0 is a variable containing the dynamic part,
+    % return a variable SizeVar that contains their sum and the Goals needed to
+    % compute it.
+    %
 :- pred generate_size_var(prog_var::in, int::in, prog_context::in,
 	prog_var::out, list(hlds_goal)::out, info::in, info::out) is det.
 
@@ -831,8 +813,7 @@
 		VarTypes0 = !.Info ^ vartypes,
 		make_int_const_construction(KnownSize,
 			yes("KnownSize"), KnownSizeGoal, KnownSizeVar,
-			VarTypes0, VarTypes1,
-			VarSet0, VarSet1),
+            VarTypes0, VarTypes1, VarSet0, VarSet1),
 		!:Info = !.Info ^ varset := VarSet1,
 		!:Info = !.Info ^ vartypes := VarTypes1,
 		get_new_var(int_type, "FinalSizeVar", SizeVar, !Info),
@@ -847,10 +828,10 @@
 
 %-----------------------------------------------------------------------------%
 
-% Create a type_info for a given type as cheaply as possible, with the
-% cheapest methods involving the reuse of existing type_infos and/or
-% type_ctor_infos. Return the variable holding the type_info in TypeInfoVar,
-% and the goals needed to create it in TypeInfoGoals.
+    % Create a type_info for a given type as cheaply as possible, with the
+    % cheapest methods involving the reuse of existing type_infos and/or
+    % type_ctor_infos. Return the variable holding the type_info in
+    % TypeInfoVar, and the goals needed to create it in TypeInfoGoals.
 
 :- pred make_type_info(prog_context::in, (type)::in, prog_var::out,
 	list(hlds_goal)::out, info::in, info::out) is det.
@@ -864,18 +845,19 @@
 			TypeInfoVar, TypeInfoGoals, !Info)
 	; type_to_ctor_and_args(Type, TypeCtor, ArgTypes0) ->
 		canonicalize_type_args(TypeCtor, ArgTypes0, ArgTypes),
-		( ArgTypes = [] ->
-			make_type_ctor_info(TypeCtor, [], TypeCtorVar,
-				TypeCtorGoals, !Info),
+        (
+            ArgTypes = [],
+            make_type_ctor_info(TypeCtor, [], TypeCtorVar, TypeCtorGoals,
+                !Info),
 			TypeInfoVar = TypeCtorVar,
 			TypeInfoGoals = TypeCtorGoals
 		;
+            ArgTypes = [_ | _],
 			construct_type_info(Context, Type, TypeCtor, ArgTypes,
 				no, TypeInfoVar, TypeInfoGoals, !Info)
 		)
 	; Type = term__variable(TVar) ->
-		rtti_lookup_type_info_locn(!.Info ^ rtti_varmaps, TVar,
-			TVarLocn),
+        rtti_lookup_type_info_locn(!.Info ^ rtti_varmaps, TVar, TVarLocn),
 		(
 			TVarLocn = type_info(TypeInfoVar),
 			TypeInfoGoals = []
@@ -915,14 +897,14 @@
 		% type_to_ctor_and_args can fail only if Type is a type
 		% variable, or acts like one. The tests in our callers should
 		% have filtered out both cases.
-		error("size_prof__make_type_info: cannot happen")
+        unexpected(this_file, "size_prof__make_type_info: cannot happen")
 	).
 
-% Construct a type_info for Type = TypeCtor(ArgTypes), given that we know
-% there is no variable that currently holds a type_info for Type. Return
-% the variable holding the type_info in TypeInfoVar, and the goals needed
-% to create it in TypeInfoGoals.
-
+    % Construct a type_info for Type = TypeCtor(ArgTypes), given that we know
+    % there is no variable that currently holds a type_info for Type. Return
+    % the variable holding the type_info in TypeInfoVar, and the goals needed
+    % to create it in TypeInfoGoals.
+    %
 :- pred construct_type_info(prog_context::in, (type)::in, type_ctor::in,
 	list(type)::in, bool::in, prog_var::out, list(hlds_goal)::out,
 	info::in, info::out) is det.
@@ -932,16 +914,14 @@
 	list__map2_foldl(make_type_info(Context), ArgTypes,
 		ArgTypeInfoVars, ArgTypeInfoGoalLists, !Info),
 	ArgTypeInfoGoals = list__condense(ArgTypeInfoGoalLists),
-	make_type_ctor_info(TypeCtor, ArgTypes, TypeCtorVar, TypeCtorGoals,
-		!Info),
+    make_type_ctor_info(TypeCtor, ArgTypes, TypeCtorVar, TypeCtorGoals, !Info),
 	(
 		CtorIsVarArity = yes,
 		list__length(ArgTypes, Arity),
 		VarSet0 = !.Info ^ varset,
 		VarTypes0 = !.Info ^ vartypes,
-		make_int_const_construction(Arity, yes("TupleArity"),
-			ArityGoal, ArityVar, VarTypes0, VarTypes1,
-			VarSet0, VarSet1),
+        make_int_const_construction(Arity, yes("TupleArity"), ArityGoal,
+            ArityVar, VarTypes0, VarTypes1, VarSet0, VarSet1),
 		!:Info = !.Info ^ varset := VarSet1,
 		!:Info = !.Info ^ vartypes := VarTypes1,
 		FrontGoals = list__append(TypeCtorGoals, [ArityGoal]),
@@ -960,9 +940,8 @@
 	;
 		MaybePreferredVar = no
 	),
-	polymorphism__init_type_info_var(Type, ArgVars,
-		MaybePreferredVar, TypeInfoVar, TypeInfoGoal,
-		VarSet2, VarSet, VarTypes2, VarTypes,
+    polymorphism__init_type_info_var(Type, ArgVars, MaybePreferredVar,
+        TypeInfoVar, TypeInfoGoal, VarSet2, VarSet, VarTypes2, VarTypes,
 		RttiVarMaps0, RttiVarMaps),
 	!:Info = !.Info ^ varset := VarSet,
 	!:Info = !.Info ^ vartypes := VarTypes,
@@ -970,11 +949,11 @@
 	TypeInfoGoals = list__condense([ArgTypeInfoGoals, FrontGoals,
 		[TypeInfoGoal]]).
 
-% Create a type_ctor_info for a given type constructor as cheaply as possible,
-% with the cheapest method being the reuse of an existing type_ctor_info.
-% Return the variable holding the type_ctor_info in TypeCtorVar,
-% and the goals needed to create it in TypeCtorGoals.
-
+    % Create a type_ctor_info for a given type constructor as cheaply as
+    % possible, with the cheapest method being the reuse of an existing
+    % type_ctor_info. Return the variable holding the type_ctor_info in
+    % TypeCtorVar, and the goals needed to create it in TypeCtorGoals.
+    %
 :- pred make_type_ctor_info(type_ctor::in, list(type)::in, prog_var::out,
 	list(hlds_goal)::out, info::in, info::out) is det.
 
@@ -984,11 +963,10 @@
 		TypeCtorGoals = []
 	;
 		( 
-			type_ctor_is_higher_order(TypeCtor, Purity,
-				PredOrFunc, EvalMethod)
+            type_ctor_is_higher_order(TypeCtor, Purity, PredOrFunc, EvalMethod)
 		->
-			construct_higher_order_type(Purity, PredOrFunc,	
-				EvalMethod, TypeArgs, Type)
+            construct_higher_order_type(Purity, PredOrFunc, EvalMethod,
+                TypeArgs, Type)
 		;
 			construct_type(TypeCtor, [], Type)
 		),
@@ -1007,15 +985,15 @@
 
 %-----------------------------------------------------------------------------%
 
-% Generate a goal that looks up the size of Arg at runtime, given that the
-% type_info of Arg's type is in TypeInfoVar.
-%
-% We ultimately always want to compute the sum of the sizes of the fields
-% being defined, so if we have previously looked up the sizes of other fields,
-% then combine the operation of looking up Arg's size with adding that size to
-% the sum of the (dynamic) sizes so far: measure_size_acc does both these
-% operations.
-
+    % Generate a goal that looks up the size of Arg at runtime, given that the
+    % type_info of Arg's type is in TypeInfoVar.
+    %
+    % We ultimately always want to compute the sum of the sizes of the fields
+    % being defined, so if we have previously looked up the sizes of other
+    % fields, then combine the operation of looking up Arg's size with adding
+    % that size to the sum of the (dynamic) sizes so far: measure_size_acc
+    % does both these operations.
+    %
 :- pred make_size_goal(prog_var::in, prog_var::in, prog_context::in,
 	hlds_goal::out, maybe(prog_var)::in, maybe(prog_var)::out,
 	info::in, info::out) is det.
@@ -1040,9 +1018,9 @@
 
 %---------------------------------------------------------------------------%
 
-% Create a new variable with a name constructed from Prefix and the variable
-% number.
-
+    % Create a new variable with a name constructed from Prefix and the
+    % variable number.
+    %
 :- pred get_new_var((type)::in, string::in, prog_var::out,
 	info::in, info::out) is det.
 
@@ -1060,23 +1038,24 @@
 
 %---------------------------------------------------------------------------%
 
-% These predicates record information about the procedure body (that was
-% either there originally or was made true by our transformation) for later
-% use in optimizating the transformation of the rest of the procedure body.
-%
-% The reason why the implementation uses map__set instead of map__det_insert
-% is that it is possible for Var to already exist in the maps. This can happen
-% e.g. when each branch of a branched structure generates a value of an
-% existential type, and thus also generates the type_info describing that type.
-% The first branch will insert the variable holding that type_info into the
-% maps, and the later branches will be given the resulting map as guidance.
-%
-% We override any old settings here, for use in the rest of the current
-% branch. Other branches will do likewise. The correct handling of the code
-% after the branched structure is ensured by process_goal returning only
-% the common subsets of the maps constructed by the various branches to
-% be used when processing the following code.
-
+    % These predicates record information about the procedure body (that was
+    % either there originally or was made true by our transformation) for later
+    % use in optimizating the transformation of the rest of the procedure body.
+    %
+    % The reason why the implementation uses map__set instead of
+    % map__det_insert is that it is possible for Var to already exist in the
+    % maps. This can happen e.g. when each branch of a branched structure
+    % generates a value of an existential type, and thus also generates
+    % the type_info describing that type. The first branch will insert the
+    % variable holding that type_info into the maps, and the later branches
+    % will be given the resulting map as guidance.
+    %
+    % We override any old settings here, for use in the rest of the current
+    % branch. Other branches will do likewise. The correct handling of the code
+    % after the branched structure is ensured by process_goal returning only
+    % the common subsets of the maps constructed by the various branches to
+    % be used when processing the following code.
+    %
 :- pred record_known_type_ctor_info(prog_var::in, module_name::in, string::in,
 	int::in, info::in, info::out) is det.
 
@@ -1097,13 +1076,9 @@
 	RevTypeCtorMap0 = !.Info ^ rev_type_ctor_map,
 	( map__search(RevTypeCtorMap0, TypeCtorInfoVar, TypeCtor0) ->
 		RevTypeInfoMap0 = !.Info ^ rev_type_info_map,
-		(
-			list__map(map__search(RevTypeInfoMap0),
-				ArgTypeInfoVars, ArgTypes)
-		->
+        ( list__map(map__search(RevTypeInfoMap0), ArgTypeInfoVars, ArgTypes) ->
 			list__length(ArgTypes, Arity),
-			% Just in case TypeCtorInfo0 has fake arity,
-			% e.g. if it is a tuple.
+            % Just in case TypeCtorInfo0 has fake arity, e.g. if it is a tuple.
 			TypeCtor0 = SymName - _DeclArity,
 			TypeCtor1 = SymName - Arity,
 			construct_type(TypeCtor1, ArgTypes, Type),
@@ -1168,18 +1143,19 @@
 
 %---------------------------------------------------------------------------%
 
-% We must ensure that we record that a branched control structure is considered
-% to generate a type_ctor_info or type_info variable only if all the branches
-% generate it. The code above takes the intersections of the forward maps
-% (type to type_info or type_ctor_info var maps) produced by different branches
-% directly, but calls update_rev_maps to ensure that the reverse maps
-%
-% (a) contain only entries that are also in the forward maps, i.e. do not
-%     contain entries that the intersection process removed, and
-% (b) do not contain entries derived from inconsistent forward map entries
-%     (since a forward map can say that e.g. both the type int and the type
-%     constructor int/0 have their typeinfo in the same variable).
-
+    % We must ensure that we record that a branched control structure is
+    % considered to generate a type_ctor_info or type_info variable only
+    % if all the branches generate it. The code above takes the intersections
+    % of the forward maps (type to type_info or type_ctor_info var maps)
+    % produced by different branches directly, but calls update_rev_maps
+    % to ensure that the reverse maps
+    %
+    % (a) contain only entries that are also in the forward maps, i.e. do not
+    %     contain entries that the intersection process removed, and
+    % (b) do not contain entries derived from inconsistent forward map entries
+    %     (since a forward map can say that e.g. both the type int and the type
+    %     constructor int/0 have their typeinfo in the same variable).
+    %
 :- pred update_rev_maps(info::in, info::out) is det.
 
 update_rev_maps(!Info) :-
@@ -1221,16 +1197,17 @@
 
 %---------------------------------------------------------------------------%
 
-% During the processing of a branched control structure, we add entries to the
-% target type_info map in an effort to encourage different branches to use the
-% same variable to store the type_info for the same type, since this increases
-% the probability that all branches define a type_info for the type and that
-% thus we will be able to use the variable holding that type_info after the
-% branched control structure without recreating it. However, if some branches
-% define the target variable but others don't, then the branched control
-% structure cannot define the variable for later code. We must therefore
-% remove the variable from the target type_info map used by later code.
-
+    % During the processing of a branched control structure, we add entries
+    % to the target type_info map in an effort to encourage different branches
+    % to use the same variable to store the type_info for the same type,
+    % since this increases the probability that all branches define a type_info
+    % for the type and that thus we will be able to use the variable holding
+    % that type_info after the branched control structure without recreating
+    % it. However, if some branches define the target variable but others
+    % don't, then the branched control structure cannot define the variable
+    % for later code. We must therefore remove the variable from the target
+    % type_info map used by later code.
+    %
 :- pred update_target_map(info::in, info::out) is det.
 
 update_target_map(!Info) :-
@@ -1244,13 +1221,11 @@
 :- pred include_in_target_map(type_info_map::in, pair(type, prog_var)::in,
 	type_info_map::in, type_info_map::out) is det.
 
-include_in_target_map(TypeInfoMap, Type - TypeInfoVar,
-		TargetTypeInfoMap0, TargetTypeInfoMap) :-
+include_in_target_map(TypeInfoMap, Type - TypeInfoVar, !TargetTypeInfoMap) :-
 	( map__search(TypeInfoMap, Type, TypeInfoVar) ->
-		map__det_insert(TargetTypeInfoMap0, Type, TypeInfoVar,
-			TargetTypeInfoMap)
+        svmap__det_insert(Type, TypeInfoVar, !TargetTypeInfoMap)
 	;
-		TargetTypeInfoMap = TargetTypeInfoMap0
+        true
 	).
 
 %---------------------------------------------------------------------------%
@@ -1279,11 +1254,11 @@
 	;
 		Args = [],
 		Modes = [_ | _],
-		error("size_prof__find_defined_args: length mismatch")
+        unexpected(this_file, "size_prof__find_defined_args: length mismatch")
 	;
 		Args = [_ | _],
 		Modes = [],
-		error("size_prof__find_defined_args: length mismatch")
+        unexpected(this_file, "size_prof__find_defined_args: length mismatch")
 	;
 		Args = [FirstArg | LaterArgs],
 		Modes = [FirstMode | LaterModes],
@@ -1323,5 +1298,11 @@
 	; VarTypeCtorName = "typeclass_info"
 	; VarTypeCtorName = "base_typeclass_info"
 	).
+
+%---------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "size_prof.m".
 
 %---------------------------------------------------------------------------%
Index: compiler/state_var.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/state_var.m,v
retrieving revision 1.3
diff -u -b -r1.3 state_var.m
--- compiler/state_var.m	18 Aug 2005 07:57:52 -0000	1.3
+++ compiler/state_var.m	28 Aug 2005 00:17:40 -0000
@@ -486,7 +486,7 @@
         Unification = Unification0
     ;
         MaybeFeature = yes(Feature),
-        goal_add_feature(Unification0, Feature, Unification)
+        goal_add_feature(Feature, Unification0, Unification)
     ).
 
 %-----------------------------------------------------------------------------%
Index: compiler/store_alloc.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/store_alloc.m,v
retrieving revision 1.90
diff -u -b -r1.90 store_alloc.m
--- compiler/store_alloc.m	24 Mar 2005 05:34:15 -0000	1.90
+++ compiler/store_alloc.m	28 Aug 2005 01:19:40 -0000
@@ -1,22 +1,24 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1994-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
 %-----------------------------------------------------------------------------%
-
+%
 % Original author: conway.
 % Extensive modification by zs.
-
+%
 % Allocates the storage location for each live variable at the end of
 % each branched structure, so that the code generator will generate code
 % which puts the variable in the same place in each branch.
-
+%
 % This module requires arg_infos and livenesses to have already been computed,
 % and stack slots allocated.
-
+%
 % If the appropriate option is set, the code calls the follow_vars module
 % to help guide its decisions.
-
+%
 % See compiler/notes/allocation.html for a description of the framework that
 % this pass operates within.
 
@@ -72,16 +74,13 @@
 	( RunType = final_allocation ->
 		proc_info_goal(!.ProcInfo, Goal0),
 
-		find_final_follow_vars(!.ProcInfo,
-			FollowVarsMap0, NextNonReserved0),
+        find_final_follow_vars(!.ProcInfo, FollowVarsMap0, NextNonReserved0),
 		proc_info_vartypes(!.ProcInfo, VarTypes),
 		find_follow_vars_in_goal(Goal0, Goal1, VarTypes, ModuleInfo,
-			FollowVarsMap0, FollowVarsMap,
-			NextNonReserved0, NextNonReserved),
+            FollowVarsMap0, FollowVarsMap, NextNonReserved0, NextNonReserved),
 		Goal1 = GoalExpr1 - GoalInfo1,
 		FollowVars = abs_follow_vars(FollowVarsMap, NextNonReserved),
-		goal_info_set_follow_vars(GoalInfo1, yes(FollowVars),
-			GoalInfo2),
+        goal_info_set_follow_vars(yes(FollowVars), GoalInfo1, GoalInfo2),
 		Goal2 = GoalExpr1 - GoalInfo2
 	;
 		proc_info_goal(!.ProcInfo, Goal2)
@@ -115,8 +114,8 @@
 	--->	store_alloc_info(
 			module_info		:: module_info,
 			stack_slots		:: stack_slots
-						% maps each var to its stack
-						% slot (if it has one)
+                                % Maps each var to its stack slot
+                                % (if it has one).
 		).
 
 :- type where_stored	== set(lval).	% These lvals may contain var() rvals.
@@ -157,7 +156,7 @@
 		),
 		store_alloc_allocate_storage(MappedVars, StoreAllocInfo,
 			AdvisoryStoreMap, StoreMap),
-		goal_info_set_store_map(GoalInfo0, StoreMap, GoalInfo)
+        goal_info_set_store_map(StoreMap, GoalInfo0, GoalInfo)
 	;
 		GoalInfo = GoalInfo0
 	).
@@ -165,7 +164,7 @@
 %-----------------------------------------------------------------------------%
 
 	% Here we process each of the different sorts of goals.
-
+    %
 :- pred store_alloc_in_goal_2(hlds_goal_expr::in, hlds_goal_expr::out,
 	liveness_info::in, liveness_info::out,
 	last_locns::in, last_locns::out, set(prog_var)::in, set(prog_var)::in,
@@ -247,7 +246,7 @@
 store_alloc_in_conj([Goal0 | Goals0], [Goal | Goals], !Liveness, !LastLocns,
 		ResumeVars0, StoreAllocInfo) :-
 	(
-			% XXX should be threading the instmap
+        % XXX should be threading the instmap.
 		Goal0 = _ - GoalInfo,
 		goal_info_get_instmap_delta(GoalInfo, InstMapDelta),
 		instmap_delta_is_unreachable(InstMapDelta)
@@ -345,26 +344,26 @@
 	%
 	% generate a store map that maps every live variable to its own
 	% real location.
-
+    %
 :- pred store_alloc_allocate_storage(list(prog_var)::in, store_alloc_info::in,
 	abs_store_map::in, abs_store_map::out) is det.
 
-store_alloc_allocate_storage(LiveVars, StoreAllocInfo, FollowVars, StoreMap) :-
+store_alloc_allocate_storage(LiveVars, StoreAllocInfo, FollowVars,
+        !:StoreMap) :-
 
 	% This addresses point 1
 	map__keys(FollowVars, FollowKeys),
-	store_alloc_remove_nonlive(FollowKeys, LiveVars, FollowVars,
-		StoreMap0),
+    store_alloc_remove_nonlive(FollowKeys, LiveVars, FollowVars, !:StoreMap),
 
 	% This addresses points 3 and 4
-	map__keys(StoreMap0, StoreVars),
+    map__keys(!.StoreMap, StoreVars),
 	set__init(SeenLvals0),
 	store_alloc_handle_conflicts_and_nonreal(StoreVars, 1, N,
-		SeenLvals0, SeenLvals, StoreMap0, StoreMap1),
+        SeenLvals0, SeenLvals, !StoreMap),
 
 	% This addresses point 2
 	store_alloc_allocate_extras(LiveVars, N, SeenLvals, StoreAllocInfo,
-		StoreMap1, StoreMap).
+        !StoreMap).
 
 :- pred store_alloc_remove_nonlive(list(prog_var)::in, list(prog_var)::in,
 	abs_store_map::in, abs_store_map::out) is det.
Index: compiler/superhomogeneous.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/superhomogeneous.m,v
retrieving revision 1.2
diff -u -b -r1.2 superhomogeneous.m
--- compiler/superhomogeneous.m	12 Aug 2005 02:33:09 -0000	1.2
+++ compiler/superhomogeneous.m	28 Aug 2005 00:27:54 -0000
@@ -149,7 +149,7 @@
         substitute_state_var_mappings(Args0, Args, !VarSet, !SInfo, !IO),
         insert_arg_unifications_2(HeadVars, Args, Context, ArgContext,
             0, Goals0, Goals, !VarSet, !ModuleInfo, !QualInfo, !SInfo, !IO),
-        goal_info_set_context(GoalInfo0, Context, GoalInfo),
+        goal_info_set_context(Context, GoalInfo0, GoalInfo),
         conj_list_to_goal(Goals, GoalInfo, !:Goal)
     ).
 
@@ -186,8 +186,7 @@
     ).
 
 insert_arg_unifications_with_supplied_contexts(ArgVars, ArgTerms0, ArgContexts,
-        Context, !Goal, !VarSet, !ModuleInfo, !QualInfo, !SInfo,
-        !IO) :-
+        Context, !Goal, !VarSet, !ModuleInfo, !QualInfo, !SInfo, !IO) :-
     (
         ArgVars = []
     ;
@@ -199,7 +198,7 @@
         insert_arg_unifications_with_supplied_contexts_2(ArgVars, ArgTerms,
             ArgContexts, Context, GoalList0, GoalList, !VarSet,
             !ModuleInfo, !QualInfo, !SInfo, !IO),
-        goal_info_set_context(GoalInfo0, Context, GoalInfo),
+        goal_info_set_context(Context, GoalInfo0, GoalInfo),
         conj_list_to_goal(GoalList, GoalInfo, !:Goal)
     ).
 
@@ -511,7 +510,7 @@
             Vars1, Modes, Det, ParsedGoal, Context, MainContext, SubContext,
             Goal0, !VarSet, !ModuleInfo, !QualInfo, !.SInfo, !IO),
         Goal0 = GoalExpr - GoalInfo0,
-        add_goal_info_purity_feature(GoalInfo0, Purity, GoalInfo),
+        add_goal_info_purity_feature(Purity, GoalInfo0, GoalInfo),
         Goal = GoalExpr - GoalInfo
     ;
         % handle if-then-else expressions
@@ -620,7 +619,7 @@
             make_atomic_unification(X, functor(ConsId, no, []), Context,
                 MainContext, SubContext, Goal0, !QualInfo),
             Goal0 = GoalExpr - GoalInfo0,
-            add_goal_info_purity_feature(GoalInfo0, Purity, GoalInfo),
+            add_goal_info_purity_feature(Purity, GoalInfo0, GoalInfo),
             % We could attach the from_ground_term feature to Goal,
             % but there would be no gain from doing so, whereas the
             % increase would lead to a slight increase in memory and time
@@ -644,7 +643,7 @@
                     !ModuleInfo, !QualInfo, !SInfo, !IO)
             ;
                 Goal0 = GoalExpr0 - GoalInfo0,
-                add_goal_info_purity_feature(GoalInfo0, Purity, GoalInfo1),
+                add_goal_info_purity_feature(Purity, GoalInfo0, GoalInfo1),
                 Goal1 = GoalExpr0 - GoalInfo1,
                 insert_arg_unifications(HeadVars, FunctorArgs, FunctorContext,
                     ArgContext, Goal1, Goal2, !VarSet,
Index: compiler/table_gen.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/table_gen.m,v
retrieving revision 1.88
diff -u -b -r1.88 table_gen.m
--- compiler/table_gen.m	27 Aug 2005 09:41:59 -0000	1.88
+++ compiler/table_gen.m	28 Aug 2005 03:07:30 -0000
@@ -697,7 +697,7 @@
         goal_info_get_instmap_delta(OrigGoalInfo, InstMapDelta),
         create_renaming(OutputVars, InstMapDelta, !VarTypes, !VarSet,
             Unifies, NewVars, Renaming),
-        rename_vars_in_goal(OrigGoal, Renaming, RenamedOrigGoal),
+        rename_vars_in_goal(Renaming, OrigGoal, RenamedOrigGoal),
 
         ThenGoalExpr = conj(list__append(Unifies, [MarkInactiveGoal])),
         list__append([TableTipVar | OutputVars], NewVars, ThenVars),
@@ -718,7 +718,7 @@
         FirstGoalExpr = conj([OrigGoal, AfterGoal]),
         goal_info_get_nonlocals(OrigGoalInfo, OrigGINonLocals),
         set__insert(OrigGINonLocals, TableTipVar, FirstNonlocals),
-        goal_info_set_nonlocals(OrigGoalInfo, FirstNonlocals, FirstGoalInfo),
+        goal_info_set_nonlocals(FirstNonlocals, OrigGoalInfo, FirstGoalInfo),
         FirstGoal = FirstGoalExpr - FirstGoalInfo,
         InactiveGoalExpr = disj([FirstGoal, MarkInactiveFailGoal])
     ),
@@ -935,7 +935,7 @@
         CodeModel = model_semi,
         create_renaming(OutputVars, OrigInstMapDelta, !VarTypes, !VarSet,
             Unifies, NewVars, Renaming),
-        rename_vars_in_goal(OrigGoal, Renaming, RenamedOrigGoal),
+        rename_vars_in_goal(Renaming, OrigGoal, RenamedOrigGoal),
 
         ThenGoalExpr = conj(list__append(Unifies, SaveAnswerGoals)),
         list__append([TableTipVar | OutputVars], NewVars, ThenVars),
@@ -1052,7 +1052,7 @@
     OrigSaveExpr = conj([OrigGoal | SaveAnswerGoals]),
     set__insert(OrigNonLocals, RecordVar, OrigSaveNonLocals),
     create_instmap_delta([OrigGoal | SaveAnswerGoals], OrigSaveIMD0),
-    instmap_delta_restrict(OrigSaveIMD0, OrigSaveNonLocals, OrigSaveIMD),
+    instmap_delta_restrict(OrigSaveNonLocals, OrigSaveIMD0, OrigSaveIMD),
     goal_info_init_hide(OrigSaveNonLocals, OrigSaveIMD, nondet, impure,
         Context, OrigSaveGoalInfo),
     OrigSaveGoal = OrigSaveExpr - OrigSaveGoalInfo,
@@ -1278,8 +1278,8 @@
         set__insert_list(RestoreAnswer0NonLocals,
             [IoStateAssignFromVar, IoStateAssignToVar],
             RestoreAnswerNonLocals),
-        instmap_delta_restrict(RestoreAnswerInstMapDelta0,
-            RestoreAnswerNonLocals, RestoreAnswerInstMapDelta),
+        instmap_delta_restrict(RestoreAnswerNonLocals,
+            RestoreAnswerInstMapDelta0, RestoreAnswerInstMapDelta),
         goal_info_init_hide(RestoreAnswerNonLocals,
             RestoreAnswerInstMapDelta, det, semipure, Context,
             RestoreAnswerGoalInfo),
@@ -1308,12 +1308,12 @@
     CallSaveAnswerGoalExpr = conj(CallSaveAnswerGoalList),
     create_instmap_delta(CallSaveAnswerGoalList, CallSaveAnswerInstMapDelta0),
     set__insert(OrigNonLocals, TipVar, CallSaveAnswerNonLocals),
-    instmap_delta_restrict(CallSaveAnswerInstMapDelta0,
-        CallSaveAnswerNonLocals, CallSaveAnswerInstMapDelta),
+    instmap_delta_restrict(CallSaveAnswerNonLocals,
+        CallSaveAnswerInstMapDelta0, CallSaveAnswerInstMapDelta),
     goal_info_init_hide(CallSaveAnswerNonLocals, CallSaveAnswerInstMapDelta,
         det, impure, Context, CallSaveAnswerGoalInfo0),
-    goal_info_add_feature(CallSaveAnswerGoalInfo0, hide_debug_event,
-        CallSaveAnswerGoalInfo),
+    goal_info_add_feature(hide_debug_event,
+        CallSaveAnswerGoalInfo0, CallSaveAnswerGoalInfo),
     CallSaveAnswerGoal = CallSaveAnswerGoalExpr - CallSaveAnswerGoalInfo,
 
     GenIfNecGoalExpr = if_then_else([], OccurredGoal,
@@ -1321,8 +1321,8 @@
     create_instmap_delta([OccurredGoal, RestoreAnswerGoal,
         CallSaveAnswerGoal], GenIfNecInstMapDelta0),
     set__insert(OrigNonLocals, TipVar, GenIfNecNonLocals),
-    instmap_delta_restrict(GenIfNecInstMapDelta0, GenIfNecNonLocals,
-        GenIfNecInstMapDelta),
+    instmap_delta_restrict(GenIfNecNonLocals,
+        GenIfNecInstMapDelta0, GenIfNecInstMapDelta),
     goal_info_init_hide(GenIfNecNonLocals, GenIfNecInstMapDelta, det,
         impure, Context, GenIfNecGoalInfo),
     GenIfNecGoal = GenIfNecGoalExpr - GenIfNecGoalInfo,
@@ -1332,8 +1332,8 @@
         CheckAndGenAnswerInstMapDelta0),
     set__insert_list(OrigNonLocals, [TableVar, CounterVar, StartVar],
         CheckAndGenAnswerNonLocals),
-    instmap_delta_restrict(CheckAndGenAnswerInstMapDelta0,
-        CheckAndGenAnswerNonLocals, CheckAndGenAnswerInstMapDelta),
+    instmap_delta_restrict(CheckAndGenAnswerNonLocals,
+        CheckAndGenAnswerInstMapDelta0, CheckAndGenAnswerInstMapDelta),
     goal_info_init_hide(CheckAndGenAnswerNonLocals,
         CheckAndGenAnswerInstMapDelta, det, impure, Context,
         CheckAndGenAnswerGoalInfo),
@@ -1344,7 +1344,7 @@
         OrigGoal),
     create_instmap_delta([InRangeGoal, CheckAndGenAnswerGoal, OrigGoal],
         BodyInstMapDelta0),
-    instmap_delta_restrict(BodyInstMapDelta0, OrigNonLocals, BodyInstMapDelta),
+    instmap_delta_restrict(OrigNonLocals, BodyInstMapDelta0, BodyInstMapDelta),
     goal_info_init_hide(OrigNonLocals, BodyInstMapDelta, det, impure,
         Context, BodyGoalInfo),
     Goal = BodyGoalExpr - BodyGoalInfo.
@@ -1439,7 +1439,7 @@
     MainExpr = conj([OrigGoal | SaveAnswerGoals]),
     set__insert_list(OrigNonLocals, [SubgoalVar, StatusVar], MainNonLocals),
     create_instmap_delta([OrigGoal | SaveAnswerGoals], MainIMD0),
-    instmap_delta_restrict(MainIMD0, MainNonLocals, MainIMD),
+    instmap_delta_restrict(MainNonLocals, MainIMD0, MainIMD),
     goal_info_init_hide(MainNonLocals, MainIMD, nondet, impure, Context,
         MainGoalInfo),
     MainGoal = MainExpr - MainGoalInfo,
@@ -1457,7 +1457,7 @@
         case(cons(qualified(TB, "mm_active"), 0), SuspendGoal)
     ],
     SwitchExpr = switch(StatusVar, cannot_fail, SwitchArms),
-    goal_info_add_feature(MainGoalInfo, hide_debug_event, SwitchGoalInfo),
+    goal_info_add_feature(hide_debug_event, MainGoalInfo, SwitchGoalInfo),
     SwitchGoal = SwitchExpr - SwitchGoalInfo,
 
     GoalExpr = conj([LookUpGoal, SwitchGoal]),
@@ -1721,7 +1721,7 @@
     set__insert(OrigNonLocals, GeneratorVar, NonLocals),
     goal_info_init(NonLocals, OrigInstMapDelta, Detism, impure, Context,
         GoalInfo0),
-    goal_info_add_feature(GoalInfo0, hide_debug_event, GoalInfo),
+    goal_info_add_feature(hide_debug_event, GoalInfo0, GoalInfo),
     Goal = GoalExpr - GoalInfo,
     proc_info_set_goal(Goal, !ProcInfo),
 
@@ -2084,7 +2084,7 @@
     ShroudedPredProcId = shroud_pred_proc_id(proc(PredId, ProcId)),
     ConsId = tabling_pointer_const(ShroudedPredProcId),
     make_const_construction(PredTableVar, ConsId, GoalExpr - GoalInfo0),
-    goal_info_add_feature(GoalInfo0, impure, GoalInfo),
+    goal_info_add_feature(impure, GoalInfo0, GoalInfo),
     Goal = GoalExpr - GoalInfo.
 
 :- pred attach_call_table_tip(hlds_goal::in, hlds_goal::out) is det.
@@ -2092,7 +2092,7 @@
 attach_call_table_tip(GoalExpr - GoalInfo0, GoalExpr - GoalInfo) :-
     goal_info_get_features(GoalInfo0, Features0),
     set__insert(Features0, call_table_gen, Features),
-    goal_info_set_features(GoalInfo0, Features, GoalInfo).
+    goal_info_set_features(Features, GoalInfo0, GoalInfo).
 
 %-----------------------------------------------------------------------------%
 
@@ -3252,7 +3252,7 @@
         GoalInfo) :-
     goal_info_init(NonLocals, InstmapDelta, Detism, Purity, Context,
         GoalInfo0),
-    goal_info_add_feature(GoalInfo0, hide_debug_event, GoalInfo).
+    goal_info_add_feature(hide_debug_event, GoalInfo0, GoalInfo).
 
 %-----------------------------------------------------------------------------%
 
Index: compiler/tupling.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/tupling.m,v
retrieving revision 1.9
diff -u -b -r1.9 tupling.m
--- compiler/tupling.m	12 Aug 2005 05:14:16 -0000	1.9
+++ compiler/tupling.m	28 Aug 2005 03:07:43 -0000
@@ -713,7 +713,7 @@
 	insert_proc_start_deconstruction(Goal1, Goal2,
 		VarSet1, VarSet, VarTypes1, VarTypes,
 		RenameMapB, ProcStartInsert),
-	rename_vars_in_goal(Goal2, RenameMapB, Goal3),
+	rename_vars_in_goal(RenameMapB, Goal2, Goal3),
 
 	map__merge(RenameMapA, RenameMapB, RenameMap),
 	apply_headvar_correction(set__from_list(HeadVars), RenameMap,
Index: compiler/typecheck.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/typecheck.m,v
retrieving revision 1.374
diff -u -b -r1.374 typecheck.m
--- compiler/typecheck.m	12 Aug 2005 05:14:16 -0000	1.374
+++ compiler/typecheck.m	27 Aug 2005 16:32:26 -0000
@@ -884,7 +884,7 @@
             Context, explicit, [], Goal0),
         Goal0 = GoalExpr - GoalInfo0,
         set__list_to_set(HeadVars, NonLocals),
-        goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+        goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
         Goal = GoalExpr - GoalInfo,
         ProcIds = [], % the clause applies to all procedures.
         Clause = clause(ProcIds, Goal, mercury, Context),
@@ -933,9 +933,8 @@
             VarSet0, VarSet, map__init, Subst, [], RevConj),
 
         goal_info_get_nonlocals(GoalInfo0, NonLocals0),
-        goal_util__rename_vars_in_var_set(NonLocals0, no,
-            Subst, NonLocals),
-        goal_info_set_nonlocals(GoalInfo0, NonLocals, GoalInfo),
+        goal_util__rename_vars_in_var_set(no, Subst, NonLocals0, NonLocals),
+        goal_info_set_nonlocals(NonLocals, GoalInfo0, GoalInfo),
         conj_list_to_goal(list__reverse(RevConj), GoalInfo, Goal),
 
         apply_partial_map_to_list(HeadVars0, Subst, HeadVars),
@@ -1270,7 +1269,7 @@
     term__context_init(EmptyContext),
     ( Context = EmptyContext ->
         typecheck_info_get_context(!.Info, EnclosingContext),
-        goal_info_set_context(GoalInfo0, EnclosingContext, GoalInfo)
+        goal_info_set_context(EnclosingContext, GoalInfo0, GoalInfo)
     ;
         GoalInfo = GoalInfo0,
         typecheck_info_set_context(Context, !Info)
Index: compiler/unify_proc.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/unify_proc.m,v
retrieving revision 1.148
diff -u -b -r1.148 unify_proc.m
--- compiler/unify_proc.m	15 Aug 2005 07:18:31 -0000	1.148
+++ compiler/unify_proc.m	27 Aug 2005 14:54:33 -0000
@@ -906,7 +906,7 @@
         explicit, [], UnifyGoal),
 
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     conj_list_to_goal([Cast1Goal, Cast2Goal, UnifyGoal], GoalInfo, Goal),
     unify_proc__quantify_clauses_body([H1, H2], Goal, Context, Clauses, !Info).
 
@@ -999,7 +999,7 @@
                     [Res, CastVar1, CastVar2], Context, CompareGoal, !Info),
 
                 goal_info_init(GoalInfo0),
-                goal_info_set_context(GoalInfo0, Context, GoalInfo),
+                goal_info_set_context(Context, GoalInfo0, GoalInfo),
                 conj_list_to_goal([Cast1Goal, Cast2Goal,
                     CompareGoal], GoalInfo, Goal),
                 unify_proc__quantify_clauses_body([Res, H1, H2], Goal,
@@ -1145,7 +1145,7 @@
         Context, CompareGoal, !Info),
 
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     conj_list_to_goal([Cast1Goal, Cast2Goal, CompareGoal], GoalInfo, Goal),
     unify_proc__quantify_clauses_body([Res, H1, H2], Goal, Context, Clauses,
         !Info).
@@ -1241,8 +1241,8 @@
         unify_proc__info_new_named_var(int_type, "CastY", CastY, !Info),
         generate_cast(unsafe_type_cast, X, CastX, Context, CastXGoal0),
         generate_cast(unsafe_type_cast, Y, CastY, Context, CastYGoal0),
-        goal_add_feature(CastXGoal0, keep_constant_binding, CastXGoal),
-        goal_add_feature(CastYGoal0, keep_constant_binding, CastYGoal),
+        goal_add_feature(keep_constant_binding, CastXGoal0, CastXGoal),
+        goal_add_feature(keep_constant_binding, CastYGoal0, CastYGoal),
         create_atomic_unification(CastY, var(CastX), Context,
             explicit, [], UnifyY_Goal),
         GoalList = [UnifyX_Goal, CastXGoal, CastYGoal, UnifyY_Goal]
@@ -1258,7 +1258,7 @@
         GoalList = [UnifyX_Goal, UnifyY_Goal | UnifyArgs_Goals]
     ),
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     conj_list_to_goal(GoalList, GoalInfo, Goal),
     unify_proc__quantify_clause_body([X, Y], Goal, Context, Clause, !Info),
     unify_proc__generate_du_unify_clauses(Ctors, X, Y, Context, Clauses,
@@ -1313,7 +1313,7 @@
         Context, explicit, [], UnifyIndex_Goal),
     GoalList = [UnifyX_Goal, UnifyIndex_Goal],
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     conj_list_to_goal(GoalList, GoalInfo, Goal),
     unify_proc__quantify_clause_body([X, Index], Goal, Context, Clause, !Info),
     unify_proc__generate_du_index_clauses(Ctors, X, Index, Context, N + 1,
@@ -1414,7 +1414,7 @@
     unify_proc__generate_du_quad_compare_clauses_1(Ctors, Ctors, R, X, Y,
         Context, [], Cases, !Info),
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     disj_list_to_goal(Cases, GoalInfo, Goal),
     HeadVars = [R, X, Y],
     unify_proc__quantify_clauses_body(HeadVars, Goal, Context, Clauses, !Info).
@@ -1526,7 +1526,7 @@
     unify_proc__info_new_var(comparison_result_type, R, !Info),
 
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
 
     instmap_delta_from_assoc_list([X_Index - ground(shared, none)],
         X_InstmapDelta),
@@ -1645,7 +1645,7 @@
         GoalList = [UnifyX_Goal, UnifyY_Goal, CompareArgs_Goal]
     ),
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     conj_list_to_goal(GoalList, GoalInfo, Case).
 
 :- pred unify_proc__generate_asymmetric_compare_case(constructor::in,
@@ -1672,7 +1672,7 @@
         Context, explicit, [], ReturnResult),
     GoalList = [UnifyX_Goal, UnifyY_Goal, ReturnResult],
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     conj_list_to_goal(GoalList, GoalInfo, Case).
 
     % unify_proc__compare_args: for a constructor such as
@@ -1723,7 +1723,7 @@
 unify_proc__compare_args_2([_Name - Type | ArgTypes], ExistQTVars,
         [X | Xs], [Y | Ys], R, Context, Goal, !Info) :-
     goal_info_init(GoalInfo0),
-    goal_info_set_context(GoalInfo0, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo0, GoalInfo),
     %
     % When comparing existentially typed arguments, the arguments may
     % have different types; in that case, rather than just comparing them,
@@ -1808,7 +1808,7 @@
         GoalExpr = call(PredId, ProcId, ArgVars, not_builtin, no, PredName),
         set__list_to_set(ArgVars, NonLocals),
         goal_info_init(NonLocals, InstmapDelta, Detism, pure, GoalInfo0),
-        goal_info_set_context(GoalInfo0, Context, GoalInfo),
+        goal_info_set_context(Context, GoalInfo0, GoalInfo),
         Goal = GoalExpr - GoalInfo
     ;
         % unify_proc__build_specific_call is only ever used to build calls
Index: compiler/unique_modes.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/unique_modes.m,v
retrieving revision 1.93
diff -u -b -r1.93 unique_modes.m
--- compiler/unique_modes.m	27 Aug 2005 09:41:59 -0000	1.93
+++ compiler/unique_modes.m	27 Aug 2005 14:54:51 -0000
@@ -271,7 +271,7 @@
 	->
 		make_mostly_uniq_inst(Inst0, Inst, ModuleInfo0, ModuleInfo),
 		mode_info_set_module_info(ModuleInfo, !ModeInfo),
-		instmap__set(InstMap0, Var, Inst, InstMap),
+		instmap__set(Var, Inst, InstMap0, InstMap),
 		mode_info_set_instmap(InstMap, !ModeInfo)
 	;
 		true
@@ -782,7 +782,7 @@
 	make_shared_inst_list(VarInsts, SharedVarInsts,
 		ModuleInfo0, ModuleInfo1),
 	mode_info_set_module_info(ModuleInfo1, !ModeInfo),
-	instmap__set_vars(InstMap0, SharedList, SharedVarInsts, InstMap1),
+	instmap__set_vars(SharedList, SharedVarInsts, InstMap0, InstMap1),
 	mode_info_set_instmap(InstMap1, !ModeInfo).
 
 	% Just process each conjunct in turn.
Index: compiler/untupling.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/untupling.m,v
retrieving revision 1.6
diff -u -b -r1.6 untupling.m
--- compiler/untupling.m	22 Jul 2005 12:32:01 -0000	1.6
+++ compiler/untupling.m	28 Aug 2005 04:53:59 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -166,8 +168,7 @@
 		!ModuleInfo, map__init, TransformMap, counter__init(0), _).
 
 :- pred expand_args_in_pred(pred_id::in, module_info::in, module_info::out,
-	transform_map::in, transform_map::out, counter::in, counter::out)
-	is det.
+    transform_map::in, transform_map::out, counter::in, counter::out) is det.
 
 expand_args_in_pred(PredId, !ModuleInfo, !TransformMap, !Counter) :-
 	module_info_types(!.ModuleInfo, TypeTable),
@@ -184,8 +185,7 @@
 		pred_info_get_head_type_params(PredInfo, []),
 		pred_info_get_class_context(PredInfo, constraints([], [])),
 		pred_info_get_origin(PredInfo, user(_)),
-		pred_info_arg_types(PredInfo, TypeVarSet, ExistQVars,
-			ArgTypes),
+        pred_info_arg_types(PredInfo, TypeVarSet, ExistQVars, ArgTypes),
 		varset__is_empty(TypeVarSet),
 		ExistQVars = [],
 		at_least_one_expandable_type(ArgTypes, TypeTable)
@@ -263,13 +263,12 @@
 	type_table::in, untuple_map::out) is det.
 
 expand_args_in_proc_2(HeadVars0, ArgModes0, HeadVars, ArgModes,
-		Goal0, Goal - GoalInfo, !VarSet, !VarTypes, TypeTable,
-		UntupleMap) :-
+        Goal0, Goal - GoalInfo, !VarSet, !VarTypes, TypeTable, UntupleMap) :-
 	expand_args_in_proc_3(HeadVars0, ArgModes0, ListOfHeadVars,
 		ListOfArgModes, Goal0, Goal - GoalInfo1, !VarSet,
 		!VarTypes, [], TypeTable),
 	goal_info_get_context(snd(Goal0), Context),
-	goal_info_set_context(GoalInfo1, Context, GoalInfo),
+    goal_info_set_context(Context, GoalInfo1, GoalInfo),
 	list__condense(ListOfHeadVars, HeadVars),
 	list__condense(ListOfArgModes, ArgModes),
 	build_untuple_map(HeadVars0, ListOfHeadVars, map__init, UntupleMap).
@@ -300,12 +299,11 @@
 expand_one_arg_in_proc(HeadVar0, ArgMode0, HeadVars, ArgModes,
 		!Goal, !VarSet, !VarTypes, ContainerTypes0, TypeTable) :-
 	expand_one_arg_in_proc_2(HeadVar0, ArgMode0, MaybeHeadVarsAndArgModes,
-		!Goal, !VarSet, !VarTypes, ContainerTypes0, ContainerTypes,
-		TypeTable),
+        !Goal, !VarSet, !VarTypes, ContainerTypes0, ContainerTypes, TypeTable),
 	(
 		MaybeHeadVarsAndArgModes = yes(HeadVars1 - ArgModes1),
-		expand_args_in_proc_3(HeadVars1, ArgModes1, ListOfHeadVars,
-			ListOfArgModes, !Goal, !VarSet, !VarTypes,
+        expand_args_in_proc_3(HeadVars1, ArgModes1,
+            ListOfHeadVars, ListOfArgModes, !Goal, !VarSet, !VarTypes,
 			ContainerTypes, TypeTable),
 		HeadVars = list__condense(ListOfHeadVars),
 		ArgModes = list__condense(ListOfArgModes)
@@ -332,21 +330,17 @@
 		varset__lookup_name(!.VarSet, HeadVar0, ParentName),
 		create_untuple_vars(ParentName, 0, NewTypes, NewHeadVars,
 			!VarSet, !VarTypes),
-		list__duplicate(list__length(NewHeadVars), ArgMode0,
-			NewArgModes),
+        list__duplicate(list__length(NewHeadVars), ArgMode0, NewArgModes),
 		MaybeHeadVarsAndArgModes = yes(NewHeadVars - NewArgModes),
 		( ArgMode0 = in_mode ->
-			construct_functor(HeadVar0, ConsId, NewHeadVars,
-				UnifGoal),
+            construct_functor(HeadVar0, ConsId, NewHeadVars, UnifGoal),
 			conjoin_goals_keep_detism(UnifGoal, !Goal)
 		; ArgMode0 = out_mode ->
-			deconstruct_functor(HeadVar0, ConsId, NewHeadVars,
-				UnifGoal),
+            deconstruct_functor(HeadVar0, ConsId, NewHeadVars, UnifGoal),
 			conjoin_goals_keep_detism(!.Goal, UnifGoal, !:Goal)
 		;
 			unexpected(this_file,
-				"expand_one_arg_in_proc_2: " ++
-				"unsupported mode encountered")
+                "expand_one_arg_in_proc_2: unsupported mode encountered")
 		),
 		ContainerTypes = [Type | ContainerTypes0]
 	;
@@ -365,8 +359,7 @@
 	string__format("Untupled_%s_%d", [s(ParentName), i(Num)], Name),
 	svvarset__new_named_var(Name, NewVar, !VarSet),
 	svmap__det_insert(NewVar, Type, !VarTypes),
-	create_untuple_vars(ParentName, Num+1, Types, NewVars,
-		!VarSet, !VarTypes).
+    create_untuple_vars(ParentName, Num+1, Types, NewVars, !VarSet, !VarTypes).
 
 :- pred conjoin_goals_keep_detism(hlds_goal::in, hlds_goal::in,
 	hlds_goal::out) is det.
@@ -377,7 +370,7 @@
 	list__append(GoalListA, GoalListB, GoalList),
 	goal_list_determinism(GoalList, Determinism),
 	goal_info_init(GoalInfo0),
-	goal_info_set_determinism(GoalInfo0, Determinism, GoalInfo).
+    goal_info_set_determinism(Determinism, GoalInfo0, GoalInfo).
 
 :- pred build_untuple_map(list(prog_var)::in, list(list(prog_var))::in,
 	untuple_map::in, untuple_map::out) is det.
@@ -390,9 +383,9 @@
 		svmap__det_insert(OldVar, NewVars, !UntupleMap),
 		build_untuple_map(OldVars, NewVarss, !UntupleMap)
 	).
-build_untuple_map([], [_|_], !_) :-
+build_untuple_map([], [_| _], !_) :-
 	unexpected(this_file, "build_untuple_map: length mismatch").
-build_untuple_map([_|_], [], !_) :-
+build_untuple_map([_| _], [], !_) :-
 	unexpected(this_file, "build_untuple_map: length mismatch").
 
 %-----------------------------------------------------------------------------%
@@ -414,13 +407,12 @@
 
 create_aux_pred(PredId, ProcId, PredInfo, ProcInfo, Counter,
 		AuxPredId, AuxProcId, CallAux, AuxPredInfo, AuxProcInfo,
-		ModuleInfo0, ModuleInfo) :-
-	module_info_name(ModuleInfo0, ModuleName),
+        !ModuleInfo) :-
+    module_info_name(!.ModuleInfo, ModuleName),
 
 	proc_info_headvars(ProcInfo, AuxHeadVars),
 	proc_info_goal(ProcInfo, Goal @ (_GoalExpr - GoalInfo)),
-	proc_info_get_initial_instmap(ProcInfo, ModuleInfo0,
-		InitialAuxInstMap),
+    proc_info_get_initial_instmap(ProcInfo, !.ModuleInfo, InitialAuxInstMap),
 	pred_info_typevarset(PredInfo, TVarSet),
 	proc_info_vartypes(ProcInfo, VarTypes),
 	pred_info_get_class_context(PredInfo, ClassContext),
@@ -446,30 +438,12 @@
 	),
 
 	Origin = transformed(untuple(ProcNo), OrigOrigin, PredId),
-	hlds_pred__define_new_pred(
-		Origin,			% in
-		Goal,			% in
-		CallAux,		% out
-		AuxHeadVars,		% in
-		_ExtraArgs,		% out
-		InitialAuxInstMap,	% in
-		AuxPredName,		% in
-		TVarSet,		% in
-		VarTypes,		% in
-		ClassContext,		% in
-		RttiVarMaps,		% in
-		VarSet,			% in
-		InstVarSet,		% in
-		Markers,		% in
-		Owner,			% in
-		address_is_not_taken,	% in
-		ModuleInfo0,
-		ModuleInfo,
-		proc(AuxPredId, AuxProcId)
-					% out
-	),
+    hlds_pred__define_new_pred(Origin, Goal, CallAux, AuxHeadVars, _ExtraArgs,
+        InitialAuxInstMap, AuxPredName, TVarSet, VarTypes, ClassContext,
+        RttiVarMaps, VarSet, InstVarSet, Markers, Owner, address_is_not_taken,
+        !ModuleInfo, proc(AuxPredId, AuxProcId)),
 
-	module_info_pred_proc_info(ModuleInfo, AuxPredId, AuxProcId,
+    module_info_pred_proc_info(!.ModuleInfo, AuxPredId, AuxProcId,
 		AuxPredInfo, AuxProcInfo).
 
 %-----------------------------------------------------------------------------%
@@ -477,11 +451,10 @@
 % Pass 2
 %
 
-	% This is the top level of the second pass.  It takes the transform
-	% map built during the first pass as input.  For every call to a
-	% procedure in the transform map, it rewrites the call to use the new
-	% procedure instead, inserting unifications before and after the call
-	% as necessary.
+    % This is the top level of the second pass. It takes the transform map
+    % built during the first pass as input.  For every call to a procedure
+    % in the transform map, it rewrites the call to use the new procedure
+    % instead, inserting unifications before and after the call as necessary.
 	%
 :- pred fix_calls_to_expanded_procs(transform_map::in, module_info::in,
 	module_info::out) is det.
@@ -496,8 +469,7 @@
 fix_calls_in_pred(TransformMap, PredId, !ModuleInfo) :-
 	module_info_pred_info(!.ModuleInfo, PredId, PredInfo),
 	ProcIds = pred_info_non_imported_procids(PredInfo),
-	list__foldl(fix_calls_in_proc(TransformMap, PredId), ProcIds,
-		!ModuleInfo).
+    list__foldl(fix_calls_in_proc(TransformMap, PredId), ProcIds, !ModuleInfo).
 
 :- pred fix_calls_in_proc(transform_map::in, pred_id::in, proc_id::in,
 	module_info::in, module_info::out) is det.
@@ -516,8 +488,7 @@
 			proc_info_set_varset(VarSet, !ProcInfo),
 			proc_info_set_vartypes(VarTypes, !ProcInfo),
 			requantify_proc(!ProcInfo),
-			recompute_instmap_delta_proc(yes, !ProcInfo,
-				!ModuleInfo),
+            recompute_instmap_delta_proc(yes, !ProcInfo, !ModuleInfo),
 			module_info_set_pred_proc_info(PredId, ProcId,
 				PredInfo, !.ProcInfo, !ModuleInfo)
 		;
@@ -541,8 +512,7 @@
 		TransformMap, ModuleInfo) :-
 	Goal0 = call(CalleePredId, CalleeProcId, OrigArgs, _, _, _),
 	(
-		map__search(TransformMap,
-			proc(CalleePredId, CalleeProcId),
+        map__search(TransformMap, proc(CalleePredId, CalleeProcId),
 			transformed_proc(_, CallAux0 - CallAuxInfo))
 	->
 		module_info_types(ModuleInfo, TypeTable),
@@ -551,15 +521,12 @@
 		proc_info_argmodes(CalleeProcInfo, OrigArgModes),
 		expand_call_args(OrigArgs, OrigArgModes, Args,
 			EnterUnifs, ExitUnifs, !VarSet, !VarTypes, TypeTable),
-		(
-			CallAux = CallAux0 ^ call_args := Args
-		->
+        ( CallAux = CallAux0 ^ call_args := Args ->
 			Call = CallAux - CallAuxInfo,
 			ConjList = EnterUnifs ++ [Call] ++ ExitUnifs,
 			conj_list_to_goal(ConjList, GoalInfo0, Goal)
 		;
-			unexpected(this_file,
-				"fix_calls_in_goal: not a call template")
+            unexpected(this_file, "fix_calls_in_goal: not a call template")
 		)
 	;
 		Goal = Goal0 - GoalInfo0
@@ -681,8 +648,7 @@
 		EnterUnifs, ExitUnifs, !VarSet, !VarTypes,
 		ContainerTypes0, TypeTable) :-
 	map__lookup(!.VarTypes, Arg0, Arg0Type),
-	expand_argument(ArgMode, Arg0Type, ContainerTypes0, TypeTable,
-		Expansion),
+    expand_argument(ArgMode, Arg0Type, ContainerTypes0, TypeTable, Expansion),
 	(
 		Expansion = expansion(ConsId, Types),
 		NumVars = list__length(Types),
@@ -692,24 +658,21 @@
 		list__duplicate(NumVars, ArgMode, ReplacementModes),
 		ContainerTypes = [Arg0Type | ContainerTypes0],
 		( ArgMode = in_mode ->
-			deconstruct_functor(Arg0, ConsId,
-				ReplacementArgs, Unif),
+            deconstruct_functor(Arg0, ConsId, ReplacementArgs, Unif),
 			EnterUnifs = [Unif | EnterUnifs1],
 			expand_call_args_2(ReplacementArgs ++ Args0,
 				ReplacementModes ++ ArgModes,
 				Args, EnterUnifs1, ExitUnifs, !VarSet,
 				!VarTypes, ContainerTypes, TypeTable)
 		; ArgMode = out_mode ->
-			construct_functor(Arg0, ConsId,
-				ReplacementArgs, Unif),
+            construct_functor(Arg0, ConsId, ReplacementArgs, Unif),
 			ExitUnifs = ExitUnifs1 ++ [Unif],
 			expand_call_args_2(ReplacementArgs ++ Args0,
 				ReplacementModes ++ ArgModes,
 				Args, EnterUnifs, ExitUnifs1, !VarSet,
 				!VarTypes, ContainerTypes, TypeTable)
 		;
-			unexpected(this_file,
-				"expand_call_args: unsupported mode")
+            unexpected(this_file, "expand_call_args: unsupported mode")
 		)
 	;
 		Expansion = no_expansion,
@@ -799,3 +762,5 @@
 :- func this_file = string.
 
 this_file = "untupling.m".
+
+%-----------------------------------------------------------------------------%
Index: compiler/unused_args.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/unused_args.m,v
retrieving revision 1.106
diff -u -b -r1.106 unused_args.m
--- compiler/unused_args.m	17 Aug 2005 07:16:37 -0000	1.106
+++ compiler/unused_args.m	28 Aug 2005 05:15:54 -0000
@@ -1,4 +1,6 @@
 %-----------------------------------------------------------------------------%
+% vim: ft=mercury ts=4 sw=4 et
+%-----------------------------------------------------------------------------%
 % Copyright (C) 1996-2005 The University of Melbourne.
 % This file may only be copied under the terms of the GNU General
 % Public License - see the file COPYING in the Mercury distribution.
@@ -29,12 +31,14 @@
 %  The first step is to determine which arguments of which predicates are
 %	used locally to their predicate. For each unused argument, a set of
 %	other arguments that it depends on is built up.
+%
 %  The next step is to iterate over the this map, checking for each unused
 %	argument whether any of the arguments it depends on has become used
-%	in the last iteration. Iterations are repeated until a fixpoint is
-%	reached.
+% in the last iteration. Iterations are repeated until a fixpoint is reached.
+%
 %  Warnings are then output. The warning message indicates which arguments
 %	are used in none of the modes of a predicate.
+%
 %  The predicates are then fixed up. Unused variables and unifications are
 %	removed.
 
@@ -83,12 +87,13 @@
 :- import_module libs__globals.
 :- import_module libs__options.
 :- import_module mdbcomp__prim_data.
+:- import_module parse_tree__error_util.
 :- import_module parse_tree__mercury_to_mercury.
 :- import_module parse_tree__modules.
 :- import_module parse_tree__prog_data.
 :- import_module parse_tree__prog_out.
-:- import_module parse_tree__prog_util.
 :- import_module parse_tree__prog_type.
+:- import_module parse_tree__prog_util.
 :- import_module transform_hlds__mmc_analysis.
 
 :- import_module assoc_list.
@@ -101,6 +106,7 @@
 :- import_module set.
 :- import_module std_util.
 :- import_module string.
+:- import_module svmap.
 
 		% Information about the dependencies of a variable
 		% that is not known to be used.
@@ -110,12 +116,12 @@
 	% A collection of variable usages for each procedure.
 :- type var_usage == map(pred_proc_id, var_dep).
 
-	% arguments are stored as their variable id, not their index
-	%	in the argument vector
+    % Arguments are stored as their variable id, not their index
+    % in the argument vector.
 :- type arg == pair(pred_proc_id, prog_var).
 
-		% Contains dependency information for the variables
-		% in a procedure that are not yet known to be used.
+    % Contains dependency information for the variables in a procedure
+    % that are not yet known to be used.
 :- type var_dep == map(prog_var, usage_info).
 
 :- type warning_info
@@ -123,7 +129,7 @@
 			% context, pred name, arity, list of args to warn
 
 %-----------------------------------------------------------------------------%
-	% Types and instances used by mmc_analysis.m.
+% Types and instances used by mmc_analysis.m.
 
 	% The list of unused arguments is in sorted order.
 :- type unused_args_answer
@@ -156,8 +162,7 @@
 ].
 :- instance partial_order(unused_args_func_info, unused_args_answer) where [
 	(more_precise_than(_, unused_args(Args1), unused_args(Args2)) :-
-		set__subset(sorted_list_to_set(Args2),
-			sorted_list_to_set(Args1))
+        set__subset(sorted_list_to_set(Args2), sorted_list_to_set(Args1))
 	),
 	equivalent(_, Args, Args)
 ].
@@ -175,16 +180,20 @@
 :- func unused_args_answer_from_string(string) = unused_args_answer is semidet.
 
 unused_args_answer_from_string(String) = unused_args(Args) :-
-	{Digits, Args0} = string__foldl((func(Char, {Digits0, Ints0}) =
+    string__foldl2(accumulate_ints_from_chars, String, [], Digits, [], Args0),
+    Args = list__reverse([det_to_int(from_rev_char_list(Digits)) | Args0]),
+    semidet_succeed.
+
+:- pred accumulate_ints_from_chars(char::in,
+    list(char)::in, list(char)::out, list(int)::in, list(int)::out) is det.
+
+accumulate_ints_from_chars(Char, !Digits, !Ints) :-
 		( char__is_digit(Char) ->
-			{[Char | Digits0], Ints0}
+        !:Digits = [Char | !.Digits]
 		;
-			{[], [string__det_to_int(
-				string__from_rev_char_list(Digits0)) | Ints0]}
-		)), String, {[], []}),
-	Args = list__reverse([string__det_to_int(
-		string__from_rev_char_list(Digits)) | Args0]),
-	semidet_succeed.
+        !:Digits = [],
+        !:Ints = [det_to_int(from_rev_char_list(!.Digits)) | !.Ints]
+    ).
 
 %-----------------------------------------------------------------------------%
 
@@ -201,20 +210,20 @@
 		UnusedArgInfo0, UnusedArgInfo),
 
 	map__keys(UnusedArgInfo, PredProcsToFix),
-	globals__io_lookup_bool_option(make_optimization_interface, MakeOpt,
-		!IO),
+    globals__io_lookup_bool_option(make_optimization_interface, MakeOpt, !IO),
 	(
 		MakeOpt = yes,
 		module_info_name(!.ModuleInfo, ModuleName),
-		module_name_to_file_name(ModuleName, ".opt.tmp", no,
-			OptFileName, !IO),
+        module_name_to_file_name(ModuleName, ".opt.tmp", no, OptFileName, !IO),
 		io__open_append(OptFileName, OptFileRes, !IO),
-		( OptFileRes = ok(OptFile),
+        (
+            OptFileRes = ok(OptFile),
 			MaybeOptFile = yes(OptFile)
-		; OptFileRes = error(IOError),
+        ;
+            OptFileRes = error(IOError),
 			io__error_message(IOError, IOErrorMessage),
-			io__write_strings(["Cannot open `", OptFileName,
-				"' for output: ", IOErrorMessage], !IO),
+            io__write_strings(["Cannot open `", OptFileName, "' for output: ",
+                IOErrorMessage], !IO),
 			io__set_exit_status(1, !IO),
 			MaybeOptFile = no
 		)
@@ -223,11 +232,14 @@
 		MaybeOptFile = no
 	),
 	globals__io_lookup_bool_option(warn_unused_args, DoWarn, !IO),
-	( ( DoWarn = yes ; MakeOpt = yes ) ->
+    (
+        ( DoWarn = yes
+        ; MakeOpt = yes
+        )
+    ->
 		set__init(WarnedPredIds0),
 		output_warnings_and_pragmas(!.ModuleInfo, UnusedArgInfo,
-			MaybeOptFile, DoWarn, PredProcsToFix, WarnedPredIds0,
-			!IO)
+            MaybeOptFile, DoWarn, PredProcsToFix, WarnedPredIds0, !IO)
 	;
 		true
 	),
@@ -268,6 +280,7 @@
 	% iteration over.
 	% OptPredProcList is a list of procedures for which we got
 	% unused argument information from .opt files.
+    %
 :- pred init_var_usage(var_usage::out, pred_proc_list::out,
 	proc_call_info::out, module_info::in, module_info::out,
 	io::di, io::uo) is det.
@@ -277,11 +290,11 @@
 	map__init(VarUsage0),
 	module_info_predids(!.ModuleInfo, PredIds),
 	module_info_unused_arg_info(!.ModuleInfo, UnusedArgInfo),
-	setup_local_var_usage(PredIds, UnusedArgInfo,
-		VarUsage0, VarUsage, [], PredProcList,
-		ProcCallInfo0, ProcCallInfo, !ModuleInfo, !IO).
+    setup_local_var_usage(PredIds, UnusedArgInfo, VarUsage0, VarUsage,
+        [], PredProcList, ProcCallInfo0, ProcCallInfo, !ModuleInfo, !IO).
 
-	% setup args for the whole module.
+    % Setup args for the whole module.
+    %
 :- pred setup_local_var_usage(list(pred_id)::in, unused_arg_info::in,
 	var_usage::in, var_usage::out, pred_proc_list::in, pred_proc_list::out,
 	proc_call_info::in, proc_call_info::out,
@@ -327,7 +340,8 @@
 		!OptProcs, !ModuleInfo, !IO) :-
 	module_info_pred_proc_info(!.ModuleInfo, PredId, ProcId,
 		PredInfo, ProcInfo),
-	map__init(VarDep0),
+    some [!VarDep] (
+        map__init(!:VarDep),
 	globals__io_lookup_bool_option(intermodule_analysis, Intermod, !IO),
 	(
 		% Don't use the intermodule analysis info when we have the
@@ -345,24 +359,21 @@
 		module_info_analysis_info(!.ModuleInfo, AnalysisInfo0),
 		lookup_best_result(module_name_to_module_id(PredModule),
 			FuncId, unused_args_func_info(PredArity),
-			any_call, MaybeBestResult,
-			AnalysisInfo0, AnalysisInfo, !IO),
+                any_call, MaybeBestResult, AnalysisInfo0, AnalysisInfo, !IO),
 		module_info_set_analysis_info(AnalysisInfo, !ModuleInfo),
 		( MaybeBestResult = yes(_ - unused_args(UnusedArgs)) ->
 			proc_info_headvars(ProcInfo, HeadVars),
-			list__map(list__index1_det(HeadVars),
-				UnusedArgs, UnusedVars),
-			initialise_vardep(VarDep0, UnusedVars, VarDep),
-			!:VarUsage = map__set(!.VarUsage,
-				proc(PredId, ProcId), VarDep),
-			globals__io_lookup_bool_option(optimize_unused_args,
-				Optimize, !IO),
-			( Optimize = yes ->
-				make_imported_unused_args_pred_info(
-					proc(PredId, ProcId), UnusedArgs,
-					!OptProcs, !ModuleInfo)
+                list__map(list__index1_det(HeadVars), UnusedArgs, UnusedVars),
+                initialise_vardep(UnusedVars, !.VarDep, VarDep),
+                svmap__set(proc(PredId, ProcId), VarDep, !VarUsage),
+                globals__io_lookup_bool_option(optimize_unused_args, Optimize,
+                    !IO),
+                (   
+                    Optimize = yes,
+                    make_imported_unused_args_pred_info(proc(PredId, ProcId),
+                        UnusedArgs, !OptProcs, !ModuleInfo)
 			;
-				true
+                    Optimize = no
 			)
 		;
 			true
@@ -384,49 +395,51 @@
 	;
 		proc_info_vartypes(ProcInfo, VarTypes),
 		map__keys(VarTypes, Vars),
-		initialise_vardep(VarDep0, Vars, VarDep1),
-		setup_output_args(!.ModuleInfo, ProcInfo, VarDep1, VarDep2),
+            initialise_vardep(Vars, !VarDep),
+            setup_output_args(!.ModuleInfo, ProcInfo, !VarDep),
 
 		module_info_globals(!.ModuleInfo, Globals),
 		proc_interface_should_use_typeinfo_liveness(PredInfo, ProcId,
 			Globals, TypeInfoLiveness),
-		( TypeInfoLiveness = yes ->
+            (
+                TypeInfoLiveness = yes,
 			proc_info_rtti_varmaps(ProcInfo, RttiVarMaps),
-			setup_typeinfo_deps(Vars, VarTypes,
-				proc(PredId, ProcId), RttiVarMaps, VarDep2,
-				VarDep3)
+                setup_typeinfo_deps(Vars, VarTypes, proc(PredId, ProcId),
+                    RttiVarMaps, !VarDep)
 		;
-			VarDep2 = VarDep3
+                TypeInfoLiveness = no
 		),
 
 		proc_info_goal(ProcInfo, Goal - _),
 		Info = traverse_info(!.ModuleInfo, VarTypes),
-		traverse_goal(Info, Goal, VarDep3, VarDep),
-		!:VarUsage = map__set(!.VarUsage,
-			proc(PredId, ProcId), VarDep),
+            traverse_goal(Info, Goal, !VarDep),
+            svmap__set(proc(PredId, ProcId), !.VarDep, !VarUsage),
 
 		!:PredProcs = [proc(PredId, ProcId) | !.PredProcs]
+        )
 	),
-	setup_pred_args(PredId, Rest, UnusedArgInfo,
-		!VarUsage, !PredProcs, !OptProcs, !ModuleInfo, !IO).
+    setup_pred_args(PredId, Rest, UnusedArgInfo, !VarUsage, !PredProcs,
+        !OptProcs, !ModuleInfo, !IO).
 
-:- pred initialise_vardep(var_dep::in, list(prog_var)::in, var_dep::out) is det.
+:- pred initialise_vardep(list(prog_var)::in, var_dep::in, var_dep::out)
+    is det.
 
-initialise_vardep(VarDep, [], VarDep).
-initialise_vardep(VarDep0, [Var | Vars], VarDep) :-
+initialise_vardep([], !VarDep).
+initialise_vardep([Var | Vars], !VarDep) :-
 	set__init(VDep),
 	set__init(Args),
-	map__set(VarDep0, Var, unused(VDep, Args), VarDep1),
-	initialise_vardep(VarDep1, Vars, VarDep).
+    svmap__set(Var, unused(VDep, Args), !VarDep),
+    initialise_vardep(Vars, !VarDep).
 
 %-------------------------------------------------------------------------------
-	% Predicates for manipulating the var_usage and var_dep structures.
+%
+% Predicates for manipulating the var_usage and var_dep structures.
 
-	% For each variable ensure the typeinfos describing the
-	% type parameters of the type of the variable depend on the
-	% head variable.
-	% For example, if HeadVar1 has type list(T), then TypeInfo_for_T
-	% is used if HeadVar1 is used.
+    % For each variable ensure the typeinfos describing the type parameters
+    % of the type of the variable depend on the head variable. For example,
+    % if HeadVar1 has type list(T), then TypeInfo_for_T is used if HeadVar1
+    % is used.
+    %
 :- pred setup_typeinfo_deps(list(prog_var)::in, map(prog_var, type)::in,
 	pred_proc_id::in, rtti_varmaps::in, var_dep::in, var_dep::out) is det.
 
@@ -444,11 +457,11 @@
 			add_arg_dep(TVar, PredProcId, Var, VarDepA, VarDepB)
 		),
 	list__foldl(AddArgDependency, TypeInfoVars, !VarDep),
-	setup_typeinfo_deps(Vars, VarTypeMap, PredProcId, RttiVarMaps,
-		!VarDep).
+    setup_typeinfo_deps(Vars, VarTypeMap, PredProcId, RttiVarMaps, !VarDep).
 
 	% Get output arguments for a procedure given the headvars and the
 	% argument modes, and set them as used.
+    %
 :- pred setup_output_args(module_info::in, proc_info::in,
 	var_dep::in, var_dep::out) is det.
 
@@ -457,8 +470,9 @@
 		ChangedInstHeadVars),
 	list__foldl(set_var_used, ChangedInstHeadVars, !VarDep).
 
-	% searches for the dependencies of a variable, succeeds if the variable
-	%	is definitely used
+    % Searches for the dependencies of a variable, succeeds if the variable
+    % is definitely used.
+    %
 :- pred var_is_used(pred_proc_id::in, prog_var::in, var_usage::in) is semidet.
 
 var_is_used(PredProc, Var, VarUsage) :-
@@ -472,7 +486,8 @@
 local_var_is_used(VarDep, Var) :-
 	\+ map__contains(VarDep, Var).
 
-		% add a list of aliases for a variable
+    % Add a list of aliases for a variable.
+    %
 :- pred add_aliases(prog_var::in, list(prog_var)::in,
 	var_dep::in, var_dep::out) is det.
 
@@ -503,8 +518,9 @@
 	map__search(VarDep, Var, UsageInfo).
 
 %-------------------------------------------------------------------------------
-	% Traversal of goal structure, building up dependencies for all
-	% variables.
+%
+% Traversal of goal structure, building up dependencies for all
+% variables.
 
 :- type traverse_info
 	--->	traverse_info(
@@ -515,57 +531,43 @@
 :- pred traverse_goal(traverse_info::in, hlds_goal_expr::in,
 	var_dep::in, var_dep::out) is det.
 
-% handle conjunction
 traverse_goal(Info, conj(Goals), !VarDep) :-
 	traverse_list_of_goals(Info, Goals, !VarDep).
 
-% handle parallel conjunction
 traverse_goal(Info, par_conj(Goals), !VarDep) :-
 	traverse_list_of_goals(Info, Goals, !VarDep).
 
-% handle disjunction
 traverse_goal(Info, disj(Goals), !VarDep) :-
 	traverse_list_of_goals(Info, Goals, !VarDep).
 
-% handle switch
 traverse_goal(Info, switch(Var, _, Cases), !VarDep) :-
 	set_var_used(Var, !VarDep),
 	list_case_to_list_goal(Cases, Goals),
 	traverse_list_of_goals(Info, Goals, !VarDep).
 
-% handle predicate call
 traverse_goal(Info, call(PredId, ProcId, Args, _, _, _), !VarDep) :-
-	module_info_pred_proc_info(Info^module_info, PredId, ProcId, _Pred,
-		Proc),
+    module_info_pred_proc_info(Info^module_info, PredId, ProcId, _Pred, Proc),
 	proc_info_headvars(Proc, HeadVars),
-	add_pred_call_arg_dep(proc(PredId, ProcId), Args, HeadVars,
-		!VarDep).
+    add_pred_call_arg_dep(proc(PredId, ProcId), Args, HeadVars, !VarDep).
 
-% handle if then else
-traverse_goal(Info, if_then_else(_, Cond - _, Then - _, Else - _),
-			!VarDep) :-
+traverse_goal(Info, if_then_else(_, Cond - _, Then - _, Else - _), !VarDep) :-
 	traverse_goal(Info, Cond, !VarDep),
 	traverse_goal(Info, Then, !VarDep),
 	traverse_goal(Info, Else, !VarDep).
 
-% handle negation
 traverse_goal(Info, not(Goal - _), !VarDep) :-
 	traverse_goal(Info, Goal, !VarDep).
 
-% handle quantification
 traverse_goal(Info, scope(_, Goal - _), !VarDep) :-
 	traverse_goal(Info, Goal, !VarDep).
 
-% we assume that higher-order predicate calls use all variables involved
 traverse_goal(_, generic_call(GenericCall, Args, _, _), !VarDep) :-
 	goal_util__generic_call_vars(GenericCall, CallArgs),
 	set_list_vars_used(CallArgs, !VarDep),
 	set_list_vars_used(Args, !VarDep).
 
-% handle pragma foreign_proc(...) -
-% only those arguments which have names can be used in the foreign code.
-traverse_goal(_, foreign_proc(_, _, _, Args, ExtraArgs, _),
-		!VarDep) :-
+traverse_goal(_, foreign_proc(_, _, _, Args, ExtraArgs, _), !VarDep) :-
+    % Only those arguments which have names can be used in the foreign code.
 	ArgIsUsed = (pred(Arg::in, Var::out) is semidet :-
 		Arg = foreign_arg(Var, MaybeNameAndMode, _),
 		MaybeNameAndMode = yes(_)
@@ -573,39 +575,34 @@
 	list__filter_map(ArgIsUsed, Args ++ ExtraArgs, UsedVars),
 	set_list_vars_used(UsedVars, !VarDep).
 
-% cases to handle all the different types of unification
-traverse_goal(_, unify(_, _, _, simple_test(Var1, Var2),_), !VarDep)
-		:-
+traverse_goal(_, unify(_, _, _, simple_test(Var1, Var2),_), !VarDep) :-
 	set_var_used(Var1, !VarDep),
 	set_var_used(Var2, !VarDep).
 
 traverse_goal(_, unify(_, _, _, assign(Var1, Var2), _), !VarDep) :-
 	( local_var_is_used(!.VarDep, Var1) ->
-		% if Var1 used to instantiate an output argument, Var2 used
+        % If Var1 is used to instantiate an output argument, Var2 is used.
 		set_var_used(Var2, !VarDep)
 	;
 		add_aliases(Var2, [Var1], !VarDep)
 	).
 
 traverse_goal(Info,
-		unify(Var1, _, _,
-			deconstruct(_, _, Args, Modes, CanFail, _), _),
+        unify(Var1, _, _, deconstruct(_, _, Args, Modes, CanFail, _), _),
 		!VarDep) :-
-	partition_deconstruct_args(Info, Args,
-		Modes, InputVars, OutputVars),
-		% The deconstructed variable is used if any of the
-		% variables, that the deconstruction binds are used.
+    partition_deconstruct_args(Info, Args, Modes, InputVars, OutputVars),
+    % The deconstructed variable is used if any of the variables that the
+    % deconstruction binds are used.
 	add_aliases(Var1, OutputVars, !VarDep),
-		% Treat a deconstruction that further instantiates its
-		% left arg as a partial construction.
+    % Treat a deconstruction that further instantiates its left arg
+    % as a partial construction.
 	add_construction_aliases(Var1, InputVars, !VarDep),
 	(
-		CanFail = can_fail
-	->
-		% a deconstruction that can_fail uses its left arg
+        CanFail = can_fail,
+        % A deconstruction that can_fail uses its left arg.
 		set_var_used(Var1, !VarDep)
 	;
-		true
+        CanFail = cannot_fail
 	).
 
 traverse_goal(_, unify(Var1, _, _, construct(_, _, Args, _, _, _, _), _),
@@ -626,14 +623,16 @@
 		set_var_used(RhsVar, !VarDep),
 		set_var_used(Var, !VarDep)
 	;
-		error("complicated unifications should only be var-var")
+        unexpected(this_file,
+            "complicated unifications should only be var-var")
 	).
 
 traverse_goal(_, shorthand(_), _, _) :-
-	% these should have been expanded out by now
-	error("traverse_goal: unexpected shorthand").
+    % These should have been expanded out by now.
+    unexpected(this_file, "traverse_goal: unexpected shorthand").
 
-	% add PredProc - HeadVar as an alias for the same element of Args.
+    % Add PredProc - HeadVar as an alias for the same element of Args.
+    %
 :- pred add_pred_call_arg_dep(pred_proc_id::in, list(prog_var)::in,
 	list(prog_var)::in, var_dep::in, var_dep::out) is det.
 
@@ -650,7 +649,7 @@
 	->
 		true
 	;
-		error("add_pred_call_arg_dep: invalid call")
+        unexpected(this_file, "add_pred_call_arg_dep: invalid call")
 	).
 
 :- pred add_arg_dep(prog_var::in, pred_proc_id::in, prog_var::in,
@@ -660,14 +659,14 @@
 	( lookup_local_var(!.VarDep, Var, VarUsage0) ->
 		VarUsage0 = unused(VarDep, ArgDep0),
 		set__insert(ArgDep0, PredProc - Arg, ArgDep),
-		map__det_update(!.VarDep, Var, unused(VarDep, ArgDep),
-			!:VarDep)
+        svmap__det_update(Var, unused(VarDep, ArgDep), !VarDep)
 	;
 		true
 	).
 
 	% Partition the arguments to a deconstruction into inputs
 	% and outputs.
+    %
 :- pred partition_deconstruct_args(traverse_info::in, list(prog_var)::in,
 	list(uni_mode)::in, list(prog_var)::out, list(prog_var)::out) is det.
 
@@ -676,10 +675,8 @@
 		ArgVars = [Var | Vars],
 		ArgModes = [Mode | Modes]
 	->
-		partition_deconstruct_args(Info, Vars, Modes, InputVars1,
-			OutputVars1),
-		Mode = ((InitialInst1 - InitialInst2) ->
-			(FinalInst1 - FinalInst2)),
+        partition_deconstruct_args(Info, Vars, Modes, InputVars1, OutputVars1),
+        Mode = ((InitialInst1 - InitialInst2) -> (FinalInst1 - FinalInst2)),
 
 		map__lookup(Info^vartypes, Var, Type),
 
@@ -697,8 +694,8 @@
 		% If the inst of the argument of the RHS is changed,
 		% the argument is output.
 		(
-			inst_matches_binding(InitialInst2, FinalInst2,
-				Type, Info^module_info)
+            inst_matches_binding(InitialInst2, FinalInst2, Type,
+                Info ^ module_info)
 		->
 			OutputVars = OutputVars1
 		;
@@ -711,10 +708,11 @@
 		InputVars = [],
 		OutputVars = []
 	;
-		error("get_instantiating_variables - invalid call")
+        unexpected(this_file, "get_instantiating_variables - invalid call")
 	).
 
-		% add Alias as an alias for all of Vars
+    % Add Alias as an alias for all of Vars.
+    %
 :- pred add_construction_aliases(prog_var::in, list(prog_var)::in,
 	var_dep::in, var_dep::out) is det.
 
@@ -723,7 +721,7 @@
 	( lookup_local_var(!.VarDep, Var, VarInf) ->
 		VarInf = unused(VarDep0, ArgDep),
 		set__insert(VarDep0, Alias, VarDep),
-		map__set(!.VarDep, Var, unused(VarDep, ArgDep), !:VarDep)
+        svmap__set(Var, unused(VarDep, ArgDep), !VarDep)
 	;
 		true
 	),
@@ -744,9 +742,10 @@
 	traverse_list_of_goals(Info, Goals, !VarDep).
 
 %-------------------------------------------------------------------------------
-	% Analysis section - do the fixpoint iteration.
+% Analysis section - do the fixpoint iteration.
 
 	% Do a full iteration, check if anything changed, if so, repeat.
+    %
 :- pred unused_args_pass(pred_proc_list::in, var_usage::in,var_usage::out)
 	is det.
 
@@ -759,7 +758,8 @@
 		Changed = no
 	).
 
-	% check over all the procedures in a module
+    % Check over all the procedures in a module.
+    %
 :- pred unused_args_single_pass(pred_proc_list::in, bool::in, bool::out,
 	var_usage::in, var_usage::out) is det.
 
@@ -768,7 +768,8 @@
 	unused_args_check_proc(PredProc, !Changed, !VarUsage),
 	unused_args_single_pass(Rest, !Changed, !VarUsage).
 
-	% check a single procedure
+    % Check a single procedure.
+    %
 :- pred unused_args_check_proc(pred_proc_id::in, bool::in, bool::out,
 	var_usage::in, var_usage::out) is det.
 
@@ -779,14 +780,14 @@
 		LocalUsages0, LocalUsages),
 	(
 		LocalChanged = yes,
-		map__det_update(!.VarUsage, PredProcId, LocalUsages,
-			!:VarUsage),
+        svmap__det_update(PredProcId, LocalUsages, !VarUsage),
 		!:Changed = yes
 	;
 		LocalChanged = no
 	).
 
-	% check each var of a procedure in turn
+    % Check each var of a procedure in turn.
+    %
 :- pred unused_args_check_all_vars(var_usage::in, list(prog_var)::in,
 	bool::in, bool::out, var_dep::in, var_dep::out) is det.
 
@@ -808,7 +809,7 @@
 				local_var_is_used(!.LocalVars, Var2)
 			)
 		->
-			% set the current variable to used
+            % Set the current variable to used.
 			set_var_used(Var, !LocalVars),
 			!:Changed = yes
 		;
@@ -830,30 +831,29 @@
 	module_info_pred_proc_info(ModuleInfo, PredId, ProcId, _, ProcInfo),
 	proc_info_headvars(ProcInfo, HeadVars),
 	get_unused_arg_nos(LocalVarUsage, HeadVars, 1, UnusedArgs),
-	map__det_insert(!.UnusedArgInfo, PredProc, UnusedArgs,
-		!:UnusedArgInfo),
+    svmap__det_insert(PredProc, UnusedArgs, !UnusedArgInfo),
 	get_unused_arg_info(ModuleInfo, PredProcs, VarUsage, !UnusedArgInfo).
 
 %-------------------------------------------------------------------------------
-	% Fix up the module
+%
+% Fix up the module.
 
-	% information about predicates which have new predicates
-	% created for the optimized version
+    % Information about predicates which have new predicates
+    % created for the optimized version.
 :- type proc_call_info == map(pred_proc_id, new_proc_info).
 
-	% new pred_id, proc_id, name, and the indices in the argument
+    % New pred_id, proc_id, name, and the indices in the argument
 	% vector of the arguments that have been removed.
 :- type new_proc_info
 	--->	call_info(pred_id, proc_id, sym_name, list(int)).
 
-		% Create a new predicate for each procedure which has unused
-		% arguments. There are two reasons why we can't throw away
-		% the old procedure for non-exported predicates. One is
-		% higher-order terms - we can't remove arguments from them
-		% without changing their type, so they need the old calling
-		% interface.
-		% The other is that the next proc_id for a predicate is
+    % Create a new predicate for each procedure which has unused arguments.
+    % There are two reasons why we can't throw away the old procedure for
+    % non-exported predicates. One is higher-order terms - we can't remove
+    % arguments from them without changing their type, so they need the old
+    % calling interface. The other is that the next proc_id for a predicate is
 		% chosen based on the length of the list of proc_ids.
+    %
 :- pred create_new_pred(unused_arg_info::in, pred_proc_id::in,
 	proc_call_info::in, proc_call_info::out,
 	module_info::in, module_info::out, io::di, io::uo) is det.
@@ -870,8 +870,7 @@
 		PredModule = pred_info_module(OrigPredInfo),
 		PredName = pred_info_name(OrigPredInfo),
 
-		globals__io_lookup_bool_option(intermodule_analysis,
-			Intermod, !IO),
+        globals__io_lookup_bool_option(intermodule_analysis, Intermod, !IO),
 		(
 			Intermod = yes,
 			module_info_analysis_info(!.ModuleInfo, AnalysisInfo0),
@@ -891,13 +890,10 @@
 			( list__member(UnusedArgs, IntermodResultsArgsLists) ->
 				AnalysisInfo = AnalysisInfo1
 			;
-				analysis__record_result(ModuleId,
-					FuncId, FuncInfo, any_call,
-					unused_args(UnusedArgs),
-					AnalysisInfo1, AnalysisInfo)
+                analysis__record_result(ModuleId, FuncId, FuncInfo, any_call,
+                    unused_args(UnusedArgs), AnalysisInfo1, AnalysisInfo)
 			),
-			module_info_set_analysis_info(AnalysisInfo,
-				!ModuleInfo),
+            module_info_set_analysis_info(AnalysisInfo, !ModuleInfo),
 
 			%
 			% XXX Mark versions which have more unused arguments
@@ -925,18 +921,16 @@
 			IntermodResultsPairs = [_ | _],
 			IntermodResults = []
 		->
-			% If this predicate is from a .opt file, and
-			% no more arguments have been removed than in the
-			% original module, then leave the import status
-			% as opt_imported so that dead_proc_elim will remove
+            % If this predicate is from a .opt file, and no more arguments
+            % have been removed than in the original module, then leave the
+            % import status as opt_imported so that dead_proc_elim will remove
 			% it if no other optimization is performed on it.
 			Status = opt_imported
 		;
 			status_is_exported(Status0, yes)
 		->
-			% This specialized version of the predicate will be
-			% declared in the analysis file for this module so
-			% it must be exported.
+            % This specialized version of the predicate will be declared
+            % in the analysis file for this module so it must be exported.
 			Status = Status0
 		;
 			Status = local
@@ -946,36 +940,33 @@
 		NewPredName = pred_info_name(NewPredInfo0),
 		pred_info_procedures(NewPredInfo0, NewProcs0),
 
-			% Assign the old procedure to a new predicate, which
-			% will be fixed up in fixup_unused_args.
+        % Assign the old procedure to a new predicate, which will be fixed up
+        % in fixup_unused_args.
 		map__set(NewProcs0, ProcId, OrigProcInfo, NewProcs),
 		pred_info_set_procedures(NewProcs, NewPredInfo0, NewPredInfo),
 
-			% add the new proc to the pred table
+        % Add the new proc to the pred table.
 		module_info_get_predicate_table(!.ModuleInfo, PredTable0),
-		predicate_table_insert(NewPredInfo, NewPredId,
-			PredTable0, PredTable),
+        predicate_table_insert(NewPredInfo, NewPredId, PredTable0, PredTable),
 		module_info_set_predicate_table(PredTable, !ModuleInfo),
 
-			% add the new proc to the proc_call_info map
+        % Add the new proc to the proc_call_info map.
 		PredSymName = qualified(PredModule, NewPredName),
 		map__det_insert(!.ProcCallInfo, proc(PredId, ProcId),
 			call_info(NewPredId, ProcId, PredSymName, UnusedArgs),
 			!:ProcCallInfo),
 
-			% add a forwarding predicate with the
-			% original interface.
+        % Add a forwarding predicate with the original interface.
 		create_call_goal(UnusedArgs, NewPredId, ProcId, PredModule,
 			NewPredName, OrigProcInfo, ForwardingProcInfo),
 		module_info_set_pred_proc_info(PredId, ProcId, OrigPredInfo,
 			ForwardingProcInfo, !ModuleInfo),
 
-			% add forwarding predicates for results
-			% produced in previous compilations.
+        % Add forwarding predicates for results produced in previous
+        % compilations.
 		list__foldl(
-			make_intermod_proc(PredId, NewPredId, ProcId,
-				NewPredName, OrigPredInfo, OrigProcInfo,
-				UnusedArgs),
+            make_intermod_proc(PredId, NewPredId, ProcId, NewPredName,
+                OrigPredInfo, OrigProcInfo, UnusedArgs),
 			IntermodResults, !ModuleInfo)
 	).
 
@@ -986,19 +977,18 @@
 make_intermod_proc(PredId, NewPredId, ProcId, NewPredName,
 		OrigPredInfo, OrigProcInfo, UnusedArgs,
 		UnusedArgs2, !ModuleInfo) :-
-	% Add an exported predicate with the number of removed
-	% arguments promised in the analysis file which just calls
-	% the new predicate.
+    % Add an exported predicate with the number of removed arguments promised
+    % in the analysis file which just calls the new predicate.
 	make_new_pred_info(!.ModuleInfo, UnusedArgs2, exported,
 		proc(PredId, ProcId), OrigPredInfo, ExtraPredInfo0),
 	PredModule = pred_info_module(OrigPredInfo),
 	create_call_goal(UnusedArgs, NewPredId, ProcId,
 		PredModule, NewPredName, OrigProcInfo, ExtraProc0),
 	proc_info_headvars(OrigProcInfo, HeadVars0),
-	remove_listof_elements(HeadVars0, 1, UnusedArgs2, IntermodHeadVars),
+    remove_listof_elements(1, UnusedArgs2, HeadVars0, IntermodHeadVars),
 	proc_info_set_headvars(IntermodHeadVars, ExtraProc0, ExtraProc1),
 	proc_info_argmodes(OrigProcInfo, ArgModes0),
-	remove_listof_elements(ArgModes0, 1, UnusedArgs2, IntermodArgModes),
+    remove_listof_elements(1, UnusedArgs2, ArgModes0, IntermodArgModes),
 	proc_info_set_argmodes(IntermodArgModes, ExtraProc1, ExtraProc),
 	pred_info_procedures(ExtraPredInfo0, ExtraProcs0),
 	map__set(ExtraProcs0, ProcId, ExtraProc, ExtraProcs),
@@ -1017,13 +1007,13 @@
 	PredOrFunc = pred_info_is_pred_or_func(!.PredInfo),
 	pred_info_arg_types(!.PredInfo, Tvars, ExistQVars, ArgTypes0),
 	pred_info_get_origin(!.PredInfo, OrigOrigin),
-		% create a unique new pred name using the old proc_id
+    % Create a unique new pred name using the old proc_id.
 	(
 		string__prefix(Name0, "__"),
 		\+ string__prefix(Name0, "__LambdaGoal__")
 	->
 		(
-				% fix up special pred names
+            % Fix up special pred names.
 			OrigOrigin = special_pred(_SpecialId - TypeCtor)
 		->
 			type_util__type_ctor_module(ModuleInfo,
@@ -1050,18 +1040,17 @@
 	),
 	make_pred_name(PredModule, "UnusedArgs", yes(PredOrFunc),
 		Name1, unused_args(UnusedArgs), Name2),
-	% The mode number is included because we want to
-	% avoid the creation of more than one predicate with the same
-	% name if more than one mode of a predicate is specialized.
-	% Since the names of e.g. deep profiling proc_static structures
-	% are derived from the names of predicates, duplicate predicate
-	% names lead to duplicate global variable names and hence to
-	% link errors.
+    % The mode number is included because we want to avoid the creation of
+    % more than one predicate with the same name if more than one mode of
+    % a predicate is specialized. Since the names of e.g. deep profiling
+    % proc_static structures are derived from the names of predicates,
+    % duplicate predicate names lead to duplicate global variable names
+    % and hence to link errors.
 	proc_id_to_int(ProcId, ProcInt),
 	add_sym_name_suffix(Name2, "_" ++ int_to_string(ProcInt), Name),
 	Arity = pred_info_orig_arity(!.PredInfo),
 	pred_info_typevarset(!.PredInfo, TypeVars),
-	remove_listof_elements(ArgTypes0, 1, UnusedArgs, ArgTypes),
+    remove_listof_elements(1, UnusedArgs, ArgTypes0, ArgTypes),
 	pred_info_context(!.PredInfo, Context),
 	pred_info_clauses_info(!.PredInfo, ClausesInfo),
 	pred_info_get_markers(!.PredInfo, Markers),
@@ -1069,10 +1058,9 @@
 	pred_info_get_class_context(!.PredInfo, ClassContext),
 	pred_info_get_aditi_owner(!.PredInfo, Owner),
 
-		% Since this pred_info isn't built until after the
-		% polymorphism transformation is complete, we just use
-		% dummy maps for the class constraints.
-		%
+    % Since this pred_info isn't built until after the polymorphism
+    % transformation is complete, we just use dummy maps for the class
+    % constraints.
 	map__init(EmptyProofs),
 	map__init(EmptyConstraintMap),
 	Origin = transformed(unused_argument_elimination(UnusedArgs),
@@ -1085,6 +1073,7 @@
 
 	% Replace the goal in the procedure with one to call the given
 	% pred_id and proc_id.
+    %
 :- pred create_call_goal(list(int)::in, pred_id::in, proc_id::in,
 	module_name::in, string::in, proc_info::in, proc_info::out) is det.
 
@@ -1094,22 +1083,21 @@
 	proc_info_goal(!.OldProc, Goal0),
 	Goal0 = _GoalExpr - GoalInfo0,
 
-		% We must use the interface determinism for determining
-		% the determinism of the version of the goal with its
-		% arguments removed, not the actual determinism of the
-		% body is it may be more lax, which will lead to code
-		% gen problems.
+    % We must use the interface determinism for determining the determinism
+    % of the version of the goal with its arguments removed, not the actual
+    % determinism of the body is it may be more lax, which will lead to code
+    % generation problems.
 	proc_info_interface_determinism(!.OldProc, Determinism),
-	goal_info_set_determinism(GoalInfo0, Determinism, GoalInfo1),
+    goal_info_set_determinism(Determinism, GoalInfo0, GoalInfo1),
 
 	proc_info_vartypes(!.OldProc, VarTypes0),
 	set__list_to_set(HeadVars, NonLocals),
 	map__apply_to_list(HeadVars, VarTypes0, VarTypeList),
 	map__from_corresponding_lists(HeadVars, VarTypeList, VarTypes1),
-		% the varset should probably be fixed up, but it
-		% shouldn't make too much difference
+    % The varset should probably be fixed up, but it shouldn't make
+    % too much difference.
 	proc_info_varset(!.OldProc, Varset0),
-	remove_listof_elements(HeadVars, 1, UnusedArgs, NewHeadVars),
+    remove_listof_elements(1, UnusedArgs, HeadVars, NewHeadVars),
 	GoalExpr = call(NewPredId, NewProcId, NewHeadVars,
 		not_builtin, no, qualified(PredModule, PredName)),
 	Goal1 = GoalExpr - GoalInfo1,
@@ -1121,6 +1109,7 @@
 
 	% Create a pred_info for an imported pred with a pragma unused_args
 	% in the .opt file.
+    %
 :- pred make_imported_unused_args_pred_info(pred_proc_id::in, list(int)::in,
 	proc_call_info::in, proc_call_info::out,
 	module_info::in, module_info::out) is det.
@@ -1128,18 +1117,18 @@
 make_imported_unused_args_pred_info(OptProc, UnusedArgs,
 		!ProcCallInfo, !ModuleInfo) :-
 	OptProc = proc(PredId, ProcId),
-	module_info_pred_proc_info(!.ModuleInfo,
-		PredId, ProcId, PredInfo0, ProcInfo0),
+    module_info_pred_proc_info(!.ModuleInfo, PredId, ProcId,
+        PredInfo0, ProcInfo0),
 	make_new_pred_info(!.ModuleInfo, UnusedArgs, imported(interface),
 		OptProc, PredInfo0, NewPredInfo0),
 	pred_info_procedures(NewPredInfo0, NewProcs0),
 
 		% Assign the old procedure to a new predicate.
 	proc_info_headvars(ProcInfo0, HeadVars0),
-	remove_listof_elements(HeadVars0, 1, UnusedArgs, HeadVars),
+    remove_listof_elements(1, UnusedArgs, HeadVars0, HeadVars),
 	proc_info_set_headvars(HeadVars, ProcInfo0, HeadVarsProcInfo),
 	proc_info_argmodes(HeadVarsProcInfo, ArgModes0),
-	remove_listof_elements(ArgModes0, 1, UnusedArgs, ArgModes),
+    remove_listof_elements(1, UnusedArgs, ArgModes0, ArgModes),
 	proc_info_set_argmodes(ArgModes, ProcInfo0, ProcInfo),
 	map__set(NewProcs0, ProcId, ProcInfo, NewProcs),
 	pred_info_set_procedures(NewProcs, NewPredInfo0, NewPredInfo),
@@ -1152,30 +1141,29 @@
 	PredName = pred_info_name(NewPredInfo),
 	PredSymName = qualified(PredModule, PredName),
 		% Add the new proc to the proc_call_info map.
-	map__det_insert(!.ProcCallInfo, proc(PredId, ProcId),
+    svmap__det_insert(proc(PredId, ProcId),
 		call_info(NewPredId, ProcId, PredSymName, UnusedArgs),
-		!:ProcCallInfo).
+        !ProcCallInfo).
 
-:- pred remove_listof_elements(list(T)::in, int::in, list(int)::in,
-	list(T)::out) is det.
+:- pred remove_listof_elements(int::in, list(int)::in,
+    list(T)::in, list(T)::out) is det.
 
-remove_listof_elements(List0, ArgNo, ElemsToRemove, List) :-
-	( ElemsToRemove = [] ->
-		List = List0
+remove_listof_elements(ArgNo, ElemsToRemove, !List) :-
+    (
+        ElemsToRemove = []
 	;
+        ElemsToRemove = [_ | _],
 		(
-			List0 = [Head | Tail],
+            !.List = [Head | Tail],
 			NextArg = ArgNo + 1,
+            remove_listof_elements(NextArg, ElemsToRemove, Tail, NewTail),
 			( list__member(ArgNo, ElemsToRemove) ->
-				List = List1
+                !:List = NewTail
 			;
-				List = [Head | List1]
-			),
-			remove_listof_elements(Tail, NextArg, ElemsToRemove,
-				List1)
+                !:List = [Head | NewTail]
+            )
 		;
-			List0 = [],
-			List = List0
+            !.List = []
 		)
 	).
 
@@ -1199,7 +1187,8 @@
 fixup_unused_args(_, [], _, !ModuleInfo, _, !IO).
 fixup_unused_args(VarUsage, [PredProc | PredProcs], ProcCallInfo,
 		!ModuleInfo, VeryVerbose, !IO) :-
-	( VeryVerbose = yes ->
+    (
+        VeryVerbose = yes,
 		PredProc = proc(PredId, ProcId),
 		io__write_string("% Fixing up `", !IO),
 		predicate_name(!.ModuleInfo, PredId, Name),
@@ -1212,7 +1201,7 @@
 		io__write_int(ProcInt, !IO),
 		io__write_char('\n', !IO)
 	;
-		true
+        VeryVerbose = no
 	),
 	do_fixup_unused_args(VarUsage, PredProc, ProcCallInfo, !ModuleInfo),
 	fixup_unused_args(VarUsage, PredProcs, ProcCallInfo, !ModuleInfo,
@@ -1224,7 +1213,7 @@
 do_fixup_unused_args(VarUsage, proc(OldPredId, OldProcId), ProcCallInfo,
 		ModuleInfo0, ModuleInfo) :-
 	(
-			% work out which proc we should be fixing up
+        % Work out which proc we should be fixing up.
 		map__search(ProcCallInfo, proc(OldPredId, OldProcId),
 			call_info(NewPredId, NewProcId, _, UnusedArgs0))
 	->
@@ -1238,8 +1227,8 @@
 	),
 	map__lookup(VarUsage, proc(OldPredId, OldProcId), UsageInfos),
 	map__keys(UsageInfos, UnusedVars),
-	module_info_pred_proc_info(ModuleInfo0, PredId, ProcId, PredInfo0,
-		ProcInfo0),
+    module_info_pred_proc_info(ModuleInfo0, PredId, ProcId,
+        PredInfo0, ProcInfo0),
 	proc_info_vartypes(ProcInfo0, VarTypes0),
 	module_info_preds(ModuleInfo0, Preds0),
 	pred_info_procedures(PredInfo0, Procs0),
@@ -1248,17 +1237,16 @@
 	proc_info_argmodes(ProcInfo0, ArgModes0),
 	proc_info_varset(ProcInfo0, Varset0),
 	proc_info_goal(ProcInfo0, Goal0),
-	remove_listof_elements(HeadVars0, 1, UnusedArgs, HeadVars),
-	remove_listof_elements(ArgModes0, 1, UnusedArgs, ArgModes),
+    remove_listof_elements(1, UnusedArgs, HeadVars0, HeadVars),
+    remove_listof_elements(1, UnusedArgs, ArgModes0, ArgModes),
 	proc_info_set_headvars(HeadVars, ProcInfo0, FixedProc1),
 	proc_info_set_argmodes(ArgModes, FixedProc1, FixedProc2),
 
-		% remove unused vars from goal
-	fixup_goal(ModuleInfo0, UnusedVars, ProcCallInfo, Changed,
-		Goal0, Goal1),
+    % Remove unused vars from goal.
+    fixup_goal(ModuleInfo0, UnusedVars, ProcCallInfo, Changed, Goal0, Goal1),
 	(
 		Changed = yes,
-			% if anything has changed, rerun quantification
+        % If anything has changed, rerun quantification.
 		set__list_to_set(HeadVars, NonLocals),
 		implicitly_quantify_goal(NonLocals, _, Goal1, Goal,
 			Varset0, Varset, VarTypes0, VarTypes),
@@ -1274,7 +1262,8 @@
 	map__set(Preds0, PredId, PredInfo, Preds),
 	module_info_set_preds(Preds, ModuleInfo0, ModuleInfo).
 
-	% this is the important bit of the transformation
+    % This is the important bit of the transformation.
+    %
 :- pred fixup_goal(module_info::in, list(prog_var)::in, proc_call_info::in,
 	bool::out, hlds_goal::in, hlds_goal::out) is det.
 
@@ -1344,7 +1333,7 @@
 			call_info(NewPredId, NewProcId, NewName, UnusedArgs))
 	->
 		Changed = yes,
-		remove_listof_elements(ArgVars0, 1, UnusedArgs, ArgVars),
+        remove_listof_elements(1, UnusedArgs, ArgVars0, ArgVars),
 		PredId = NewPredId,
 		ProcId = NewProcId,
 		Name = NewName
@@ -1388,13 +1377,13 @@
 		[Goal0 | Goals0], Goals) :-
 	fixup_goal(ModuleInfo, UnusedVars, ProcCallInfo, LocalChanged,
 		Goal0, Goal),
-	( LocalChanged = yes ->
+    (
+        LocalChanged = yes,
 		!:Changed = yes
 	;
-		true
+        LocalChanged = no
 	),
-		% replacing a goal with conj([]) signals that it is
-		%	no longer needed
+    % Replacing a goal with conj([]) signals that it is no longer needed.
 	( Goal = conj([]) - _ ->
 		Goals = Goals1
 	;
@@ -1404,8 +1393,8 @@
 		Goals0, Goals1).
 
 	% We can't remove unused goals from the list of disjuncts as we do
-	% for conjuncts, since that would change the determinism of
-	% the goal.
+    % for conjuncts, since that would change the determinism of the goal.
+    %
 :- pred fixup_disjuncts(module_info::in, list(prog_var)::in, proc_call_info::in,
 	bool::in, bool::out, hlds_goals::in, hlds_goals::out) is det.
 
@@ -1414,10 +1403,11 @@
 		[Goal0 | Goals0], [Goal | Goals]) :-
 	fixup_goal(ModuleInfo, UnusedVars, ProcCallInfo, LocalChanged,
 		Goal0, Goal),
-	( LocalChanged = yes ->
+    (
+        LocalChanged = yes,
 		!:Changed = yes
 	;
-		true
+        LocalChanged = no
 	),
 	fixup_disjuncts(ModuleInfo, UnusedVars, ProcCallInfo, !Changed,
 		Goals0, Goals).
@@ -1431,20 +1421,21 @@
 		[case(ConsId, Goal) | Cases]) :-
 	fixup_goal(ModuleInfo, UnusedVars, ProcCallInfo, LocalChanged,
 		Goal0, Goal),
-	( LocalChanged = yes ->
+    (
+        LocalChanged = yes,
 		!:Changed = yes
 	;
-		true
+        LocalChanged = no
 	),
 	fixup_cases(ModuleInfo, UnusedVars, ProcCallInfo, !Changed,
 		Cases0, Cases).
 
-	% fix up a unification, fail if the unification is no
-	%	longer needed
+    % Fix up a unification, fail if the unification is no longer needed.
+    %
 :- pred fixup_unify(module_info::in, list(prog_var)::in, bool::out,
 	unification::in, unification::out) is semidet.
 
-	% a simple test doesn't have any unused vars to fixup
+    % A simple test doesn't have any unused vars to fixup.
 fixup_unify(_, _UnusedVars, no, simple_test(A, B), simple_test(A, B)).
 
 	% Var1 unused => we don't need the assignment
@@ -1461,11 +1452,10 @@
 	Unify =	deconstruct(LVar, _, ArgVars, ArgModes, CanFail, _CanCGC),
 	\+ list__member(LVar, UnusedVars),
 	(
-			% are any of the args unused, if so we need to
-			% to fix up the goal_info
+        % Are any of the args unused, if so we need to to fix up the goal_info.
 		CanFail = cannot_fail,
-		check_deconstruct_args(ModuleInfo, UnusedVars, ArgVars,
-			ArgModes, Changed, no)
+        check_deconstruct_args(ModuleInfo, UnusedVars, ArgVars, ArgModes,
+            Changed, no)
 	;
 		CanFail = can_fail,
 		Changed = no
@@ -1479,6 +1469,7 @@
 	% so Changed will be yes and quantification will be rerun. Fails if
 	% none of the arguments are used. Arguments which further instantiate
 	% the deconstructed variable are ignored in this.
+    %
 :- pred check_deconstruct_args(module_info::in, list(prog_var)::in,
 	list(prog_var)::in, list(uni_mode)::in,
 	bool::out, bool::in) is semidet.
@@ -1493,12 +1484,12 @@
 			mode_is_output(ModuleInfo, (Inst1 -> Inst2)),
 			list__member(ArgVar, UnusedVars)
 		->
-			check_deconstruct_args(ModuleInfo, UnusedVars,
-				ArgVars, ArgModes, _, Used),
+            check_deconstruct_args(ModuleInfo, UnusedVars, ArgVars, ArgModes,
+                _, Used),
 			Changed = yes
 		;
-			check_deconstruct_args(ModuleInfo, UnusedVars,
-				ArgVars, ArgModes, Changed, yes)
+            check_deconstruct_args(ModuleInfo, UnusedVars, ArgVars, ArgModes,
+                Changed, yes)
 		)
 	;
 		Args = [],
@@ -1507,25 +1498,25 @@
 		Changed = no,
 		Used = yes
 	;
-		error("check_deconstruct_args - invalid call")
+        unexpected(this_file, "check_deconstruct_args - invalid call")
 	).
 
-	% Remove unused vars from the instmap_delta, quantification fixes
-	%	up the rest.
+    % Remove unused vars from the instmap_delta, quantification fixes up
+    % the rest.
+    %
 :- pred fixup_goal_info(list(prog_var)::in, hlds_goal_info::in,
 	hlds_goal_info::out) is det.
 
 fixup_goal_info(UnusedVars, !GoalInfo) :-
 	goal_info_get_instmap_delta(!.GoalInfo, InstMap0),
-	instmap_delta_delete_vars(InstMap0, UnusedVars, InstMap),
-	goal_info_set_instmap_delta(!.GoalInfo, InstMap, !:GoalInfo).
+    instmap_delta_delete_vars(UnusedVars, InstMap0, InstMap),
+    goal_info_set_instmap_delta(InstMap, !GoalInfo).
 
 %-------------------------------------------------------------------------------
 
-		% Except for type_infos, all args that are unused
-		% in one mode of a predicate should be unused in all of the
-		% modes of a predicate, so we only need to put out one warning
-		% for each predicate.
+    % Except for type_infos, all args that are unused in one mode of a
+    % predicate should be unused in all of the modes of a predicate, so we only
+    % need to put out one warning for each predicate.
 :- pred output_warnings_and_pragmas(module_info::in, unused_arg_info::in,
 	maybe(io__output_stream)::in, bool::in, pred_proc_list::in,
 	set(pred_id)::in, io::di, io::uo) is det.
@@ -1539,36 +1530,33 @@
 			Name = pred_info_name(PredInfo),
 			\+ pred_info_is_imported(PredInfo),
 			\+ pred_info_import_status(PredInfo, opt_imported),
-				% Don't warn about builtins
-				% that have unused arguments.
+
+            % Don't warn about builtins that have unused arguments.
 			\+ pred_info_is_builtin(PredInfo),
 			\+ is_unify_or_compare_pred(PredInfo),
-				% Don't warn about stubs for procedures
-				% with no clauses -- in that case,
-				% we *expect* that none of the arguments
+
+            % Don't warn about stubs for procedures with no clauses --
+            % in that case, we *expect* that none of the arguments
 				% will be used,
 			pred_info_get_markers(PredInfo, Markers),
 			\+ check_marker(Markers, stub),
-				% Don't warn about lambda expressions
-				% not using arguments. (The warning
-				% message for these doesn't contain
-				% context, so it's useless)
-			\+ string__sub_string_search(Name,
-				"__LambdaGoal__", _),
+
+            % Don't warn about lambda expressions not using arguments.
+            % (The warning message for these doesn't contain context,
+            % so it's useless).
+            \+ string__sub_string_search(Name, "__LambdaGoal__", _),
+
+            % Don't warn for a specialized version.
 			\+ (
-				% don't warn for a specialized version
-				string__sub_string_search(Name, "__ho",
-					Position),
+                string__sub_string_search(Name, "__ho", Position),
 				string__length(Name, Length),
 				IdLen = Length - Position - 4,
 				string__right(Name, IdLen, Id),
 				string__to_int(Id, _)
 			),
-			% XXX We don't currently generate pragmas
-			% for the automatically generated class
-			% instance methods because the compiler
-			% aborts when trying to read them back in
-			% from the `.opt' files. 
+            % XXX We don't currently generate pragmas for the automatically
+            % generated class instance methods because the compiler aborts
+            % when trying to read them back in from the `.opt' files. 
 			\+ check_marker(Markers, class_instance_method),
 			\+ check_marker(Markers, named_class_instance_method)	
 
@@ -1576,8 +1564,7 @@
 			write_unused_args_to_opt_file(WriteOptPragmas,
 				PredInfo, ProcId, UnusedArgs, !IO),
 			maybe_warn_unused_args(DoWarn, ModuleInfo, PredInfo,
-				PredId, ProcId, UnusedArgs, !WarnedPredIds,
-				!IO)
+                PredId, ProcId, UnusedArgs, !WarnedPredIds, !IO)
 		;
 			true
 		)
@@ -1598,7 +1585,7 @@
 		; pred_info_is_opt_exported(PredInfo)
 		; pred_info_is_exported_to_submodules(PredInfo)
 		),
-		UnusedArgs \= []
+        UnusedArgs = [_ | _]
 	->
 		Module = pred_info_module(PredInfo),
 		Name = pred_info_name(PredInfo),
@@ -1606,9 +1593,8 @@
 		PredOrFunc = pred_info_is_pred_or_func(PredInfo),
 		io__set_output_stream(OptStream, OldOutput, !IO),
 		proc_id_to_int(ProcId, ModeNum),
-		mercury_output_pragma_unused_args(PredOrFunc,
-			qualified(Module, Name), Arity, ModeNum, UnusedArgs,
-			!IO),
+        mercury_output_pragma_unused_args(PredOrFunc, qualified(Module, Name),
+            Arity, ModeNum, UnusedArgs, !IO),
 		io__set_output_stream(OldOutput, _, !IO)
 	;
 		true
@@ -1642,44 +1628,8 @@
 		)
 	).
 
-	% Warn about unused arguments in a predicate. Only arguments unused
-	% in every mode of a predicate are warned about. The warning is
-	% suppressed for type_infos.
-:- pred report_unused_args(pred_info::in, list(int)::in,
-	io::di, io::uo) is det.
-
-report_unused_args(PredInfo, UnusedArgs) -->
-	{ list__length(UnusedArgs, NumArgs) },
-	{ pred_info_context(PredInfo, Context) },
-	{ PredOrFunc = pred_info_is_pred_or_func(PredInfo) },
-	{ Module = pred_info_module(PredInfo) },
-	{ Name = pred_info_name(PredInfo) },
-	{ Arity = pred_info_orig_arity(PredInfo) },
-	prog_out__write_context(Context),
-	io__write_string("In "),
-	write_pred_or_func(PredOrFunc),
-	io__write_string(" `"),
-	prog_out__write_sym_name(Module),
-	io__write_string("."),
-	io__write_string(Name),
-	io__write_string("/"),
-	io__write_int(Arity),
-	io__write_string("':\n"),
-	prog_out__write_context(Context),
-	io__write_string("  warning: "),
-	(
-		{ NumArgs = 1 }
-	->
-		io__write_string("argument "),
-		output_arg_list(UnusedArgs),
-		io__write_string(" is unused.\n")
-	;
-		io__write_string("arguments "),
-		output_arg_list(UnusedArgs),
-		io__write_string(" are unused.\n")
-	).
-
-	% adjust warning message for the presence of type_infos.
+    % Adjust warning message for the presence of type_infos.
+    %
 :- pred adjust_unused_args(int::in, list(int)::in, list(int)::out) is det.
 
 adjust_unused_args(_, [], []).
@@ -1692,33 +1642,62 @@
 	),
 	adjust_unused_args(NumToDrop, UnusedArgNos0, AdjUnusedArgs1).
 
-:- pred output_arg_list(list(int)::in, io::di, io::uo) is det.
+    % Warn about unused arguments in a predicate. Only arguments unused
+    % in every mode of a predicate are warned about. The warning is
+    % suppressed for type_infos.
+    %
+:- pred report_unused_args(pred_info::in, list(int)::in,
+    io::di, io::uo) is det.
 
-output_arg_list([], !IO) :-
-	error("output_list_int called with empty list").
-output_arg_list([Arg | Rest], !IO) :-
-	io__write_int(Arg, !IO),
+report_unused_args(PredInfo, UnusedArgs, !IO) :-
+    list__length(UnusedArgs, NumArgs),
+    pred_info_context(PredInfo, Context),
+    PredOrFunc = pred_info_is_pred_or_func(PredInfo),
+    Module = pred_info_module(PredInfo),
+    Name = pred_info_name(PredInfo),
+    Arity = pred_info_orig_arity(PredInfo),
+    Pieces1 = [words("In"), fixed(pred_or_func_to_full_str(PredOrFunc)),
+        sym_name_and_arity(qualified(Module, Name) / Arity), suffix(":"), nl,
+        words("warning:")],
+    ( NumArgs = 1 ->
+        Pieces2 = [words("argument") | format_arg_list(UnusedArgs)] ++
+            [words("is unused."), nl]
+    ;
+        Pieces2 = [words("arguments") | format_arg_list(UnusedArgs)] ++
+            [words("are unused."), nl]
+    ),
+    write_error_pieces(Context, 0, Pieces1 ++ Pieces2, !IO).
+
+:- func format_arg_list(list(int)) = list(format_component).
+
+format_arg_list([]) = func_error("format_arg_list: empty list").
+format_arg_list([Arg | Rest]) = Pieces :-
+    ArgStr = int_to_string(Arg),
 	(
-		Rest = []
+        Rest = [],
+        Pieces = [fixed(ArgStr)]
 	;
-		Rest = [_ | _],
-		output_arg_list_2(Rest, !IO)
+        Rest = [Head | Tail],
+        Pieces = [fixed(ArgStr) | format_arg_list_2(Head, Tail)]
 	).
 
-:- pred output_arg_list_2(list(int)::in, io::di, io::uo) is det.
+:- func format_arg_list_2(int, list(int)) = list(format_component).
 
-output_arg_list_2(Args, !IO) :-
+format_arg_list_2(First, List) = Pieces :-
+    FirstStr = int_to_string(First),
 	(
-		Args = [First, Second | Rest]
-	->
-		io__write_string(", ", !IO),
-		io__write_int(First, !IO),
-		output_arg_list_2([Second | Rest], !IO)
-	;
-		Args = [Last]
-	->
-		io__write_string(" and ", !IO),
-		io__write_int(Last, !IO)
+        List = [Second | Rest],
+        Pieces = [suffix(","), fixed(FirstStr) |
+            format_arg_list_2(Second, Rest)]
 	;
-		error("output_arg_list_2 called with empty list")
+        List = [],
+        Pieces = [fixed("and"), fixed(FirstStr)]
 	).
+
+%-----------------------------------------------------------------------------%
+
+:- func this_file = string.
+
+this_file = "unused_args.m".
+
+%-----------------------------------------------------------------------------%
cvs diff: Diffing compiler/notes
cvs diff: Diffing debian
cvs diff: Diffing deep_profiler
cvs diff: Diffing deep_profiler/notes
cvs diff: Diffing doc
cvs diff: Diffing extras
cvs diff: Diffing extras/aditi
cvs diff: Diffing extras/cgi
cvs diff: Diffing extras/complex_numbers
cvs diff: Diffing extras/complex_numbers/samples
cvs diff: Diffing extras/complex_numbers/tests
cvs diff: Diffing extras/concurrency
cvs diff: Diffing extras/curs
cvs diff: Diffing extras/curs/samples
cvs diff: Diffing extras/curses
cvs diff: Diffing extras/curses/sample
cvs diff: Diffing extras/dynamic_linking
cvs diff: Diffing extras/error
cvs diff: Diffing extras/graphics
cvs diff: Diffing extras/graphics/easyx
cvs diff: Diffing extras/graphics/easyx/samples
cvs diff: Diffing extras/graphics/mercury_glut
cvs diff: Diffing extras/graphics/mercury_opengl
cvs diff: Diffing extras/graphics/mercury_tcltk
cvs diff: Diffing extras/graphics/samples
cvs diff: Diffing extras/graphics/samples/calc
cvs diff: Diffing extras/graphics/samples/gears
cvs diff: Diffing extras/graphics/samples/maze
cvs diff: Diffing extras/graphics/samples/pent
cvs diff: Diffing extras/lazy_evaluation
cvs diff: Diffing extras/lex
cvs diff: Diffing extras/lex/samples
cvs diff: Diffing extras/lex/tests
cvs diff: Diffing extras/logged_output
cvs diff: Diffing extras/moose
cvs diff: Diffing extras/moose/samples
cvs diff: Diffing extras/moose/tests
cvs diff: Diffing extras/morphine
cvs diff: Diffing extras/morphine/non-regression-tests
cvs diff: Diffing extras/morphine/scripts
cvs diff: Diffing extras/morphine/source
cvs diff: Diffing extras/odbc
cvs diff: Diffing extras/posix
cvs diff: Diffing extras/quickcheck
cvs diff: Diffing extras/quickcheck/tutes
cvs diff: Diffing extras/references
cvs diff: Diffing extras/references/samples
cvs diff: Diffing extras/references/tests
cvs diff: Diffing extras/stream
cvs diff: Diffing extras/trailed_update
cvs diff: Diffing extras/trailed_update/samples
cvs diff: Diffing extras/trailed_update/tests
cvs diff: Diffing extras/xml
cvs diff: Diffing extras/xml/samples
cvs diff: Diffing extras/xml_stylesheets
cvs diff: Diffing java
cvs diff: Diffing java/runtime
cvs diff: Diffing library
cvs diff: Diffing mdbcomp
cvs diff: Diffing profiler
cvs diff: Diffing robdd
cvs diff: Diffing runtime
cvs diff: Diffing runtime/GETOPT
cvs diff: Diffing runtime/machdeps
cvs diff: Diffing samples
cvs diff: Diffing samples/c_interface
cvs diff: Diffing samples/c_interface/c_calls_mercury
cvs diff: Diffing samples/c_interface/cplusplus_calls_mercury
cvs diff: Diffing samples/c_interface/mercury_calls_c
cvs diff: Diffing samples/c_interface/mercury_calls_cplusplus
cvs diff: Diffing samples/c_interface/mercury_calls_fortran
cvs diff: Diffing samples/c_interface/simpler_c_calls_mercury
cvs diff: Diffing samples/c_interface/simpler_cplusplus_calls_mercury
cvs diff: Diffing samples/diff
cvs diff: Diffing samples/muz
cvs diff: Diffing samples/rot13
cvs diff: Diffing samples/solutions
cvs diff: Diffing samples/tests
cvs diff: Diffing samples/tests/c_interface
cvs diff: Diffing samples/tests/c_interface/c_calls_mercury
cvs diff: Diffing samples/tests/c_interface/cplusplus_calls_mercury
cvs diff: Diffing samples/tests/c_interface/mercury_calls_c
cvs diff: Diffing samples/tests/c_interface/mercury_calls_cplusplus
cvs diff: Diffing samples/tests/c_interface/mercury_calls_fortran
cvs diff: Diffing samples/tests/c_interface/simpler_c_calls_mercury
cvs diff: Diffing samples/tests/c_interface/simpler_cplusplus_calls_mercury
cvs diff: Diffing samples/tests/diff
cvs diff: Diffing samples/tests/muz
cvs diff: Diffing samples/tests/rot13
cvs diff: Diffing samples/tests/solutions
cvs diff: Diffing samples/tests/toplevel
cvs diff: Diffing scripts
cvs diff: Diffing slice
cvs diff: Diffing tests
cvs diff: Diffing tests/benchmarks
cvs diff: Diffing tests/debugger
cvs diff: Diffing tests/debugger/declarative
cvs diff: Diffing tests/dppd
cvs diff: Diffing tests/general
cvs diff: Diffing tests/general/accumulator
cvs diff: Diffing tests/general/string_format
cvs diff: Diffing tests/general/structure_reuse
cvs diff: Diffing tests/grade_subdirs
cvs diff: Diffing tests/hard_coded
cvs diff: Diffing tests/hard_coded/exceptions
cvs diff: Diffing tests/hard_coded/purity
cvs diff: Diffing tests/hard_coded/sub-modules
cvs diff: Diffing tests/hard_coded/typeclasses
cvs diff: Diffing tests/invalid
Index: tests/invalid/circ_inst.err_exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/invalid/circ_inst.err_exp,v
retrieving revision 1.2
diff -u -b -r1.2 circ_inst.err_exp
--- tests/invalid/circ_inst.err_exp	17 Jan 2003 05:57:07 -0000	1.2
+++ tests/invalid/circ_inst.err_exp	28 Aug 2005 23:14:08 -0000
@@ -1,4 +1,4 @@
-circ_inst.m:006: Error: circular equivalence inst `circ_inst.circ/0'.
-circ_inst.m:010: Error: circular equivalence insts `circ_inst.circ1/0' and
-circ_inst.m:010:   `circ_inst.circ2/0'.
+circ_inst.m:006: Error: circular equivalence inst `circ_inst.circ'/0.
+circ_inst.m:010: Error: circular equivalence insts `circ_inst.circ1'/0 and
+circ_inst.m:010:   `circ_inst.circ2'/0.
 For more information, try recompiling with `-E'.
Index: tests/invalid/circ_inst2.err_exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/invalid/circ_inst2.err_exp,v
retrieving revision 1.2
diff -u -b -r1.2 circ_inst2.err_exp
--- tests/invalid/circ_inst2.err_exp	17 Jan 2003 05:57:07 -0000	1.2
+++ tests/invalid/circ_inst2.err_exp	28 Aug 2005 23:14:09 -0000
@@ -1,6 +1,6 @@
-circ_inst2.m:010: Error: circular equivalence inst `circ_inst2.circ1/1'.
-circ_inst2.m:011: Error: circular equivalence inst `circ_inst2.circ2/1'.
-circ_inst2.m:013: Error: circular equivalence inst `circ_inst2.circ4/1'.
-circ_inst2.m:016: Error: circular equivalence insts `circ_inst2.left/1' and
-circ_inst2.m:016:   `circ_inst2.right/1'.
+circ_inst2.m:010: Error: circular equivalence inst `circ_inst2.circ1'/1.
+circ_inst2.m:011: Error: circular equivalence inst `circ_inst2.circ2'/1.
+circ_inst2.m:013: Error: circular equivalence inst `circ_inst2.circ4'/1.
+circ_inst2.m:016: Error: circular equivalence insts `circ_inst2.left'/1 and
+circ_inst2.m:016:   `circ_inst2.right'/1.
 For more information, try recompiling with `-E'.
Index: tests/invalid/circ_inst3.err_exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/invalid/circ_inst3.err_exp,v
retrieving revision 1.2
diff -u -b -r1.2 circ_inst3.err_exp
--- tests/invalid/circ_inst3.err_exp	17 Jan 2003 05:57:07 -0000	1.2
+++ tests/invalid/circ_inst3.err_exp	28 Aug 2005 23:14:09 -0000
@@ -1,4 +1,4 @@
-circ_inst3.m:009: Error: circular equivalence inst `circ_inst3.circ/0'.
-circ_inst3.m:013: Error: circular equivalence insts `circ_inst3.circ1/0' and
-circ_inst3.m:013:   `circ_inst3.circ2/0'.
+circ_inst3.m:009: Error: circular equivalence inst `circ_inst3.circ'/0.
+circ_inst3.m:013: Error: circular equivalence insts `circ_inst3.circ1'/0 and
+circ_inst3.m:013:   `circ_inst3.circ2'/0.
 For more information, try recompiling with `-E'.
Index: tests/invalid/circ_inst4.err_exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/invalid/circ_inst4.err_exp,v
retrieving revision 1.2
diff -u -b -r1.2 circ_inst4.err_exp
--- tests/invalid/circ_inst4.err_exp	17 Jan 2003 05:57:07 -0000	1.2
+++ tests/invalid/circ_inst4.err_exp	28 Aug 2005 23:14:09 -0000
@@ -1,6 +1,6 @@
-circ_inst4.m:010: Error: circular equivalence inst `circ_inst4.circ1/1'.
-circ_inst4.m:011: Error: circular equivalence inst `circ_inst4.circ2/1'.
-circ_inst4.m:013: Error: circular equivalence inst `circ_inst4.circ4/1'.
-circ_inst4.m:016: Error: circular equivalence insts `circ_inst4.left/1' and
-circ_inst4.m:016:   `circ_inst4.right/1'.
+circ_inst4.m:010: Error: circular equivalence inst `circ_inst4.circ1'/1.
+circ_inst4.m:011: Error: circular equivalence inst `circ_inst4.circ2'/1.
+circ_inst4.m:013: Error: circular equivalence inst `circ_inst4.circ4'/1.
+circ_inst4.m:016: Error: circular equivalence insts `circ_inst4.left'/1 and
+circ_inst4.m:016:   `circ_inst4.right'/1.
 For more information, try recompiling with `-E'.
Index: tests/invalid/circ_inst5.err_exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/invalid/circ_inst5.err_exp,v
retrieving revision 1.2
diff -u -b -r1.2 circ_inst5.err_exp
--- tests/invalid/circ_inst5.err_exp	18 Jan 2003 05:50:18 -0000	1.2
+++ tests/invalid/circ_inst5.err_exp	28 Aug 2005 23:14:10 -0000
@@ -1,3 +1,3 @@
-circ_inst5.m:005: Error: circular equivalence insts `circ_inst5.i/1' and
-circ_inst5.m:005:   `circ_inst5.c/1'.
+circ_inst5.m:005: Error: circular equivalence insts `circ_inst5.i'/1 and
+circ_inst5.m:005:   `circ_inst5.c'/1.
 For more information, try recompiling with `-E'.
Index: tests/invalid/circ_mode.err_exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/invalid/circ_mode.err_exp,v
retrieving revision 1.2
diff -u -b -r1.2 circ_mode.err_exp
--- tests/invalid/circ_mode.err_exp	17 Jan 2003 05:57:07 -0000	1.2
+++ tests/invalid/circ_mode.err_exp	28 Aug 2005 23:14:10 -0000
@@ -1,4 +1,4 @@
-circ_mode.m:006: Error: circular equivalence mode `circ_mode.circ/0'.
-circ_mode.m:010: Error: circular equivalence modes `circ_mode.circ1/0' and
-circ_mode.m:010:   `circ_mode.circ2/0'.
+circ_mode.m:006: Error: circular equivalence mode `circ_mode.circ'/0.
+circ_mode.m:010: Error: circular equivalence modes `circ_mode.circ1'/0 and
+circ_mode.m:010:   `circ_mode.circ2'/0.
 For more information, try recompiling with `-E'.
Index: tests/invalid/circ_mode2.err_exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/invalid/circ_mode2.err_exp,v
retrieving revision 1.2
diff -u -b -r1.2 circ_mode2.err_exp
--- tests/invalid/circ_mode2.err_exp	17 Jan 2003 05:57:07 -0000	1.2
+++ tests/invalid/circ_mode2.err_exp	28 Aug 2005 23:14:10 -0000
@@ -1,5 +1,5 @@
-circ_mode2.m:010: Error: circular equivalence mode `circ_mode2.circ1/1'.
-circ_mode2.m:011: Error: circular equivalence mode `circ_mode2.circ2/1'.
-circ_mode2.m:014: Error: circular equivalence modes `circ_mode2.left/1' and
-circ_mode2.m:014:   `circ_mode2.right/1'.
+circ_mode2.m:010: Error: circular equivalence mode `circ_mode2.circ1'/1.
+circ_mode2.m:011: Error: circular equivalence mode `circ_mode2.circ2'/1.
+circ_mode2.m:014: Error: circular equivalence modes `circ_mode2.left'/1 and
+circ_mode2.m:014:   `circ_mode2.right'/1.
 For more information, try recompiling with `-E'.
Index: tests/invalid/circ_mode3.err_exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/invalid/circ_mode3.err_exp,v
retrieving revision 1.2
diff -u -b -r1.2 circ_mode3.err_exp
--- tests/invalid/circ_mode3.err_exp	17 Jan 2003 05:57:07 -0000	1.2
+++ tests/invalid/circ_mode3.err_exp	28 Aug 2005 23:14:11 -0000
@@ -1,4 +1,4 @@
-circ_mode3.m:009: Error: circular equivalence mode `circ_mode3.circ/0'.
-circ_mode3.m:013: Error: circular equivalence modes `circ_mode3.circ1/0' and
-circ_mode3.m:013:   `circ_mode3.circ2/0'.
+circ_mode3.m:009: Error: circular equivalence mode `circ_mode3.circ'/0.
+circ_mode3.m:013: Error: circular equivalence modes `circ_mode3.circ1'/0 and
+circ_mode3.m:013:   `circ_mode3.circ2'/0.
 For more information, try recompiling with `-E'.
Index: tests/invalid/circ_mode4.err_exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/invalid/circ_mode4.err_exp,v
retrieving revision 1.2
diff -u -b -r1.2 circ_mode4.err_exp
--- tests/invalid/circ_mode4.err_exp	17 Jan 2003 05:57:07 -0000	1.2
+++ tests/invalid/circ_mode4.err_exp	28 Aug 2005 23:14:11 -0000
@@ -1,5 +1,5 @@
-circ_mode4.m:010: Error: circular equivalence mode `circ_mode4.circ1/1'.
-circ_mode4.m:011: Error: circular equivalence mode `circ_mode4.circ2/1'.
-circ_mode4.m:014: Error: circular equivalence modes `circ_mode4.left/1' and
-circ_mode4.m:014:   `circ_mode4.right/1'.
+circ_mode4.m:010: Error: circular equivalence mode `circ_mode4.circ1'/1.
+circ_mode4.m:011: Error: circular equivalence mode `circ_mode4.circ2'/1.
+circ_mode4.m:014: Error: circular equivalence modes `circ_mode4.left'/1 and
+circ_mode4.m:014:   `circ_mode4.right'/1.
 For more information, try recompiling with `-E'.
cvs diff: Diffing tests/invalid/purity
cvs diff: Diffing tests/misc_tests
cvs diff: Diffing tests/mmc_make
cvs diff: Diffing tests/mmc_make/lib
cvs diff: Diffing tests/recompilation
cvs diff: Diffing tests/tabling
cvs diff: Diffing tests/term
cvs diff: Diffing tests/valid
cvs diff: Diffing tests/warnings
Index: tests/warnings/unused_args_analysis.exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/warnings/unused_args_analysis.exp,v
retrieving revision 1.2
diff -u -b -r1.2 unused_args_analysis.exp
--- tests/warnings/unused_args_analysis.exp	18 Jan 2003 16:43:42 -0000	1.2
+++ tests/warnings/unused_args_analysis.exp	28 Aug 2005 23:32:45 -0000
@@ -1,2 +1,2 @@
-unused_args_analysis.m:005: In predicate `unused_args_analysis.p/2':
+unused_args_analysis.m:005: In predicate `unused_args_analysis.p'/2:
 unused_args_analysis.m:005:   warning: argument 1 is unused.
Index: tests/warnings/unused_args_test.exp
===================================================================
RCS file: /home/mercury/mercury1/repository/tests/warnings/unused_args_test.exp,v
retrieving revision 1.6
diff -u -b -r1.6 unused_args_test.exp
--- tests/warnings/unused_args_test.exp	17 Jan 2003 05:57:19 -0000	1.6
+++ tests/warnings/unused_args_test.exp	28 Aug 2005 23:32:47 -0000
@@ -1,4 +1,4 @@
-unused_args_test.m:009: In predicate `unused_args_test.recursive/3':
+unused_args_test.m:009: In predicate `unused_args_test.recursive'/3:
 unused_args_test.m:009:   warning: argument 1 is unused.
-unused_args_test.m:011: In predicate `unused_args_test.nonrecursive/1':
+unused_args_test.m:011: In predicate `unused_args_test.nonrecursive'/1:
 unused_args_test.m:011:   warning: argument 1 is unused.
cvs diff: Diffing tools
cvs diff: Diffing trace
cvs diff: Diffing util
cvs diff: Diffing vim
cvs diff: Diffing vim/after
cvs diff: Diffing vim/ftplugin
cvs diff: Diffing vim/syntax
--------------------------------------------------------------------------
mercury-reviews mailing list
post:  mercury-reviews at cs.mu.oz.au
administrative address: owner-mercury-reviews at cs.mu.oz.au
unsubscribe: Address: mercury-reviews-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-reviews-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the reviews mailing list