[m-rev.] diff: clean up mercury_compile.m

Zoltan Somogyi zs at cs.mu.OZ.AU
Fri Jan 30 16:49:52 AEDT 2004


compiler/mercury_compile.m:
	Bring this module up to date with our current coding standards. Use
	predmode declarations and state variable syntax where appropriate.
	Reorder predicate arguments where this is needed for the use of state
	variable syntax. Replace lambda expressions with explicitly named
	predicates where appropriate. Break up predicates that are excessively
	long and/or excessively deeply indented. Fix inconsistent indentation
	and wrap 80+ column lines.

	The only algorithmic change is the replacement of some calls to
	io__write with calls to predicates in error_util.

compiler/error_util.m:
	Add a predicate for printing messages without context, for use by
	mercury_compile.m to report problems that are not specific to
	a single predicate, e.g. inconsistent options.

	Bring this module up to date with our coding standards. Use predmode
	declarations and state variable syntax where appropriate.

compiler/check_typeclass.m:
compiler/dnf.m:
compiler/optimize.m:
	Reorder arguments of predicates exported to mercury_compile.m to
	allow the use of state variable syntax.

compiler/globals.m:
	Wrap an 80+ column line.

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/check_typeclass.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/check_typeclass.m,v
retrieving revision 1.52
diff -u -r1.52 check_typeclass.m
--- compiler/check_typeclass.m	21 Dec 2003 05:04:32 -0000	1.52
+++ compiler/check_typeclass.m	28 Jan 2004 03:06:33 -0000
@@ -53,10 +53,8 @@
 
 :- import_module bool, io.
 
-:- pred check_typeclass__check_instance_decls(module_info, qual_info,
-	module_info, qual_info, bool, io__state, io__state).
-:- mode check_typeclass__check_instance_decls(in, in, out, out,
-	out, di, uo) is det.
+:- pred check_typeclass__check_instance_decls(qual_info::in, qual_info::out,
+	module_info::in, module_info::out, bool::out, io::di, io::uo) is det.
 
 :- implementation.
 
@@ -84,23 +82,21 @@
 :- type error_message == pair(prog_context, list(format_component)).
 :- type error_messages == list(error_message).
 
-check_typeclass__check_instance_decls(ModuleInfo0, QualInfo0,
-		ModuleInfo, QualInfo, FoundError, !IO) :-
-	module_info_classes(ModuleInfo0, ClassTable),
-	module_info_instances(ModuleInfo0, InstanceTable0),
+check_typeclass__check_instance_decls(!QualInfo, !ModuleInfo, FoundError,
+		!IO) :-
+	module_info_classes(!.ModuleInfo, ClassTable),
+	module_info_instances(!.ModuleInfo, InstanceTable0),
 	map__to_assoc_list(InstanceTable0, InstanceList0),
 	list_map_foldl2(check_one_class(ClassTable), InstanceList0,
-		InstanceList, check_tc_info([], ModuleInfo0, QualInfo0),
-		check_tc_info(Errors, ModuleInfo1, QualInfo), !IO),
+		InstanceList, check_tc_info([], !.ModuleInfo, !.QualInfo),
+		check_tc_info(Errors, !:ModuleInfo, !:QualInfo), !IO),
 	(
 		Errors = []
 	->
 		map__from_assoc_list(InstanceList, InstanceTable),
-		module_info_set_instances(InstanceTable,
-			ModuleInfo1, ModuleInfo),
+		module_info_set_instances(InstanceTable, !ModuleInfo),
 		FoundError = no
 	;
-		ModuleInfo = ModuleInfo1,
 		list__reverse(Errors, ErrorList),
 		WriteError = (pred(E::in, IO0::di, IO::uo) is det :-
 			E = ErrorContext - ErrorPieces,
Index: compiler/dnf.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/dnf.m,v
retrieving revision 1.52
diff -u -r1.52 dnf.m
--- compiler/dnf.m	1 Dec 2003 15:55:32 -0000	1.52
+++ compiler/dnf.m	28 Jan 2004 04:37:24 -0000
@@ -50,8 +50,8 @@
 
 :- import_module set, list, bool, std_util.
 
-:- pred dnf__transform_module(module_info::in, bool::in,
-	maybe(set(pred_proc_id))::in, module_info::out) is det.
+:- pred dnf__transform_module(bool::in, maybe(set(pred_proc_id))::in,
+	module_info::in, module_info::out) is det.
 
 :- pred dnf__transform_proc(proc_info::in, pred_info::in,
 	maybe(set(pred_proc_id))::in, module_info::in, module_info::out,
@@ -75,12 +75,12 @@
 
 	% Traverse the module structure.
 
-dnf__transform_module(ModuleInfo0, TransformAll, MaybeNonAtomic, ModuleInfo) :-
-	module_info_predids(ModuleInfo0, PredIds),
+dnf__transform_module(TransformAll, MaybeNonAtomic, !ModuleInfo) :-
+	module_info_predids(!.ModuleInfo, PredIds),
 	dnf__transform_preds(PredIds, TransformAll, MaybeNonAtomic,
-		ModuleInfo0, ModuleInfo1),
+		!ModuleInfo),
 	% The dependency_graph information is now incorrect.
-	module_info_clobber_dependency_info(ModuleInfo1, ModuleInfo).
+	module_info_clobber_dependency_info(!ModuleInfo).
 
 :- pred dnf__transform_preds(list(pred_id)::in, bool::in,
 	maybe(set(pred_proc_id))::in, module_info::in, module_info::out) is det.
Index: compiler/error_util.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/error_util.m,v
retrieving revision 1.24
diff -u -r1.24 error_util.m
--- compiler/error_util.m	24 Oct 2003 06:17:37 -0000	1.24
+++ compiler/error_util.m	27 Jan 2004 22:40:12 -0000
@@ -6,7 +6,7 @@
 %
 % error_util.m
 % Main author: zs.
-% 
+%
 % This module contains code that can be helpful in the formatting of
 % error messages.
 %
@@ -51,40 +51,44 @@
 				% white space may be rearranged and line
 				% breaks may be inserted.
 
-	;	nl		% Insert a line break if there has been text
+	;	nl.		% Insert a line break if there has been text
 				% output since the last line break.
-	.
-		
+
 	% Convert a list of strings into a list of format_components,
 	% suitable for displaying as an error message.
 :- pred error_util__list_to_pieces(list(string)::in,
-		list(format_component)::out) is det.
+	list(format_component)::out) is det.
 
 	% Convert a list of lists of format_components into a list of
 	% format_components separated by commas, with the last two
 	% elements separated by `and'.
 :- func error_util__component_lists_to_pieces(list(list(format_component))) =
-		list(format_component).
+	list(format_component).
+
+	% Display the given error message, without a context and with standard
+	% indentation.
+:- pred write_error_pieces_plain(list(format_component)::in,
+	io::di, io::uo) is det.
 
 	% Display the given error message.
 :- pred write_error_pieces(prog_context::in, int::in,
-	list(format_component)::in, io__state::di, io__state::uo) is det.
+	list(format_component)::in, io::di, io::uo) is det.
 
 	% Display the given error message, but indent the first line.
 	% This is useful when adding extra lines to an already
 	% displayed message.
 :- pred write_error_pieces_not_first_line(prog_context::in, int::in,
-	list(format_component)::in, io__state::di, io__state::uo) is det.
+	list(format_component)::in, io::di, io::uo) is det.
 
 :- pred write_error_pieces_maybe_with_context(maybe(prog_context)::in, int::in,
-	list(format_component)::in, io__state::di, io__state::uo) is det.
+	list(format_component)::in, io::di, io::uo) is det.
 
 	% Report a warning, and set the exit status to error if the
 	% --halt-at-warn option is set. This predicate does the same thing as
 	% prog_io_util__report_warning, except that it does a nicer job of
 	% displaying the warning message.
 :- pred report_warning(prog_context::in, int::in, list(format_component)::in,
-	io__state::di, io__state::uo) is det.
+	io::di, io::uo) is det.
 
 	% Predicates to convert a predicate names to strings.
 
@@ -116,7 +120,7 @@
 	% Append a punctuation character to a message, avoiding unwanted
 	% line splitting between the message and the punctuation.
 :- func error_util__append_punctuation(list(format_component), char) =
-		list(format_component).
+	list(format_component).
 
 	% report_error_num_args(MaybePredOrFunc, Arity, CorrectArities).
 	%
@@ -124,9 +128,8 @@
 	% "wrong number of arguments (<Arity>; should be <CorrectArities>)",
 	% adjusting `Arity' and `CorrectArities' if `MaybePredOrFunc' is
 	% `yes(function)'.
-:- pred report_error_num_args(maybe(pred_or_func), int, list(int),
-		io__state, io__state).
-:- mode report_error_num_args(in, in, in, di, uo) is det.
+:- pred report_error_num_args(maybe(pred_or_func)::in, int::in, list(int)::in,
+	io::di, io::uo) is det.
 
 	% sorry(ModuleName, Message)
 	% Call error/1 with a "Sorry, not implemented" message.
@@ -172,34 +175,37 @@
 		error_util__component_lists_to_pieces(
 			[Components2, Components3 | Components])).
 
-report_warning(Context, Indent, Components) -->
-	globals__io_lookup_bool_option(halt_at_warn, HaltAtWarn),
-	( { HaltAtWarn = yes } ->
-		io__set_exit_status(1)
+report_warning(Context, Indent, Components, !IO) :-
+	globals__io_lookup_bool_option(halt_at_warn, HaltAtWarn, !IO),
+	( HaltAtWarn = yes ->
+		io__set_exit_status(1, !IO)
 	;
-		[]
+		true
 	),
-	write_error_pieces(Context, Indent, Components).
+	write_error_pieces(Context, Indent, Components, !IO).
 
-write_error_pieces(Context, Indent, Components) -->
+write_error_pieces_plain(Components, !IO) :-
+	write_error_pieces_maybe_with_context(yes, no, 0, Components, !IO).
+
+write_error_pieces(Context, Indent, Components, !IO) :-
 	write_error_pieces_maybe_with_context(yes, yes(Context),
-		Indent, Components).
+		Indent, Components, !IO).
 
-write_error_pieces_not_first_line(Context, Indent, Components) -->
+write_error_pieces_not_first_line(Context, Indent, Components, !IO) :-
 	write_error_pieces_maybe_with_context(no, yes(Context),
-		Indent, Components).
+		Indent, Components, !IO).
 
-write_error_pieces_maybe_with_context(MaybeContext, Indent, Components) -->
+write_error_pieces_maybe_with_context(MaybeContext, Indent, Components, !IO) :-
 	write_error_pieces_maybe_with_context(yes, MaybeContext,
-		Indent, Components).
+		Indent, Components, !IO).
 
 :- pred write_error_pieces_maybe_with_context(bool::in,
 	maybe(prog_context)::in, int::in, list(format_component)::in,
-	io__state::di, io__state::uo) is det.
+	io::di, io::uo) is det.
 
 write_error_pieces_maybe_with_context(IsFirst, MaybeContext,
-		Indent, Components) -->
-	{
+		Indent, Components, !IO) :-
+	(
 			% The fixed characters at the start of the line are:
 			% filename
 			% :
@@ -229,67 +235,67 @@
 		Remain = 79 - (ContextLength + Indent + NotFirstIndent),
 		convert_components_to_word_list(Components, [], [], Words),
 		group_words(IsFirst, Words, Remain, Lines)
-	},
-	( { IsFirst = yes } ->
-		write_lines(Lines, MaybeContext, Indent)
+	),
+	( IsFirst = yes ->
+		write_lines(Lines, MaybeContext, Indent, !IO)
 	;
-		write_nonfirst_lines(Lines, MaybeContext, Indent + 2)
+		write_nonfirst_lines(Lines, MaybeContext, Indent + 2, !IO)
 	).
 
 :- pred write_lines(list(list(string))::in, maybe(prog_context)::in, int::in,
-	io__state::di, io__state::uo) is det.
+	io::di, io::uo) is det.
 
-write_lines([], _, _) --> [].
-write_lines([Line | Lines], MaybeContext, Indent) -->
+write_lines([], _, _, !IO).
+write_lines([Line | Lines], MaybeContext, Indent, !IO) :-
 	(
-		{ MaybeContext = yes(Context) },
-		prog_out__write_context(Context)
+		MaybeContext = yes(Context),
+		prog_out__write_context(Context, !IO)
 	;
-		{ MaybeContext = no }
+		MaybeContext = no
 	),
-	{ string__pad_left("", ' ', Indent, IndentStr) },
-	io__write_string(IndentStr),
-	write_line(Line),
-	{ Indent2 = Indent + 2 },
-	write_nonfirst_lines(Lines, MaybeContext, Indent2).
+	string__pad_left("", ' ', Indent, IndentStr),
+	io__write_string(IndentStr, !IO),
+	write_line(Line, !IO),
+	Indent2 = Indent + 2,
+	write_nonfirst_lines(Lines, MaybeContext, Indent2, !IO).
 
 :- pred write_nonfirst_lines(list(list(string))::in, maybe(prog_context)::in,
-	int::in, io__state::di, io__state::uo) is det.
+	int::in, io::di, io::uo) is det.
 
-write_nonfirst_lines([], _, _) --> [].
-write_nonfirst_lines([Line | Lines], MaybeContext, Indent) -->
+write_nonfirst_lines([], _, _, !IO).
+write_nonfirst_lines([Line | Lines], MaybeContext, Indent, !IO) :-
 	(
-		{ MaybeContext = yes(Context) },
-		prog_out__write_context(Context)
+		MaybeContext = yes(Context),
+		prog_out__write_context(Context, !IO)
 	;
-		{ MaybeContext = no }
+		MaybeContext = no
 	),
-	{ string__pad_left("", ' ', Indent, IndentStr) },
-	io__write_string(IndentStr),
-	write_line(Line),
-	write_nonfirst_lines(Lines, MaybeContext, Indent).
-
-:- pred write_line(list(string)::in, io__state::di, io__state::uo) is det.
-
-write_line([]) --> [].
-write_line([Word | Words]) -->
-	io__write_string(Word),
-	write_line_rest(Words),
-	io__write_char('\n').
-
-:- pred write_line_rest(list(string)::in, io__state::di, io__state::uo) is det.
-
-write_line_rest([]) --> [].
-write_line_rest([Word | Words]) -->
-	io__write_char(' '),
-	io__write_string(Word),
-	write_line_rest(Words).
+	string__pad_left("", ' ', Indent, IndentStr),
+	io__write_string(IndentStr, !IO),
+	write_line(Line, !IO),
+	write_nonfirst_lines(Lines, MaybeContext, Indent, !IO).
+
+:- pred write_line(list(string)::in, io::di, io::uo) is det.
+
+write_line([], !IO).
+write_line([Word | Words], !IO) :-
+	io__write_string(Word, !IO),
+	write_line_rest(Words, !IO),
+	io__write_char('\n', !IO).
+
+:- pred write_line_rest(list(string)::in, io::di, io::uo) is det.
+
+write_line_rest([], !IO).
+write_line_rest([Word | Words], !IO) :-
+	io__write_char(' ', !IO),
+	io__write_string(Word, !IO),
+	write_line_rest(Words, !IO).
 
 %----------------------------------------------------------------------------%
 
 :- pred convert_components_to_word_list(list(format_component)::in,
-		list(string)::in, list(list(string))::in,
-		list(list(string))::out) is det.
+	list(string)::in, list(list(string))::in, list(list(string))::out)
+	is det.
 
 convert_components_to_word_list([], Words0, Paras0, Paras) :-
 	list__reverse(Words0, Words),
@@ -312,14 +318,14 @@
 	),
 	convert_components_to_word_list(Components, Words1, Paras1, Paras).
 
-:- pred break_into_words(string::in, list(string)::in,
-		list(string)::out) is det.
+:- pred break_into_words(string::in, list(string)::in, list(string)::out)
+	is det.
 
 break_into_words(String, Words0, Words) :-
 	break_into_words_from(String, 0, Words0, Words).
 
-:- pred break_into_words_from(string::in, int::in,
-		list(string)::in, list(string)::out) is det.
+:- pred break_into_words_from(string::in, int::in, list(string)::in,
+	list(string)::out) is det.
 
 break_into_words_from(String, Cur, Words0, Words) :-
 	( find_word_start(String, Cur, Start) ->
@@ -365,7 +371,7 @@
 	% at least one line.
 
 :- pred group_words(bool::in, list(list(string))::in, int::in,
-		list(list(string))::out) is det.
+	list(list(string))::out) is det.
 
 group_words(IsFirst, Paras, Max, Lines) :-
 	(
@@ -429,7 +435,7 @@
 		Line = Line0,
 		RestWords = [Word | Words]
 	).
-		
+
 %-----------------------------------------------------------------------------%
 
 	% The code of this predicate duplicates the functionality of
@@ -461,7 +467,7 @@
 			"'"], Piece)
 	).
 
-error_util__describe_several_pred_names(Module, PredId, Pieces) :- 
+error_util__describe_several_pred_names(Module, PredId, Pieces) :-
 	list__map(error_util__describe_one_pred_name(Module), PredId, Pieces0),
 	error_util__list_to_pieces(Pieces0, Pieces).
 
@@ -509,8 +515,8 @@
 error_util__pred_or_func_to_string(function) = "function".
 
 error_util__append_punctuation([], _) = _ :-
-	error(
-	"error_util__append_punctuation: appending punctuation after nothing").
+	error("error_util__append_punctuation: " ++
+		"appending punctuation after nothing").
 error_util__append_punctuation([Piece0], Punc) = [Piece] :-
 	% Avoid unwanted line splitting between the message
 	% and the punctuation.
@@ -522,17 +528,17 @@
 		Piece = fixed(string__append(String, char_to_string(Punc)))
 	;
 		Piece0 = nl,
-		error(
-	"error_util__append_punctutation: appending punctuation after newline")
+		error("error_util__append_punctutation: " ++
+			"appending punctuation after newline")
 	).
 error_util__append_punctuation([Piece1, Piece2 | Pieces], Punc) =
 	[Piece1 | error_util__append_punctuation([Piece2 | Pieces], Punc)].
 
 %-----------------------------------------------------------------------------%
 
-report_error_num_args(MaybePredOrFunc, Arity0, Arities0) -->
+report_error_num_args(MaybePredOrFunc, Arity0, Arities0, !IO) :-
 	% Adjust arities for functions.
-	{ MaybePredOrFunc = yes(function) ->
+	( MaybePredOrFunc = yes(function) ->
 		adjust_func_arity(function, Arity, Arity0),
 		list__map(
 			(pred(OtherArity0::in, OtherArity::out) is det :-
@@ -543,30 +549,26 @@
 	;
 		Arity = Arity0,
 		Arities = Arities0
-	},
-
-	io__write_string("wrong number of arguments ("),
-	io__write_int(Arity),
-	io__write_string("; should be "),
-	report_error_right_num_args(Arities),
-	io__write_string(")").
-
-:- pred report_error_right_num_args(list(int), io__state, io__state).
-:- mode report_error_right_num_args(in, di, uo) is det.
-
-report_error_right_num_args([]) --> [].
-report_error_right_num_args([Arity | Arities]) -->
-	io__write_int(Arity),
-	( { Arities = [] } ->
-		[]
-	; { Arities = [_] } ->
-		io__write_string(" or ")
+	),
+	io__write_string("wrong number of arguments (", !IO),
+	io__write_int(Arity, !IO),
+	io__write_string("; should be ", !IO),
+	report_error_right_num_args(Arities, !IO),
+	io__write_string(")", !IO).
+
+:- pred report_error_right_num_args(list(int)::in, io::di, io::uo) is det.
+
+report_error_right_num_args([], !IO).
+report_error_right_num_args([Arity | Arities], !IO) :-
+	io__write_int(Arity, !IO),
+	( Arities = [] ->
+		true
+	; Arities = [_] ->
+		io__write_string(" or ", !IO)
 	;
-		io__write_string(", ")
+		io__write_string(", ", !IO)
 	),
-	report_error_right_num_args(Arities).
-
-
+	report_error_right_num_args(Arities, !IO).
 
 	% Call error/1 with a "Sorry, not implemented" message.
 	%
@@ -576,8 +578,6 @@
 	error(ErrorMessage).
 
 unexpected(Module, What) :-
-	string__format("%s: Unexpected: %s", 
+	string__format("%s: Unexpected: %s",
 		[s(Module), s(What)], ErrorMessage),
 	error(ErrorMessage).
-
-
Index: compiler/globals.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/globals.m,v
retrieving revision 1.57
diff -u -r1.57 globals.m
--- compiler/globals.m	15 Jan 2004 07:36:17 -0000	1.57
+++ compiler/globals.m	27 Jan 2004 22:14:27 -0000
@@ -314,7 +314,8 @@
 		( convert_foreign_language(String, ForeignLang0) ->
 			ForeignLang = ForeignLang0
 		;
-			error("globals__io_get_backend_foreign_languages: invalid foreign_language string")
+			error("globals__io_get_backend_foreign_languages: " ++
+				"invalid foreign_language string")
 		), LangStrs).
 
 globals__set_options(Globals, Options, Globals ^ options := Options).
Index: compiler/mercury_compile.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/mercury_compile.m,v
retrieving revision 1.299
diff -u -r1.299 mercury_compile.m
--- compiler/mercury_compile.m	1 Jan 2004 05:57:09 -0000	1.299
+++ compiler/mercury_compile.m	28 Jan 2004 07:11:35 -0000
@@ -22,12 +22,10 @@
 
 	% This is the main entry point for the Mercury compiler.
 	% It is called from top_level.main.
-:- pred real_main(io__state, io__state).
-:- mode real_main(di, uo) is det.
+:- pred real_main(io::di, io::uo) is det.
 
 	% main(Args).
-:- pred main(list(string), io__state, io__state).
-:- mode main(in, di, uo) is det.
+:- pred main(list(string)::in, io::di, io::uo) is det.
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
@@ -127,7 +125,7 @@
 :- import_module ml_backend__mlds_to_java.	% MLDS -> Java
 :- import_module ml_backend__mlds_to_ilasm.	% MLDS -> IL assembler
 :- import_module ml_backend__maybe_mlds_to_gcc.	% MLDS -> GCC back-end
-:- import_module ml_backend__ml_util.		% MLDS utility predicates 
+:- import_module ml_backend__ml_util.		% MLDS utility predicates
 
 	% miscellaneous compiler modules
 :- import_module aditi_backend__rl.
@@ -136,6 +134,7 @@
 :- import_module backend_libs__compile_target_code.
 :- import_module backend_libs__name_mangle.
 :- import_module check_hlds__goal_path.
+:- import_module hlds__error_util.
 :- import_module hlds__hlds_data.
 :- import_module hlds__hlds_module.
 :- import_module hlds__hlds_out.
@@ -170,129 +169,140 @@
 
 %-----------------------------------------------------------------------------%
 
-real_main -->
-    gc_init,
+real_main(!IO) :-
+	gc_init(!IO),
 
-         % All messages go to stderr
-    io__stderr_stream(StdErr),
-    io__set_output_stream(StdErr, _),
-    io__command_line_arguments(Args0),
+		% All messages go to stderr
+	io__stderr_stream(StdErr, !IO),
+	io__set_output_stream(StdErr, _, !IO),
+	io__command_line_arguments(Args0, !IO),
 
-    ( { Args0 = ["--arg-file", ArgFile] } ->
-	%
-	% All the configuration and options file options
-	% are passed in the given file, which is created
-	% by the parent `mmc --make' process.
-	%
+	( Args0 = ["--arg-file", ArgFile] ->
+		%
+		% All the configuration and options file options
+		% are passed in the given file, which is created
+		% by the parent `mmc --make' process.
+		%
+
+		% read_args_file may attempt to look up options,
+		% so we need to initialize the globals..
+		handle_options([], _, _, _, _, !IO),
+
+		options_file__read_args_file(ArgFile, MaybeArgs1, !IO),
+		(
+			MaybeArgs1 = yes(Args1),
+			process_options(Args1, OptionArgs, NonOptionArgs, _),
+			MaybeMCFlags = yes([])
+		;
+			MaybeArgs1 = no,
+			OptionArgs = [],
+			NonOptionArgs = [],
+			MaybeMCFlags = yes([])
+		),
+		Variables = options_variables_init,
+		Link = no
+	;
+		%
+		% Find out which options files to read.
+		%
+		handle_options(Args0, MaybeError0, OptionArgs, NonOptionArgs,
+			Link, !IO),
+		(
+			MaybeError0 = yes(Error0),
+			usage_error(Error0, !IO),
+			Variables = options_variables_init,
+			MaybeMCFlags = no
+		;
+			MaybeError0 = no,
+			read_options_files(options_variables_init,
+				MaybeVariables0, !IO),
+			(
+				MaybeVariables0 = yes(Variables0),
+				lookup_mmc_options(Variables0, MaybeMCFlags0,
+					!IO),
+				(
+					MaybeMCFlags0 = yes(MCFlags0),
+					real_main_2(MCFlags0, MaybeMCFlags,
+						Args0, Variables0, Variables,
+						!IO)
+
+				;
+					MaybeMCFlags0 = no,
+					Variables = options_variables_init,
+					MaybeMCFlags = no
+				)
+			;
+				MaybeVariables0 = no,
+				Variables = options_variables_init,
+				MaybeMCFlags = no
+			)
+		)
+	),
+	(
+		MaybeMCFlags = yes(MCFlags),
+		handle_options(MCFlags ++ OptionArgs, MaybeError, _, _, _,
+			!IO),
 
-	% read_args_file may attempt to look up options,
-	% so we need to initialize the globals..
-	handle_options([], _, _, _, _),
-
-	options_file__read_args_file(ArgFile, MaybeArgs1),
-	{
-		MaybeArgs1 = yes(Args1),
-        	process_options(Args1, OptionArgs, NonOptionArgs, _),
-        	MaybeMCFlags = yes([])
-	;
-		MaybeArgs1 = no,
-		OptionArgs = [],
-		NonOptionArgs = [],
-        	MaybeMCFlags = yes([])
-	},
-        { Variables = options_variables_init },
-	{ Link = no }
-    ;
+		%
+		% When computing the option arguments to pass
+		% to `--make', only include the command-line
+		% arguments, not the contents of DEFAULT_MCFLAGS.
+		%
+		main_2(MaybeError, Variables, OptionArgs, NonOptionArgs, Link,
+			!IO)
+	;
+		MaybeMCFlags = no,
+		io__set_exit_status(1, !IO)
+	).
+
+:- pred real_main_2(list(string)::in, maybe(list(string))::out,
+	list(string)::in, options_variables::in, options_variables::out,
+	io::di, io::uo) is det.
+
+real_main_2(MCFlags0, MaybeMCFlags, Args0, Variables0, Variables, !IO) :-
 	%
-	% Find out which options files to read.
+	% Process the options again to find out
+	% which configuration file to read.
 	%
-	handle_options(Args0, MaybeError0, OptionArgs, NonOptionArgs, Link),
+	handle_options(MCFlags0 ++ Args0, MaybeError1, _, _, _, !IO),
 	(
-	    { MaybeError0 = yes(Error0) },
-            usage_error(Error0),
-            { Variables = options_variables_init },
-            { MaybeMCFlags = no }
-	;
-            { MaybeError0 = no },
-            read_options_files(options_variables_init, MaybeVariables0),
-            (
-	        { MaybeVariables0 = yes(Variables0) },
-                lookup_mmc_options(Variables0, MaybeMCFlags0),
-                (
-		    { MaybeMCFlags0 = yes(MCFlags0) },
-
-		    %
-		    % Process the options again to find out which
-		    % configuration file to read.
-		    %
-                    handle_options(MCFlags0 ++ Args0, MaybeError1, 
-                        _, _, _),
-                    (
-                        { MaybeError1 = yes(Error1) },
-                        usage_error(Error1),
-                        { Variables = options_variables_init },
-                        { MaybeMCFlags = no }
-                    ;
-                        { MaybeError1 = no },
-
-                        globals__io_lookup_maybe_string_option(config_file,
-                            MaybeConfigFile),
-                        (
-                            { MaybeConfigFile = yes(ConfigFile) },
-                            read_options_file(ConfigFile, Variables0,
-    				MaybeVariables),
-                            (
-                                { MaybeVariables = yes(Variables) },
-                                lookup_mmc_options(Variables, MaybeMCFlags)
-                            ;
-                                { MaybeVariables = no },
-                                { MaybeMCFlags = no },
-                                { Variables = options_variables_init }
-                            )
-                        ;
-                            { MaybeConfigFile = no },
-                            { Variables = options_variables_init },
-                            lookup_mmc_options(Variables, MaybeMCFlags)
-                        )
-		    )
-		;
-		    { MaybeMCFlags0 = no },
-                    { Variables = options_variables_init },
-                    { MaybeMCFlags = no }
-                )
-	    ;
-	    	{ MaybeVariables0 = no },
-                { Variables = options_variables_init },
-                { MaybeMCFlags = no }
-	    )
-        )
-    ),
-    (
-        { MaybeMCFlags = yes(MCFlags) },
-
-        handle_options(MCFlags ++ OptionArgs, MaybeError,
-                _, _, _),
-
-        %
-        % When computing the option arguments to pass
-        % to `--make', only include the command-line
-        % arguments, not the contents of DEFAULT_MCFLAGS.
-        %
-        main_2(MaybeError, Variables, OptionArgs, NonOptionArgs, Link)
-    ;
-        { MaybeMCFlags = no },
-        io__set_exit_status(1)
-    ).
+		MaybeError1 = yes(Error1),
+		usage_error(Error1, !IO),
+		Variables = options_variables_init,
+		MaybeMCFlags = no
+	;
+		MaybeError1 = no,
+		globals__io_lookup_maybe_string_option(config_file,
+			MaybeConfigFile, !IO),
+		(
+			MaybeConfigFile = yes(ConfigFile),
+			read_options_file(ConfigFile, Variables0,
+				MaybeVariables, !IO),
+			(
+				MaybeVariables = yes(Variables),
+				lookup_mmc_options(Variables, MaybeMCFlags,
+					!IO)
+			;
+				MaybeVariables = no,
+				MaybeMCFlags = no,
+				Variables = options_variables_init
+			)
+		;
+			MaybeConfigFile = no,
+			Variables = options_variables_init,
+			lookup_mmc_options(Variables, MaybeMCFlags, !IO)
+		)
+	).
 
-main(Args) -->
-	main_2(no, options_variables_init, [], Args, no).
+main(Args, !IO) :-
+	main_2(no, options_variables_init, [], Args, no, !IO).
 
 %-----------------------------------------------------------------------------%
 
 :- pred gc_init(io__state::di, io__state::uo) is det.
 
 % This version is only used if there is no matching foreign_proc version.
-gc_init --> [].
+gc_init(!IO).
 
 :- pragma foreign_proc("C",
 	gc_init(_IO0::di, _IO::uo),
@@ -316,97 +326,102 @@
 
 %-----------------------------------------------------------------------------%
 
-:- pred main_2(maybe(string), options_variables, list(string), list(string),
-		bool, io__state, io__state).
-:- mode main_2(in, in, in, in, in, di, uo) is det.
-
-main_2(yes(ErrorMessage), _, _, _, _) -->
-	usage_error(ErrorMessage).
-main_2(no, OptionVariables, OptionArgs, Args, Link) -->
-	globals__io_lookup_bool_option(help, Help),
-	globals__io_lookup_bool_option(generate_source_file_mapping,
+:- pred main_2(maybe(string)::in, options_variables::in, list(string)::in,
+	list(string)::in, bool::in, io::di, io::uo) is det.
+
+main_2(yes(ErrorMessage), _, _, _, _, !IO) :-
+	usage_error(ErrorMessage, !IO).
+main_2(no, OptionVariables, OptionArgs, Args, Link, !IO) :-
+	globals__io_get_globals(Globals, !IO),
+	globals__lookup_bool_option(Globals, help, Help),
+	globals__lookup_bool_option(Globals, generate_source_file_mapping,
 		GenerateMapping),
-	globals__io_lookup_bool_option(output_grade_string, OutputGrade),
-	globals__io_lookup_bool_option(output_link_command, OutputLinkCommand),
-	globals__io_lookup_bool_option(output_shared_lib_link_command,
+	globals__lookup_bool_option(Globals, output_grade_string,
+		OutputGrade),
+	globals__lookup_bool_option(Globals, output_link_command,
+		OutputLinkCommand),
+	globals__lookup_bool_option(Globals, output_shared_lib_link_command,
 		OutputShLibLinkCommand),
-	globals__io_lookup_bool_option(filenames_from_stdin,
+	globals__lookup_bool_option(Globals, filenames_from_stdin,
 		FileNamesFromStdin),
-	globals__io_lookup_bool_option(make, Make),
-	( { Help = yes } ->
-		io__stdout_stream(Stdout),
-		io__set_output_stream(Stdout, OldOutputStream),
-		long_usage,
-		io__set_output_stream(OldOutputStream, _)
-	; { OutputGrade = yes } ->
-		globals__io_get_globals(Globals),
+	globals__lookup_bool_option(Globals, make, Make),
+	( Help = yes ->
+		io__stdout_stream(Stdout, !IO),
+		io__set_output_stream(Stdout, OldOutputStream, !IO),
+		long_usage(!IO),
+		io__set_output_stream(OldOutputStream, _, !IO)
+	; OutputGrade = yes ->
 		% When Mmake asks for the grade, it really wants
 		% the directory component to use. This is consistent
 		% with scripts/canonical_grade.
-		{ grade_directory_component(Globals, Grade) },
-		io__stdout_stream(Stdout),
-		io__write_string(Stdout, Grade),
-		io__write_string(Stdout, "\n")
-	; { OutputLinkCommand = yes } ->
-		globals__io_lookup_string_option(link_executable_command,
+		grade_directory_component(Globals, Grade),
+		io__stdout_stream(Stdout, !IO),
+		io__write_string(Stdout, Grade, !IO),
+		io__write_string(Stdout, "\n", !IO)
+	; OutputLinkCommand = yes ->
+		globals__lookup_string_option(Globals, link_executable_command,
 			LinkCommand),
-		io__stdout_stream(Stdout),
-		io__write_string(Stdout, LinkCommand),
-		io__write_string(Stdout, "\n")
-	; { OutputShLibLinkCommand = yes } ->
-		globals__io_lookup_string_option(link_shared_lib_command,
+		io__stdout_stream(Stdout, !IO),
+		io__write_string(Stdout, LinkCommand, !IO),
+		io__write_string(Stdout, "\n", !IO)
+	; OutputShLibLinkCommand = yes ->
+		globals__lookup_string_option(Globals, link_shared_lib_command,
 			LinkCommand),
-		io__stdout_stream(Stdout),
-		io__write_string(Stdout, LinkCommand),
-		io__write_string(Stdout, "\n")
-	; { GenerateMapping = yes } ->
-		source_file_map__write_source_file_map(Args)
-	; { Make = yes } ->
-		make__process_args(OptionVariables, OptionArgs, Args)
-	; { Args = [], FileNamesFromStdin = no } ->
-		usage
+		io__stdout_stream(Stdout, !IO),
+		io__write_string(Stdout, LinkCommand, !IO),
+		io__write_string(Stdout, "\n", !IO)
+	; GenerateMapping = yes ->
+		source_file_map__write_source_file_map(Args, !IO)
+	; Make = yes ->
+		make__process_args(OptionVariables, OptionArgs, Args, !IO)
+	; Args = [], FileNamesFromStdin = no ->
+		usage(!IO)
 	;
 		process_all_args(OptionVariables, OptionArgs,
-			Args, ModulesToLink),
-		io__get_exit_status(ExitStatus),
-		( { ExitStatus = 0 } ->
-			( { Link = yes, ModulesToLink = [FirstModule | _] } ->
-				{ file_name_to_module_name(FirstModule,
-					MainModuleName) },
+			Args, ModulesToLink, !IO),
+		io__get_exit_status(ExitStatus, !IO),
+		( ExitStatus = 0 ->
+			(
+				Link = yes,
+				ModulesToLink = [FirstModule | _]
+			->
+				file_name_to_module_name(FirstModule,
+					MainModuleName),
 				compile_with_module_options(MainModuleName,
 					OptionVariables, OptionArgs,
 					compile_target_code__link_module_list(
-						ModulesToLink), Succeeded),
-				maybe_set_exit_status(Succeeded)
+						ModulesToLink),
+					Succeeded, !IO),
+				maybe_set_exit_status(Succeeded, !IO)
 			;
-				[]
+				true
 			)
 		;
 			% If we found some errors, but the user didn't enable
 			% the `-E' (`--verbose-errors') option, give them a
 			% hint about it.
 
-			globals__io_lookup_bool_option(verbose_errors,
+			globals__lookup_bool_option(Globals, verbose_errors,
 				VerboseErrors),
-			( { VerboseErrors = no } ->
-				io__write_string("For more information, try recompiling with `-E'.\n")
+			( VerboseErrors = no ->
+				io__write_string("For more information, " ++
+					"try recompiling with `-E'.\n", !IO)
 			;
-				[]
+				true
 			)
 		),
-		globals__io_lookup_bool_option(statistics, Statistics),
-		( { Statistics = yes } ->
-			io__report_stats("full_memory_stats")
+		globals__lookup_bool_option(Globals, statistics, Statistics),
+		( Statistics = yes ->
+			io__report_stats("full_memory_stats", !IO)
 		;
-			[]
+			true
 		)
 	).
 
-:- pred process_all_args(options_variables, list(string),
-		list(string), list(string), io__state, io__state).
-:- mode process_all_args(in, in, in, out, di, uo) is det.
+:- pred process_all_args(options_variables::in, list(string)::in,
+	list(string)::in, list(string)::out, io::di, io::uo) is det.
 
-process_all_args(OptionVariables, OptionArgs, Args, ModulesToLink) -->
+process_all_args(OptionVariables, OptionArgs, Args, ModulesToLink, !IO) :-
 	% Because of limitations in the GCC back-end,
 	% we can only call the GCC back-end once (per process),
 	% to generate a single assembler file, rather than
@@ -414,48 +429,57 @@
 	% assembler files for each module.
 	% So if we're generating code using the GCC back-end,
 	% we need to call run_gcc_backend here at the top level.
-	globals__io_get_globals(Globals),
-	( { compiling_to_asm(Globals) } ->
-	    ( { Args = [FirstArg | OtherArgs] }  ->
-		globals__io_lookup_bool_option(smart_recompilation, Smart),
-		( { Smart = yes } ->
-		    ( { OtherArgs = [] } ->
-			% With smart recompilation we need to delay
-			% starting the gcc backend to avoid overwriting
-			% the output assembler file even if recompilation 
-			% is found to be unnecessary.
-		    	mercury_compile__process_args(OptionVariables,
-					OptionArgs, Args, ModulesToLink)
-		    ;
-			io__write_string(
-"Sorry, not implemented: `--target asm' with `--smart-recompilation'\n"),
-			io__write_string(
-"with more than one module to compile.\n"),
-			io__set_exit_status(1),
-			{ ModulesToLink = [] }
-		    )
-		;
-		    compile_using_gcc_backend(OptionVariables, OptionArgs,
-		    	string_to_file_or_module(FirstArg),
-			mercury_compile__process_args(OptionVariables,
-				OptionArgs, Args),
-			ModulesToLink)
-	        )
-	    ;
-		io__write_string(
-"Sorry, not implemented: `--target asm' with `--filenames-from-stdin\n"),
-		io__set_exit_status(1),
-		{ ModulesToLink = [] }
-	    )
+	globals__io_get_globals(Globals, !IO),
+	( compiling_to_asm(Globals) ->
+		( Args = [FirstArg | OtherArgs] ->
+			globals__lookup_bool_option(Globals,
+				smart_recompilation, Smart),
+			( Smart = yes ->
+				( OtherArgs = [] ->
+				% With smart recompilation we need to delay
+				% starting the gcc backend to avoid overwriting
+				% the output assembler file even if
+				% recompilation is found to be unnecessary.
+					mercury_compile__process_args(
+						OptionVariables,
+						OptionArgs, Args,
+						ModulesToLink, !IO)
+				;
+					Msg = "Sorry, not implemented: " ++
+						"`--target asm' with " ++
+						"`--smart-recompilation' " ++
+						"with more than one module " ++
+						"to compile.",
+					write_error_pieces_plain([words(Msg)],
+						!IO),
+					io__set_exit_status(1, !IO),
+					ModulesToLink = []
+				)
+			;
+				compile_using_gcc_backend(OptionVariables,
+					OptionArgs,
+					string_to_file_or_module(FirstArg),
+				mercury_compile__process_args(OptionVariables,
+					OptionArgs, Args),
+				ModulesToLink, !IO)
+			)
+		;
+			Msg = "Sorry, not implemented: `--target asm' " ++
+				"with `--filenames-from-stdin",
+			write_error_pieces_plain([words(Msg)], !IO),
+			io__set_exit_status(1, !IO),
+			ModulesToLink = []
+		)
 	;
 		% If we're NOT using the GCC back-end,
 		% then we can just call process_args directly,
 		% rather than via GCC.
-	    mercury_compile__process_args(OptionVariables, OptionArgs,
-	    		Args, ModulesToLink)
+		mercury_compile__process_args(OptionVariables, OptionArgs,
+			Args, ModulesToLink, !IO)
 	).
 
 :- pred compiling_to_asm(globals::in) is semidet.
+
 compiling_to_asm(Globals) :-
 	globals__get_target(Globals, asm),
 	% even if --target asm is specified,
@@ -471,14 +495,13 @@
 		OptionList),
 	bool__or_list(BoolList) = no.
 
-:- pred compile_using_gcc_backend(options_variables, list(string),
-		file_or_module, frontend_callback(list(string)),
-		list(string), io__state, io__state).
-:- mode compile_using_gcc_backend(in, in, in, in(frontend_callback),
-		out, di, uo) is det.
+:- pred compile_using_gcc_backend(options_variables::in, list(string)::in,
+	file_or_module::in,
+	frontend_callback(list(string))::in(frontend_callback),
+	list(string)::out, io::di, io::uo) is det.
 
 compile_using_gcc_backend(OptionVariables, OptionArgs, FirstFileOrModule,
-		CallBack, ModulesToLink) -->
+		CallBack, ModulesToLink, !IO) :-
 	% The name of the assembler file that we generate
 	% is based on name of the first module named
 	% on the command line.  (Mmake requires this.)
@@ -505,187 +528,192 @@
 	% contain directory seperators, and issuing
 	% a warning or error in that case?)
 	%
-	{
+	(
 		FirstFileOrModule = file(FirstFileName),
 		file_name_to_module_name(FirstFileName, FirstModuleName)
 	;
 		FirstFileOrModule = module(FirstModuleName)
-	},
+	),
 
 	% Invoke run_gcc_backend.  It will call us back,
 	% and then we'll continue with the normal work of
 	% the compilation, which will be done by the callback
 	% function (`process_args').
-	maybe_mlds_to_gcc__run_gcc_backend(FirstModuleName,
-		CallBack, ModulesToLink),
+	maybe_mlds_to_gcc__run_gcc_backend(FirstModuleName, CallBack,
+		ModulesToLink, !IO),
 
 	% Now we know what the real module name was, so we
 	% can rename the assembler file if needed (see above).
-	( { ModulesToLink = [Module | _] } ->
-		{ file_name_to_module_name(Module, ModuleName) },
-		globals__io_lookup_bool_option(pic, Pic),
-		{ AsmExt = (Pic = yes -> ".pic_s" ; ".s") },
+	( ModulesToLink = [Module | _] ->
+		file_name_to_module_name(Module, ModuleName),
+		globals__io_lookup_bool_option(pic, Pic, !IO),
+		AsmExt = (Pic = yes -> ".pic_s" ; ".s"),
 		module_name_to_file_name(ModuleName, AsmExt, yes,
-			AsmFile),
-		(
-			{ ModuleName \= FirstModuleName }
-		->
+			AsmFile, !IO),
+		( ModuleName \= FirstModuleName ->
 			module_name_to_file_name(FirstModuleName,
-				AsmExt, no, FirstAsmFile),
-			do_rename_file(FirstAsmFile, AsmFile, Result)
+				AsmExt, no, FirstAsmFile, !IO),
+			do_rename_file(FirstAsmFile, AsmFile, Result, !IO)
 		;
-			{ Result = ok }
+			Result = ok
 		),
 
 		% Invoke the assembler to produce an object file,
 		% if needed.
-		globals__io_lookup_bool_option(target_code_only, 
-				TargetCodeOnly),
-		( { Result = ok, TargetCodeOnly = no } ->
-			io__output_stream(OutputStream),
-			get_linked_target_type(TargetType),
-			get_object_code_type(TargetType, PIC),
+		globals__io_lookup_bool_option(target_code_only,
+			TargetCodeOnly, !IO),
+		(
+			Result = ok,
+			TargetCodeOnly = no
+		->
+			io__output_stream(OutputStream, !IO),
+			get_linked_target_type(TargetType, !IO),
+			get_object_code_type(TargetType, PIC, !IO),
 			compile_with_module_options(ModuleName,
 				OptionVariables, OptionArgs,
 				compile_target_code__assemble(OutputStream,
 					PIC, ModuleName),
-				AssembleOK),
-			maybe_set_exit_status(AssembleOK)
+				AssembleOK, !IO),
+			maybe_set_exit_status(AssembleOK, !IO)
 		;
-			[]
+			true
 		)
 	;
 		% This can happen if smart recompilation decided
 		% that nothing needed to be compiled.
-		[]
+		true
 	).
 
 :- pred do_rename_file(string::in, string::in, io__res::out,
-		io__state::di, io__state::uo) is det.
+	io::di, io::uo) is det.
 
-do_rename_file(OldFileName, NewFileName, Result) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(very_verbose, VeryVerbose),
-	maybe_write_string(Verbose, "% Renaming `"),
-	maybe_write_string(Verbose, OldFileName),
-	maybe_write_string(Verbose, "' as `"),
-	maybe_write_string(Verbose, NewFileName),
-	maybe_write_string(Verbose, "'..."),
-	maybe_flush_output(Verbose),
-	io__rename_file(OldFileName, NewFileName, Result0),
-	( { Result0 = error(Error0) } ->
-		maybe_write_string(VeryVerbose, " failed.\n"),
-		maybe_flush_output(VeryVerbose),
-		{ io__error_message(Error0, ErrorMsg0) },
+do_rename_file(OldFileName, NewFileName, Result, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(very_verbose, VeryVerbose, !IO),
+	maybe_write_string(Verbose, "% Renaming `", !IO),
+	maybe_write_string(Verbose, OldFileName, !IO),
+	maybe_write_string(Verbose, "' as `", !IO),
+	maybe_write_string(Verbose, NewFileName, !IO),
+	maybe_write_string(Verbose, "'...", !IO),
+	maybe_flush_output(Verbose, !IO),
+	io__rename_file(OldFileName, NewFileName, Result0, !IO),
+	( Result0 = error(Error0) ->
+		maybe_write_string(VeryVerbose, " failed.\n", !IO),
+		maybe_flush_output(VeryVerbose, !IO),
+		io__error_message(Error0, ErrorMsg0),
 		% On some systems, we need to remove the existing file
 		% first, if any.  So try again that way.
-		maybe_write_string(VeryVerbose, "% Removing `"),
-		maybe_write_string(VeryVerbose, OldFileName),
-		maybe_write_string(VeryVerbose, "'..."),
-		maybe_flush_output(VeryVerbose),
-		io__remove_file(NewFileName, Result1),
-		( { Result1 = error(Error1) } ->
-			maybe_write_string(Verbose, " failed.\n"),
-			maybe_flush_output(Verbose),
-			{ io__error_message(Error1, ErrorMsg1) },
-			{ string__append_list(["can't rename file `",
+		maybe_write_string(VeryVerbose, "% Removing `", !IO),
+		maybe_write_string(VeryVerbose, OldFileName, !IO),
+		maybe_write_string(VeryVerbose, "'...", !IO),
+		maybe_flush_output(VeryVerbose, !IO),
+		io__remove_file(NewFileName, Result1, !IO),
+		( Result1 = error(Error1) ->
+			maybe_write_string(Verbose, " failed.\n", !IO),
+			maybe_flush_output(Verbose, !IO),
+			io__error_message(Error1, ErrorMsg1),
+			string__append_list(["can't rename file `",
 				OldFileName, "' as `", NewFileName, "': ",
 				ErrorMsg0, "; and can't remove file `",
-				NewFileName, "': ", ErrorMsg1], Message) },
-			report_error(Message),
-			{ Result = Result1 }
-		;
-			maybe_write_string(VeryVerbose, " done.\n"),
-			maybe_write_string(VeryVerbose, "% Renaming `"),
-			maybe_write_string(VeryVerbose, OldFileName),
-			maybe_write_string(VeryVerbose, "' as `"),
-			maybe_write_string(VeryVerbose, NewFileName),
-			maybe_write_string(VeryVerbose, "' again..."),
-			maybe_flush_output(VeryVerbose),
-			io__rename_file(OldFileName, NewFileName, Result2),
-			( { Result2 = error(Error2) } ->
+				NewFileName, "': ", ErrorMsg1], Message),
+			report_error(Message, !IO),
+			Result = Result1
+		;
+			maybe_write_string(VeryVerbose, " done.\n", !IO),
+			maybe_write_string(VeryVerbose, "% Renaming `", !IO),
+			maybe_write_string(VeryVerbose, OldFileName, !IO),
+			maybe_write_string(VeryVerbose, "' as `", !IO),
+			maybe_write_string(VeryVerbose, NewFileName, !IO),
+			maybe_write_string(VeryVerbose, "' again...", !IO),
+			maybe_flush_output(VeryVerbose, !IO),
+			io__rename_file(OldFileName, NewFileName, Result2, !IO),
+			( Result2 = error(Error2) ->
 				maybe_write_string(Verbose,
-					" failed.\n"),
-				maybe_flush_output(Verbose),
-				{ io__error_message(Error2, ErrorMsg) },
-				{ string__append_list(
+					" failed.\n", !IO),
+				maybe_flush_output(Verbose, !IO),
+				io__error_message(Error2, ErrorMsg),
+				string__append_list(
 					["can't rename file `", OldFileName,
 					"' as `", NewFileName, "': ",
-					ErrorMsg], Message) },
-				report_error(Message)
+					ErrorMsg], Message),
+				report_error(Message, !IO)
 			;
-				maybe_write_string(Verbose, " done.\n")
+				maybe_write_string(Verbose, " done.\n", !IO)
 			),
-			{ Result = Result2 }
+			Result = Result2
 		)
 	;
-		maybe_write_string(Verbose, " done.\n"),
-		{ Result = Result0 }
+		maybe_write_string(Verbose, " done.\n", !IO),
+		Result = Result0
 	).
 
-:- pred process_args(options_variables, list(string), list(string),
-		list(string), io__state, io__state).
-:- mode process_args(in, in, in, out, di, uo) is det.
+:- pred process_args(options_variables::in, list(string)::in, list(string)::in,
+	list(string)::out, io::di, io::uo) is det.
 
-process_args(OptionVariables, OptionArgs, Args, ModulesToLink) -->
+process_args(OptionVariables, OptionArgs, Args, ModulesToLink, !IO) :-
 	globals__io_lookup_bool_option(filenames_from_stdin,
-		FileNamesFromStdin),
-	( { FileNamesFromStdin = yes } ->
+		FileNamesFromStdin, !IO),
+	( FileNamesFromStdin = yes ->
 		process_stdin_arg_list(OptionVariables, OptionArgs,
-			[], ModulesToLink)
+			[], ModulesToLink, !IO)
 	;
 		process_arg_list(OptionVariables, OptionArgs,
-			Args, ModulesToLink)
+			Args, ModulesToLink, !IO)
 	).
 
-:- pred process_stdin_arg_list(options_variables, list(string), list(string),
-		list(string), io__state, io__state).
-:- mode process_stdin_arg_list(in, in, in, out, di, uo) is det.
-
-process_stdin_arg_list(OptionVariables, OptionArgs, Modules0, Modules) -->
-	( { Modules0 \= [] } -> garbage_collect ; [] ),
-	io__read_line_as_string(FileResult),
-	( 
-		{ FileResult = ok(Line) },
-		{ string__remove_suffix(Line, "\n", Arg0) ->
+:- pred process_stdin_arg_list(options_variables::in, list(string)::in,
+	list(string)::in, list(string)::out, io::di, io::uo) is det.
+
+process_stdin_arg_list(OptionVariables, OptionArgs, !Modules, !IO) :-
+	( !.Modules \= [] ->
+		garbage_collect(!IO)
+	;
+		true
+	),
+	io__read_line_as_string(FileResult, !IO),
+	(
+		FileResult = ok(Line),
+		( string__remove_suffix(Line, "\n", Arg0) ->
 			Arg = Arg0
 		;
 			Arg = Line
-		},
-		process_arg(OptionVariables, OptionArgs, Arg, Module),
-		{ list__append(Module, Modules0, Modules1) },
+		),
+		process_arg(OptionVariables, OptionArgs, Arg, Module, !IO),
+		list__append(Module, !Modules),
 		process_stdin_arg_list(OptionVariables, OptionArgs,
-			Modules1, Modules)
+			!Modules, !IO)
 	;
-		{ FileResult = eof },
-		{ Modules = Modules0 }
+		FileResult = eof
 	;
-		{ FileResult = error(Error) },
-		{ io__error_message(Error, Msg) },
-		io__write_string("Error reading module name: "),
-		io__write_string(Msg),
-		{ Modules = Modules0 },
-		io__set_exit_status(1)
+		FileResult = error(Error),
+		io__error_message(Error, Msg),
+		io__write_string("Error reading module name: ", !IO),
+		io__write_string(Msg, !IO),
+		io__set_exit_status(1, !IO)
 	).
 
-:- pred process_arg_list(options_variables, list(string), list(string),
-		list(string), io__state, io__state).
-:- mode process_arg_list(in, in, in, out, di, uo) is det.
+:- pred process_arg_list(options_variables::in, list(string)::in,
+	list(string)::in, list(string)::out, io::di, io::uo) is det.
 
-process_arg_list(OptionVariables, OptionArgs, Args, Modules) -->
-	process_arg_list_2(OptionVariables, OptionArgs, Args, ModulesList),
-	{ list__condense(ModulesList, Modules) }.
+process_arg_list(OptionVariables, OptionArgs, Args, Modules, !IO) :-
+	process_arg_list_2(OptionVariables, OptionArgs, Args, ModulesList,
+		!IO),
+	list__condense(ModulesList, Modules).
 
-:- pred process_arg_list_2(options_variables, list(string), list(string),
-		list(list(string)), io__state, io__state).
-:- mode process_arg_list_2(in, in, in, out, di, uo) is det.
+:- pred process_arg_list_2(options_variables::in, list(string)::in,
+	list(string)::in, list(list(string))::out, io::di, io::uo) is det.
 
-process_arg_list_2(_, _, [], []) --> [].
+process_arg_list_2(_, _, [], [], !IO).
 process_arg_list_2(OptionVariables, OptionArgs, [Arg | Args],
-		[Modules | ModulesList]) -->
-	process_arg(OptionVariables, OptionArgs, Arg, Modules),
-	( { Args \= [] } -> garbage_collect ; [] ),
-	process_arg_list_2(OptionVariables, OptionArgs, Args, ModulesList).
+		[Modules | ModulesList], !IO) :-
+	process_arg(OptionVariables, OptionArgs, Arg, Modules, !IO),
+	( Args \= [] ->
+		garbage_collect(!IO)
+	;
+		true
+	),
+	process_arg_list_2(OptionVariables, OptionArgs, Args, ModulesList,
+		!IO).
 
 	% Figure out whether the argument is a module name or a file name.
 	% Open the specified file or module, and process it.
@@ -693,52 +721,57 @@
 	% if they were compiled to seperate object files)
 	% that should be linked into the final executable.
 
-:- pred process_arg(options_variables, list(string), string,
-		list(string), io__state, io__state).
-:- mode process_arg(in, in, in, out, di, uo) is det.
-
-process_arg(OptionVariables, OptionArgs, Arg, ModulesToLink) -->
-	{ FileOrModule = string_to_file_or_module(Arg) },
-	globals__io_lookup_bool_option(invoked_by_mmc_make, InvokedByMake),
-	( { InvokedByMake = no } ->
-    		build_with_module_options(
+:- pred process_arg(options_variables::in, list(string)::in, string::in,
+	list(string)::out, io::di, io::uo) is det.
+
+process_arg(OptionVariables, OptionArgs, Arg, ModulesToLink, !IO) :-
+	FileOrModule = string_to_file_or_module(Arg),
+	globals__io_lookup_bool_option(invoked_by_mmc_make, InvokedByMake,
+		!IO),
+	( InvokedByMake = no ->
+		build_with_module_options(
 			file_or_module_to_module_name(FileOrModule),
-        		OptionVariables, OptionArgs, [],
-			(pred(_::in, yes::out, _::in,
-					Modules::out, di, uo) is det -->	
-	    			process_arg_2(OptionVariables, OptionArgs,
-					FileOrModule, Modules)
-			), _, [], ModulesToLink)
+			OptionVariables, OptionArgs, [],
+			process_arg_build(FileOrModule, OptionVariables,
+				OptionArgs),
+			_, [], ModulesToLink, !IO)
 	;
 		% `mmc --make' has already set up the options.
 		process_arg_2(OptionVariables, OptionArgs,
-			FileOrModule, ModulesToLink)
+			FileOrModule, ModulesToLink, !IO)
 	).
 
-:- pred process_arg_2(options_variables, list(string),
-		file_or_module, list(string), io__state, io__state).
-:- mode process_arg_2(in, in, in, out, di, uo) is det.
+:- pred process_arg_build(file_or_module::in, options_variables::in,
+	list(string)::in, list(string)::in, bool::out,
+	list(string)::in, list(string)::out, io::di, io::uo) is det.
+
+process_arg_build(FileOrModule, OptionVariables, OptionArgs, _, yes,
+		_, Modules, !IO) :-
+	process_arg_2(OptionVariables, OptionArgs, FileOrModule, Modules, !IO).
+
+:- pred process_arg_2(options_variables::in, list(string)::in,
+	file_or_module::in, list(string)::out, io::di, io::uo) is det.
 
-process_arg_2(OptionVariables, OptionArgs, FileOrModule, ModulesToLink) -->
-	globals__io_lookup_bool_option(generate_dependencies, GenerateDeps),
-	( { GenerateDeps = yes } ->
-		{ ModulesToLink = [] },
+process_arg_2(OptionVariables, OptionArgs, FileOrModule, ModulesToLink, !IO) :-
+	globals__io_lookup_bool_option(generate_dependencies, GenerateDeps,
+		!IO),
+	( GenerateDeps = yes ->
+		ModulesToLink = [],
 		(
-			{ FileOrModule = file(FileName) },
-			generate_file_dependencies(FileName)
+			FileOrModule = file(FileName),
+			generate_file_dependencies(FileName, !IO)
 		;
-			{ FileOrModule = module(ModuleName) },
-			generate_module_dependencies(ModuleName)
+			FileOrModule = module(ModuleName),
+			generate_module_dependencies(ModuleName, !IO)
 		)
 	;
 		process_module(OptionVariables, OptionArgs,
-			FileOrModule, ModulesToLink)
+			FileOrModule, ModulesToLink, !IO)
 	).
 
 :- type file_or_module
 	--->	file(file_name)
-	;	module(module_name)
-	.
+	;	module(module_name).
 
 :- func string_to_file_or_module(string) = file_or_module.
 
@@ -753,7 +786,7 @@
 		% name doesn't contain directory seperators, and issuing
 		% a warning or error in that case?)
 		file_name_to_module_name(String, ModuleName),
-		FileOrModule = module(ModuleName) 			
+		FileOrModule = module(ModuleName)
 	).
 
 :- func file_or_module_to_module_name(file_or_module) = module_name.
@@ -763,70 +796,68 @@
 	file_name_to_module_name(FileName, ModuleName).
 file_or_module_to_module_name(module(ModuleName)) = ModuleName.
 
-:- pred read_module(file_or_module, bool, module_name, file_name,
-		maybe(timestamp), item_list, module_error,
-		read_modules, read_modules, io__state, io__state).
-:- mode read_module(in, in, out, out, out, out, out, in, out, di, uo) is det.
+:- pred read_module(file_or_module::in, bool::in, module_name::out,
+	file_name::out, maybe(timestamp)::out, item_list::out,
+	module_error::out, read_modules::in, read_modules::out,
+	io::di, io::uo) is det.
 
 read_module(module(ModuleName), ReturnTimestamp, ModuleName, FileName,
-		MaybeTimestamp, Items, Error, ReadModules0, ReadModules) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	maybe_write_string(Verbose, "% Parsing module `"),
-	{ prog_out__sym_name_to_string(ModuleName, ModuleNameString) },
-	maybe_write_string(Verbose, ModuleNameString),
-	maybe_write_string(Verbose, "' and imported interfaces...\n"),
+		MaybeTimestamp, Items, Error, !ReadModules, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	maybe_write_string(Verbose, "% Parsing module `", !IO),
+	prog_out__sym_name_to_string(ModuleName, ModuleNameString),
+	maybe_write_string(Verbose, ModuleNameString, !IO),
+	maybe_write_string(Verbose, "' and imported interfaces...\n", !IO),
 	(
 		% Avoid rereading the module if it was already read
 		% by recompilation_version.m.
-		{ find_read_module(ReadModules0, ModuleName, ".m",
+		find_read_module(!.ReadModules, ModuleName, ".m",
 			ReturnTimestamp, Items0, MaybeTimestamp0,
-			Error0, FileName0) }
+			Error0, FileName0)
 	->
-		{ map__delete(ReadModules0, ModuleName - ".m", ReadModules) },
-		{ FileName = FileName0 },
-		{ Items = Items0 },
-		{ Error = Error0 },
-		{ MaybeTimestamp = MaybeTimestamp0 }
+		map__delete(!.ReadModules, ModuleName - ".m", !:ReadModules),
+		FileName = FileName0,
+		Items = Items0,
+		Error = Error0,
+		MaybeTimestamp = MaybeTimestamp0
 	;
-		{ ReadModules = ReadModules0 },
 		% We don't search `--search-directories' for source files
 		% because that can result in the generated interface files
 		% being created in the wrong directory.
-		{ Search = no },
+		Search = no,
 		read_mod(ModuleName, ".m", "Reading module", Search,
 			ReturnTimestamp, Items, Error, FileName,
-			MaybeTimestamp)
+			MaybeTimestamp, !IO)
 	),
-	globals__io_lookup_bool_option(statistics, Stats),
-	maybe_report_stats(Stats).
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+	maybe_report_stats(Stats, !IO).
 read_module(file(FileName), ReturnTimestamp, ModuleName, SourceFileName,
-		MaybeTimestamp, Items, Error, ReadModules0, ReadModules) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	maybe_write_string(Verbose, "% Parsing file `"),
-	maybe_write_string(Verbose, FileName),
-	maybe_write_string(Verbose, "' and imported interfaces...\n"),
+		MaybeTimestamp, Items, Error, !ReadModules, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	maybe_write_string(Verbose, "% Parsing file `", !IO),
+	maybe_write_string(Verbose, FileName, !IO),
+	maybe_write_string(Verbose, "' and imported interfaces...\n", !IO),
 
-	{ file_name_to_module_name(FileName, DefaultModuleName) },
+	file_name_to_module_name(FileName, DefaultModuleName),
 	(
 		% Avoid rereading the module if it was already read
 		% by recompilation_version.m.
-		{ find_read_module(ReadModules0, DefaultModuleName, ".m",
-			ReturnTimestamp, Items0, MaybeTimestamp0, Error0, _) }
+		find_read_module(!.ReadModules, DefaultModuleName, ".m",
+			ReturnTimestamp, Items0, MaybeTimestamp0, Error0, _)
 	->
-		{ map__delete(ReadModules0, ModuleName - ".m", ReadModules) },
-		{ ModuleName = DefaultModuleName },
-		{ Items = Items0 },
-		{ Error = Error0 },
-		{ MaybeTimestamp = MaybeTimestamp0 }
+		map__delete(!.ReadModules, ModuleName - ".m", !:ReadModules),
+		ModuleName = DefaultModuleName,
+		Items = Items0,
+		Error = Error0,
+		MaybeTimestamp = MaybeTimestamp0
 	;
-		{ ReadModules = ReadModules0 },
 		% We don't search `--search-directories' for source files
 		% because that can result in the generated interface files
 		% being created in the wrong directory.
-		{ Search = no },
+		Search = no,
 		read_mod_from_file(FileName, ".m", "Reading file", Search,
 			ReturnTimestamp, Items, Error, ModuleName,
-			MaybeTimestamp),
+			MaybeTimestamp, !IO),
 
 		%
 		% XXX If the module name doesn't match the file name
@@ -836,58 +867,64 @@
 		% This will be fixed when mmake functionality
 		% is moved into the compiler.
 		%
-		globals__io_lookup_bool_option(smart_recompilation, Smart),
-		( { Smart = yes, ModuleName \= DefaultModuleName } ->
-			globals__io_lookup_bool_option(
-				warn_smart_recompilation, Warn),
+		globals__io_lookup_bool_option(smart_recompilation, Smart, !IO),
+		(
+			Smart = yes,
+			ModuleName \= DefaultModuleName
+		->
 			globals__io_lookup_bool_option(
-				halt_at_warn, Halt),
-			( { Warn = yes } ->
-				io__write_string(
-		"Warning: module name does not match file name:\n"),
-				io__write_string("  "),
-				io__write_string(FileName),
-				io__write_string(" contains module `"),
-				prog_out__write_sym_name(ModuleName),	
-				io__write_string(".\n"),
-				io__write_string(
-		"  Smart recompilation will not work unless a module name\n"),
-				io__write_string(
-		"  to file name mapping is created using `mmc -f *.m'.\n"),
-				( { Halt = yes } ->
-					io__set_exit_status(1)
+				warn_smart_recompilation, Warn, !IO),
+			globals__io_lookup_bool_option(halt_at_warn, Halt,
+				!IO),
+			( Warn = yes ->
+				Msg1 = "Warning: module name does not " ++
+					"match file name: ",
+				ModuleNameStr = describe_sym_name(ModuleName),
+				Msg2 = FileName ++ " contains module `" ++
+					ModuleNameStr ++ "'.",
+				Msg3 = "Smart recompilation will not work " ++
+					"unless a module name to file name " ++
+					"mapping is created using " ++
+					"`mmc -f *.m'.",
+				write_error_pieces_plain([words(Msg1), nl,
+					words(Msg2), nl, words(Msg3)], !IO),
+				( Halt = yes ->
+					io__set_exit_status(1, !IO)
 				;
-					[]
+					true
 				)
 			;
-				[]	
+				true
 			),
-			globals__io_set_option(smart_recompilation, bool(no))
+			globals__io_set_option(smart_recompilation, bool(no),
+				!IO)
 		;
-			[]
+			true
 		)
 	),
-
-	globals__io_lookup_bool_option(statistics, Stats),
-	maybe_report_stats(Stats),
-	{ string__append(FileName, ".m", SourceFileName) }.
-
-:- pred process_module(options_variables, list(string),
-		file_or_module, list(string), io__state, io__state).
-:- mode process_module(in, in, in, out, di, uo) is det.
-
-process_module(OptionVariables, OptionArgs, FileOrModule, ModulesToLink) -->
-	globals__io_lookup_bool_option(halt_at_syntax_errors, HaltSyntax),
-	globals__io_lookup_bool_option(make_interface, MakeInterface),
-	globals__io_lookup_bool_option(make_short_interface,
-						MakeShortInterface),
-	globals__io_lookup_bool_option(make_private_interface,
-						MakePrivateInterface),
-	globals__io_lookup_bool_option(convert_to_mercury, ConvertToMercury),
-	globals__io_lookup_bool_option(generate_item_version_numbers,
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+	maybe_report_stats(Stats, !IO),
+	string__append(FileName, ".m", SourceFileName).
+
+:- pred process_module(options_variables::in, list(string)::in,
+	file_or_module::in, list(string)::out, io::di, io::uo) is det.
+
+process_module(OptionVariables, OptionArgs, FileOrModule, ModulesToLink,
+		!IO) :-
+	globals__io_get_globals(Globals, !IO),
+	globals__lookup_bool_option(Globals, halt_at_syntax_errors,
+		HaltSyntax),
+	globals__lookup_bool_option(Globals, make_interface, MakeInterface),
+	globals__lookup_bool_option(Globals, make_short_interface,
+		MakeShortInterface),
+	globals__lookup_bool_option(Globals, make_private_interface,
+		MakePrivateInterface),
+	globals__lookup_bool_option(Globals, convert_to_mercury,
+		ConvertToMercury),
+	globals__lookup_bool_option(Globals, generate_item_version_numbers,
 		GenerateVersionNumbers),
-	( 
-		{ MakeInterface = yes ->
+	(
+		( MakeInterface = yes ->
 			ProcessModule = make_interface,
 			ReturnTimestamp = GenerateVersionNumbers
 		; MakeShortInterface = yes ->
@@ -898,41 +935,42 @@
 			ReturnTimestamp = GenerateVersionNumbers
 		;
 			fail
-		}
+		)
 	->
 		read_module(FileOrModule, ReturnTimestamp, ModuleName,
-			FileName, MaybeTimestamp, Items, Error, map__init, _),
-		( { halt_at_module_error(HaltSyntax, Error) } ->
-			[]
-		;
-			split_into_submodules(ModuleName, Items, SubModuleList),
-			list__foldl(
-				(pred(SubModule::in, di, uo) is det -->
-					ProcessModule(FileName, ModuleName,
-						MaybeTimestamp, SubModule)
-				),
-				SubModuleList)
+			FileName, MaybeTimestamp, Items, Error, map__init, _,
+			!IO),
+		( halt_at_module_error(HaltSyntax, Error) ->
+			true
+		;
+			split_into_submodules(ModuleName, Items, SubModuleList,
+				!IO),
+			list__foldl(apply_process_module(ProcessModule,
+				FileName, ModuleName, MaybeTimestamp),
+				SubModuleList, !IO)
 		),
-		{ ModulesToLink = [] }
+		ModulesToLink = []
 	;
-		{ ConvertToMercury = yes }
+		ConvertToMercury = yes
 	->
 		read_module(FileOrModule, no, ModuleName, _, _,
-			Items, Error, map__init, _),
-			
-		( { halt_at_module_error(HaltSyntax, Error) } ->
-			[]
+			Items, Error, map__init, _, !IO),
+
+		( halt_at_module_error(HaltSyntax, Error) ->
+			true
 		;
 			module_name_to_file_name(ModuleName, ".ugly", yes,
-					OutputFileName),
-			convert_to_mercury(ModuleName, OutputFileName, Items)
+				OutputFileName, !IO),
+			convert_to_mercury(ModuleName, OutputFileName, Items,
+				!IO)
 		),
-		{ ModulesToLink = [] }
+		ModulesToLink = []
 	;
-		globals__io_lookup_bool_option(smart_recompilation, Smart),
-		globals__io_get_target(Target),
-		( { Smart = yes } ->
-			{
+		globals__lookup_bool_option(Globals, smart_recompilation,
+			Smart),
+		globals__get_target(Globals, Target),
+		( Smart = yes ->
+			(
 				FileOrModule = module(ModuleName)
 			;
 				FileOrModule = file(FileName),
@@ -945,21 +983,20 @@
 				% The file_name->module_name mapping
 				% will be explicitly recorded.
 				file_name_to_module_name(FileName, ModuleName)
-			},
+			),
 
-			globals__io_get_globals(Globals),
-			{ find_smart_recompilation_target_files(ModuleName,
-				Globals, FindTargetFiles) },
-			{ find_timestamp_files(ModuleName, Globals,
-				FindTimestampFiles) },
+			find_smart_recompilation_target_files(ModuleName,
+				Globals, FindTargetFiles),
+			find_timestamp_files(ModuleName, Globals,
+				FindTimestampFiles),
 			recompilation__check__should_recompile(ModuleName,
 				FindTargetFiles, FindTimestampFiles,
-				ModulesToRecompile0, ReadModules),
-			{
+				ModulesToRecompile0, ReadModules, !IO),
+			(
 				Target = asm,
 				ModulesToRecompile0 = some([_ | _])
 			->
-				% 
+				%
 				% With `--target asm', if one module
 				% needs to be recompiled, all need to be
 				% recompiled because they are all compiled
@@ -968,65 +1005,78 @@
 				ModulesToRecompile = (all)
 			;
 				ModulesToRecompile = ModulesToRecompile0
-			}
+			)
 		;
-			{ map__init(ReadModules) },
-			{ ModulesToRecompile = (all) }
+			map__init(ReadModules),
+			ModulesToRecompile = (all)
 		),
-		( { ModulesToRecompile = some([]) } ->
+		( ModulesToRecompile = some([]) ->
 			% XXX Currently smart recompilation is disabled
 			% if mmc is linking the executable because it
 			% doesn't know how to check whether all the
 			% necessary intermediate files are present
 			% and up-to-date.
-			{ ModulesToLink = [] }
+			ModulesToLink = []
 		;
-			( { Target = asm, Smart = yes } ->
-			    % See the comment in process_all_args.
-			    compile_using_gcc_backend(OptionVariables,
-			    	OptionArgs, FileOrModule,
-				process_module_2(FileOrModule,
-					ModulesToRecompile, ReadModules),
-				ModulesToLink)
+			(
+				Target = asm,
+				Smart = yes
+			->
+				% See the comment in process_all_args.
+				compile_using_gcc_backend(OptionVariables,
+					OptionArgs, FileOrModule,
+					process_module_2(FileOrModule,
+						ModulesToRecompile,
+						ReadModules),
+					ModulesToLink, !IO)
 			;
-			    process_module_2(FileOrModule, ModulesToRecompile,
-			    	ReadModules, ModulesToLink)
+				process_module_2(FileOrModule,
+					ModulesToRecompile, ReadModules,
+					ModulesToLink, !IO)
 			)
 		)
 	).
 
-:- pred process_module_2(file_or_module, modules_to_recompile,
-		read_modules, list(string), io__state, io__state).
-:- mode process_module_2(in, in, in, out, di, uo) is det.
+:- pred apply_process_module(
+	pred(file_name, module_name, maybe(timestamp),
+		pair(module_name, item_list), io, io)::
+		in(pred(in, in, in, in, di, uo) is det),
+	file_name::in, module_name::in, maybe(timestamp)::in,
+	pair(module_name, item_list)::in, io::di, io::uo) is det.
+
+apply_process_module(ProcessModule, FileName, ModuleName, MaybeTimestamp,
+		SubModule, !IO) :-
+	ProcessModule(FileName, ModuleName, MaybeTimestamp, SubModule, !IO).
+
+:- pred process_module_2(file_or_module::in, modules_to_recompile::in,
+	read_modules::in, list(string)::out, io::di, io::uo) is det.
 
 process_module_2(FileOrModule, MaybeModulesToRecompile, ReadModules0,
-		ModulesToLink) -->
+		ModulesToLink, !IO) :-
 	read_module(FileOrModule, yes, ModuleName, FileName,
-		MaybeTimestamp, Items, Error, ReadModules0, ReadModules),
-	globals__io_lookup_bool_option(halt_at_syntax_errors, HaltSyntax),
-	( { halt_at_module_error(HaltSyntax, Error) } ->
-		{ ModulesToLink = [] }
-	;
-		split_into_submodules(ModuleName, Items, SubModuleList0),
-		{ MaybeModulesToRecompile = some(ModulesToRecompile) ->
-			list__filter(
-				(pred((SubModule - _)::in) is semidet :-
-					list__member(SubModule,
-						ModulesToRecompile)
-				),
-				SubModuleList0, SubModuleListToCompile)
+		MaybeTimestamp, Items, Error, ReadModules0, ReadModules, !IO),
+	globals__io_lookup_bool_option(halt_at_syntax_errors, HaltSyntax, !IO),
+	( halt_at_module_error(HaltSyntax, Error) ->
+		ModulesToLink = []
+	;
+		split_into_submodules(ModuleName, Items, SubModuleList0, !IO),
+		( MaybeModulesToRecompile = some(ModulesToRecompile) ->
+			ToRecompile = (pred((SubModule - _)::in) is semidet :-
+				list__member(SubModule, ModulesToRecompile)
+			),
+			list__filter(ToRecompile, SubModuleList0,
+				SubModuleListToCompile)
 		;
-				SubModuleListToCompile = SubModuleList0	
-		},
-		{ assoc_list__keys(SubModuleList0, NestedSubModules0) },
-		{ list__delete_all(NestedSubModules0,
-			ModuleName, NestedSubModules) },
-
-		globals__io_get_globals(Globals),
-		{ find_timestamp_files(ModuleName, Globals,
-			FindTimestampFiles) },
+			SubModuleListToCompile = SubModuleList0
+		),
+		assoc_list__keys(SubModuleList0, NestedSubModules0),
+		list__delete_all(NestedSubModules0, ModuleName,
+			NestedSubModules),
+
+		globals__io_get_globals(Globals, !IO),
+		find_timestamp_files(ModuleName, Globals, FindTimestampFiles),
 		(
-			{ any_mercury_builtin_module(ModuleName) }
+			any_mercury_builtin_module(ModuleName)
 		->
 			% Some predicates in the builtin modules are missing
 			% typeinfo arguments, which means that execution
@@ -1035,26 +1085,28 @@
 			% anyway; they are effectively language primitives.
 			% (They may still be parts of stack traces.)
 			globals__io_lookup_bool_option(trace_stack_layout,
-				TSL),
-			globals__io_get_trace_level(TraceLevel),
+				TSL, !IO),
+			globals__io_get_trace_level(TraceLevel, !IO),
 
-			globals__io_set_option(trace_stack_layout, bool(no)),
-			globals__io_set_trace_level_none,
+			globals__io_set_option(trace_stack_layout, bool(no),
+				!IO),
+			globals__io_set_trace_level_none(!IO),
 
 			compile_all_submodules(FileName,
 				ModuleName, NestedSubModules,
 				MaybeTimestamp, ReadModules,
 				FindTimestampFiles, SubModuleListToCompile,
-				ModulesToLink),
+				ModulesToLink, !IO),
 
-			globals__io_set_option(trace_stack_layout, bool(TSL)),
-			globals__io_set_trace_level(TraceLevel)
+			globals__io_set_option(trace_stack_layout, bool(TSL),
+				!IO),
+			globals__io_set_trace_level(TraceLevel, !IO)
 		;
 			compile_all_submodules(FileName,
 				ModuleName, NestedSubModules,
 				MaybeTimestamp, ReadModules,
 				FindTimestampFiles, SubModuleListToCompile,
-				ModulesToLink)
+				ModulesToLink, !IO)
 		)
 	).
 
@@ -1069,80 +1121,76 @@
 	%
 	% i.e. compile nested modules to a single C file.
 
-:- pred compile_all_submodules(string, module_name, list(module_name),
-	maybe(timestamp), read_modules, find_timestamp_file_names,
-	list(pair(module_name, item_list)),
-	list(string), io__state, io__state).
-:- mode compile_all_submodules(in, in, in, in, in,
-	in(find_timestamp_file_names), in, out, di, uo) is det.
+:- pred compile_all_submodules(string::in, module_name::in,
+	list(module_name)::in, maybe(timestamp)::in, read_modules::in,
+	find_timestamp_file_names::in(find_timestamp_file_names),
+	list(pair(module_name, item_list))::in, list(string)::out,
+	io::di, io::uo) is det.
 
 compile_all_submodules(FileName, SourceFileModuleName, NestedSubModules,
 		MaybeTimestamp, ReadModules, FindTimestampFiles,
-		SubModuleList, ModulesToLink) -->
+		SubModuleList, ModulesToLink, !IO) :-
 	list__foldl(
 		compile(FileName, SourceFileModuleName, NestedSubModules,
 			MaybeTimestamp, ReadModules, FindTimestampFiles),
-		SubModuleList),
-	list__map_foldl(module_to_link, SubModuleList, ModulesToLink).
+		SubModuleList, !IO),
+	list__map(module_to_link, SubModuleList, ModulesToLink).
 
-:- pred make_interface(file_name, module_name, maybe(timestamp),
-		pair(module_name, item_list), io__state, io__state).
-:- mode make_interface(in, in, in, in, di, uo) is det.
+:- pred make_interface(file_name::in, module_name::in, maybe(timestamp)::in,
+	pair(module_name, item_list)::in, io::di, io::uo) is det.
 
 make_interface(SourceFileName, SourceFileModuleName, MaybeTimestamp,
-		ModuleName - Items) -->
+		ModuleName - Items, !IO) :-
 	make_interface(SourceFileName, SourceFileModuleName,
-		ModuleName, MaybeTimestamp, Items).
+		ModuleName, MaybeTimestamp, Items, !IO).
 
-:- pred make_short_interface(file_name, module_name, maybe(timestamp),
-		pair(module_name, item_list), io__state, io__state).
-:- mode make_short_interface(in, in, in, in, di, uo) is det.
-
-make_short_interface(SourceFileName, _, _, ModuleName - Items) -->
-	make_short_interface(SourceFileName, ModuleName, Items).
-
-:- pred make_private_interface(file_name, module_name, maybe(timestamp),
-		pair(module_name, item_list), io__state, io__state).
-:- mode make_private_interface(in, in, in, in, di, uo) is det.
+:- pred make_short_interface(file_name::in, module_name::in,
+	maybe(timestamp)::in, pair(module_name, item_list)::in,
+	io::di, io::uo) is det.
+
+make_short_interface(SourceFileName, _, _, ModuleName - Items, !IO) :-
+	make_short_interface(SourceFileName, ModuleName, Items, !IO).
+
+:- pred make_private_interface(file_name::in, module_name::in,
+	maybe(timestamp)::in, pair(module_name, item_list)::in,
+	io::di, io::uo) is det.
 
 make_private_interface(SourceFileName, SourceFileModuleName,
-		MaybeTimestamp, ModuleName - Items) -->
+		MaybeTimestamp, ModuleName - Items, !IO) :-
 	make_private_interface(SourceFileName, SourceFileModuleName,
-		ModuleName, MaybeTimestamp, Items).
+		ModuleName, MaybeTimestamp, Items, !IO).
 
-:- pred halt_at_module_error(bool, module_error).
-:- mode halt_at_module_error(in, in) is semidet.
+:- pred halt_at_module_error(bool::in, module_error::in) is semidet.
 
 halt_at_module_error(_, fatal_module_errors).
 halt_at_module_error(HaltSyntax, some_module_errors) :- HaltSyntax = yes.
 
-:- pred module_to_link(pair(module_name, item_list), string,
-			io__state, io__state).
-:- mode module_to_link(in, out, di, uo) is det.
+:- pred module_to_link(pair(module_name, item_list)::in, string::out) is det.
 
-module_to_link(ModuleName - _Items, ModuleToLink) -->
-	{ module_name_to_file_name(ModuleName, ModuleToLink) }.
+module_to_link(ModuleName - _Items, ModuleToLink) :-
+	module_name_to_file_name(ModuleName, ModuleToLink).
 
 :- type compile == pred(bool, io__state, io__state).
 :- inst compile == (pred(out, di, uo) is det).
 
 :- pred compile_with_module_options(module_name::in, options_variables::in,
-		list(string)::in, compile::in(compile),
-		bool::out, io__state::di, io__state::uo) is det.
+	list(string)::in, compile::in(compile),
+	bool::out, io__state::di, io__state::uo) is det.
 
 compile_with_module_options(ModuleName, OptionVariables, OptionArgs,
-		Compile, Succeeded) -->
-	globals__io_lookup_bool_option(invoked_by_mmc_make, InvokedByMake),
-	( { InvokedByMake = yes } ->
+		Compile, Succeeded, !IO) :-
+	globals__io_lookup_bool_option(invoked_by_mmc_make, InvokedByMake,
+		!IO),
+	( InvokedByMake = yes ->
 		% `mmc --make' has already set up the options.
-		Compile(Succeeded)
+		Compile(Succeeded, !IO)
 	;
 		build_with_module_options(ModuleName, OptionVariables,
 			OptionArgs, [],
-			(pred(_::in, Succeeded0::out,
-					X::in, X::out, di, uo) is det -->
-				Compile(Succeeded0)
-			), Succeeded, unit, _)
+			(pred(_::in, Succeeded0::out, X::in, X::out,
+					IO0::di, IO::uo) is det :-
+				Compile(Succeeded0, IO0, IO)
+			), Succeeded, unit, _, !IO)
 	).
 
 %-----------------------------------------------------------------------------%
@@ -1157,10 +1205,8 @@
 	% without using mmake is not a sensible thing to do.
 	% handle_options.m will disable smart recompilation if
 	% `--target-code-only' is not set.
-:- pred find_smart_recompilation_target_files(module_name, globals,
-		find_target_file_names).
-:- mode find_smart_recompilation_target_files(in, in,
-		out(find_target_file_names)) is det.
+:- pred find_smart_recompilation_target_files(module_name::in, globals::in,
+	find_target_file_names::out(find_target_file_names)) is det.
 
 find_smart_recompilation_target_files(TopLevelModuleName,
 		Globals, FindTargetFiles) :-
@@ -1169,69 +1215,88 @@
 		CompilationTarget = c,
 		globals__lookup_bool_option(Globals, split_c_files, yes)
 	->
-		FindTargetFiles =
-		    (pred(ModuleName::in, [FileName]::out, di, uo) is det -->
-			% We don't know how many chunks there should
-			% be, so just check the first.
-			{ Chunk = 0 },
-			globals__io_lookup_string_option(object_file_extension,
-				Obj),
-			module_name_to_split_c_file_name(ModuleName, Chunk,
-				Obj, FileName)
-		)
+		FindTargetFiles = split_c_find_target_files
 	;
 		( CompilationTarget = c, TargetSuffix = ".c"
 		; CompilationTarget = il, TargetSuffix = ".il"
 		; CompilationTarget = java, TargetSuffix = ".java"
 		; CompilationTarget = asm, TargetSuffix = ".s"
 		),
-		FindTargetFiles =
-		    (pred(ModuleName::in, TargetFiles::out, di, uo) is det -->
-			% XXX Should we check the generated header files?
-			(
-				{ CompilationTarget = asm },
-				{ ModuleName \= TopLevelModuleName }
-			->
-				% With `--target asm' all the nested
-				% sub-modules are placed in the `.s' file
-				% of the top-level module.
-				{ TargetFiles = [] }
-			;
-				module_name_to_file_name(ModuleName,
-					TargetSuffix, yes, FileName),
-				{ TargetFiles = [FileName] }
-			)
-		    )
+		FindTargetFiles = usual_find_target_files(CompilationTarget,
+			TargetSuffix, TopLevelModuleName)
+	).
+
+:- pred split_c_find_target_files(module_name::in, list(file_name)::out,
+	io::di, io::uo) is det.
+
+split_c_find_target_files(ModuleName, [FileName], !IO) :-
+	globals__io_lookup_string_option(object_file_extension, Obj, !IO),
+	% We don't know how many chunks there should be, so just check
+	% the first.
+	module_name_to_split_c_file_name(ModuleName, 0, Obj, FileName, !IO).
+
+:- pred usual_find_target_files(compilation_target::in, string::in,
+	module_name::in, module_name::in, list(file_name)::out,
+	io::di, io::uo) is det.
+
+usual_find_target_files(CompilationTarget, TargetSuffix, TopLevelModuleName,
+		ModuleName, TargetFiles, !IO) :-
+	% XXX Should we check the generated header files?
+	(
+		CompilationTarget = asm,
+		ModuleName \= TopLevelModuleName
+	->
+		% With `--target asm' all the nested
+		% sub-modules are placed in the `.s' file
+		% of the top-level module.
+		TargetFiles = []
+	;
+		module_name_to_file_name(ModuleName, TargetSuffix, yes,
+			FileName, !IO),
+		TargetFiles = [FileName]
 	).
 
-:- pred find_timestamp_files(module_name, globals, find_timestamp_file_names).
-:- mode find_timestamp_files(in, in, out(find_timestamp_file_names)) is det.
+:- pred find_timestamp_files(module_name::in, globals::in,
+	find_timestamp_file_names::out(find_timestamp_file_names)) is det.
 
 find_timestamp_files(TopLevelModuleName, Globals, FindTimestampFiles) :-
 	globals__lookup_bool_option(Globals, pic, Pic),
 	globals__get_target(Globals, CompilationTarget),
-	( CompilationTarget = c, TimestampSuffix = ".c_date"
-	; CompilationTarget = il, TimestampSuffix = ".il_date"
-	; CompilationTarget = java, TimestampSuffix = ".java_date"
-	; CompilationTarget = asm,
+	(
+		CompilationTarget = c,
+		TimestampSuffix = ".c_date"
+	;
+		CompilationTarget = il,
+		TimestampSuffix = ".il_date"
+	;
+		CompilationTarget = java,
+		TimestampSuffix = ".java_date"
+	;
+		CompilationTarget = asm,
 		TimestampSuffix = (Pic = yes -> ".pic_s_date" ; ".s_date")
 	),
-	FindTimestampFiles =
-	    (pred(ModuleName::in, TimestampFiles::out, di, uo) is det -->
-		(
-			{ CompilationTarget = asm },
-			{ ModuleName \= TopLevelModuleName }
-		->
-			% With `--target asm' all the nested
-			% sub-modules are placed in the `.s' file
-			% of the top-level module.
-			{ TimestampFiles = [] }
-		;
-			module_name_to_file_name(ModuleName,
-				TimestampSuffix, yes, FileName),
-			{ TimestampFiles = [FileName] }
-		)
-	    ).
+	FindTimestampFiles = find_timestamp_files_2(CompilationTarget,
+		TimestampSuffix, TopLevelModuleName).
+
+:- pred find_timestamp_files_2(compilation_target::in, string::in,
+	module_name::in, module_name::in, list(file_name)::out,
+	io::di, io::uo) is det.
+
+find_timestamp_files_2(CompilationTarget, TimestampSuffix,
+		TopLevelModuleName, ModuleName, TimestampFiles, !IO) :-
+	(
+		CompilationTarget = asm,
+		ModuleName \= TopLevelModuleName
+	->
+		% With `--target asm' all the nested
+		% sub-modules are placed in the `.s' file
+		% of the top-level module.
+		TimestampFiles = []
+	;
+		module_name_to_file_name(ModuleName, TimestampSuffix, yes,
+			FileName, !IO),
+		TimestampFiles = [FileName]
+	).
 
 %-----------------------------------------------------------------------------%
 
@@ -1248,167 +1313,197 @@
 	% The initial arrangement has the stage numbers increasing by three
 	% so that new stages can be slotted in without too much trouble.
 
-:- pred compile(file_name, module_name, list(module_name),
-	maybe(timestamp), read_modules, find_timestamp_file_names,
-	pair(module_name, item_list), io__state, io__state).
-:- mode compile(in, in, in, in, in, in(find_timestamp_file_names),
-	in, di, uo) is det.
+:- pred compile(file_name::in, module_name::in, list(module_name)::in,
+	maybe(timestamp)::in, read_modules::in,
+	find_timestamp_file_names::in(find_timestamp_file_names),
+	pair(module_name, item_list)::in, io::di, io::uo) is det.
 
 compile(SourceFileName, SourceFileModuleName, NestedSubModules0,
 		MaybeTimestamp, ReadModules, FindTimestampFiles,
-		ModuleName - Items) -->
-	check_for_no_exports(Items, ModuleName),
-	{ ModuleName = SourceFileModuleName ->
+		ModuleName - Items, !IO) :-
+	check_for_no_exports(Items, ModuleName, !IO),
+	( ModuleName = SourceFileModuleName ->
 		NestedSubModules = NestedSubModules0
 	;
 		NestedSubModules = []
-	},
+	),
 	grab_imported_modules(SourceFileName, SourceFileModuleName, ModuleName,
 		NestedSubModules, ReadModules, MaybeTimestamp,
-		Items, Module, Error2),
-	( { Error2 \= fatal_module_errors } ->
-		mercury_compile(Module, NestedSubModules, FindTimestampFiles)
+		Items, Module, Error2, !IO),
+	( Error2 \= fatal_module_errors ->
+		mercury_compile(Module, NestedSubModules, FindTimestampFiles,
+			!IO)
 	;
-		[]
+		true
 	).
 
-:- pred mercury_compile(module_imports, list(module_name),
-		find_timestamp_file_names, io__state, io__state).
-:- mode mercury_compile(in, in, in(find_timestamp_file_names), di, uo) is det.
+:- pred mercury_compile(module_imports::in, list(module_name)::in,
+	find_timestamp_file_names::in(find_timestamp_file_names),
+	io::di, io::uo) is det.
 
-mercury_compile(Module, NestedSubModules, FindTimestampFiles) -->
-	{ module_imports_get_module_name(Module, ModuleName) },
+mercury_compile(Module, NestedSubModules, FindTimestampFiles, !IO) :-
+	module_imports_get_module_name(Module, ModuleName),
 	% If we are only typechecking or error checking, then we should not
 	% modify any files, this includes writing to .d files.
-	globals__io_lookup_bool_option(typecheck_only, TypeCheckOnly),
-	globals__io_lookup_bool_option(errorcheck_only, ErrorCheckOnly),
-	{ bool__or(TypeCheckOnly, ErrorCheckOnly, DontWriteDFile) },
+	globals__io_lookup_bool_option(typecheck_only, TypeCheckOnly, !IO),
+	globals__io_lookup_bool_option(errorcheck_only, ErrorCheckOnly, !IO),
+	bool__or(TypeCheckOnly, ErrorCheckOnly, DontWriteDFile),
 	mercury_compile__pre_hlds_pass(Module, DontWriteDFile,
 		HLDS1, QualInfo, MaybeTimestamps, UndefTypes, UndefModes,
-		Errors1),
-	mercury_compile__frontend_pass(HLDS1, QualInfo, UndefTypes,
-		UndefModes, Errors1, HLDS20, Errors2),
-	( { Errors1 = no }, { Errors2 = no } ->
-	    globals__io_lookup_bool_option(verbose, Verbose),
-	    globals__io_lookup_bool_option(statistics, Stats),
-	    mercury_compile__maybe_write_dependency_graph(HLDS20,
-		Verbose, Stats, HLDS21),
-	    mercury_compile__maybe_generate_schemas(HLDS21, Verbose),
-	    globals__io_lookup_bool_option(make_optimization_interface,
-		MakeOptInt),
-	    globals__io_lookup_bool_option(make_transitive_opt_interface,
-		MakeTransOptInt),
-	    ( { TypeCheckOnly = yes } ->
-		[]
-	    ; { ErrorCheckOnly = yes } ->
-		% we may still want to run `unused_args' so that we get
-		% the appropriate warnings
-		globals__io_lookup_bool_option(warn_unused_args, UnusedArgs),
-		( { UnusedArgs = yes } ->
-			globals__io_set_option(optimize_unused_args, bool(no)),
-			mercury_compile__maybe_unused_args(HLDS21,
-				Verbose, Stats, HLDS22)
-	    	;
-			{ HLDS22 = HLDS21 }
-	    	),
-		% magic sets can report errors.
-		mercury_compile__maybe_transform_dnf(HLDS22,
-			Verbose, Stats, HLDS23),
-		mercury_compile__maybe_magic(HLDS23, Verbose, Stats, _)
-	    ; { MakeOptInt = yes } ->
-		% only run up to typechecking when making the .opt file
-		[]
-	    ; { MakeTransOptInt = yes } ->
-	    	mercury_compile__output_trans_opt_file(HLDS21)
-	    ;
-		mercury_compile__maybe_output_prof_call_graph(HLDS21,
-			Verbose, Stats, HLDS25),
-		mercury_compile__middle_pass(ModuleName, HLDS25, HLDS50,
-			DeepProfilingStructures),
-		globals__io_lookup_bool_option(highlevel_code, HighLevelCode),
-		globals__io_lookup_bool_option(aditi_only, AditiOnly),
-		globals__io_get_target(Target),
-		globals__io_lookup_bool_option(target_code_only, 
-				TargetCodeOnly),
+		Errors1, !IO),
+	mercury_compile__frontend_pass(QualInfo, UndefTypes,
+		UndefModes, Errors1, Errors2, HLDS1, HLDS20, !IO),
+	( Errors1 = no, Errors2 = no ->
+		globals__io_lookup_bool_option(verbose, Verbose, !IO),
+		globals__io_lookup_bool_option(statistics, Stats, !IO),
+		mercury_compile__maybe_write_dependency_graph(Verbose, Stats,
+			HLDS20, HLDS21, !IO),
+		mercury_compile__maybe_generate_schemas(HLDS21, Verbose, Stats,
+			!IO),
+		globals__io_lookup_bool_option(make_optimization_interface,
+			MakeOptInt, !IO),
+		globals__io_lookup_bool_option(make_transitive_opt_interface,
+			MakeTransOptInt, !IO),
+		( TypeCheckOnly = yes ->
+			true
+		; ErrorCheckOnly = yes ->
+			% we may still want to run `unused_args' so that we get
+			% the appropriate warnings
+			globals__io_lookup_bool_option(warn_unused_args,
+				UnusedArgs, !IO),
+			( UnusedArgs = yes ->
+				globals__io_set_option(optimize_unused_args,
+					bool(no), !IO),
+				mercury_compile__maybe_unused_args(
+					Verbose, Stats, HLDS21, HLDS22, !IO)
+			;
+				HLDS22 = HLDS21
+			),
+			% magic sets can report errors.
+			mercury_compile__maybe_transform_dnf(Verbose, Stats,
+				HLDS22, HLDS23, !IO),
+			mercury_compile__maybe_magic(Verbose, Stats,
+				HLDS23, _, !IO)
+		; MakeOptInt = yes ->
+			% only run up to typechecking when making the .opt file
+			true
+		; MakeTransOptInt = yes ->
+			mercury_compile__output_trans_opt_file(HLDS21, !IO)
+		;
+			mercury_compile_after_front_end(NestedSubModules,
+				FindTimestampFiles, MaybeTimestamps,
+				ModuleName, HLDS21, !IO)
+		)
+	;
+		% If the number of errors is > 0, make sure that the compiler
+		% exits with a non-zero exit status.
+		io__get_exit_status(ExitStatus, !IO),
+		( ExitStatus = 0 ->
+			io__set_exit_status(1, !IO)
+		;
+			true
+		)
+	).
 
-		%
-		% Remove any existing `.used' file before writing the
-		% output file file. This avoids leaving the old `used'
-		% file lying around if compilation is interrupted after
-		% the new output file is written but before the new
-		% `.used' file is written.
-		%
-		module_name_to_file_name(ModuleName, ".used", no,
-			UsageFileName),
-		io__remove_file(UsageFileName, _),
-
-		% magic sets can report errors.
-		{ module_info_num_errors(HLDS50, NumErrors) },
-		( { NumErrors = 0 } ->
-
-		    globals__io_lookup_bool_option(intermodule_analysis,
-				IntermodAnalysis),
-		    ( { IntermodAnalysis = yes } ->
-			{ module_info_analysis_info(HLDS50, AnalysisInfo) },
+:- pred mercury_compile_after_front_end(list(module_name)::in,
+	find_timestamp_file_names::in(find_timestamp_file_names),
+	maybe(module_timestamps)::in, module_name::in, module_info::in,
+	io::di, io::uo) is det.
+
+mercury_compile_after_front_end(NestedSubModules, FindTimestampFiles,
+		MaybeTimestamps, ModuleName, HLDS21, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+	mercury_compile__maybe_output_prof_call_graph(Verbose, Stats,
+		HLDS21, HLDS25, !IO),
+	mercury_compile__middle_pass(ModuleName, HLDS25, HLDS50,
+		DeepProfilingStructures, !IO),
+	globals__io_lookup_bool_option(highlevel_code, HighLevelCode, !IO),
+	globals__io_lookup_bool_option(aditi_only, AditiOnly, !IO),
+	globals__io_get_target(Target, !IO),
+	globals__io_lookup_bool_option(target_code_only, TargetCodeOnly, !IO),
+
+	%
+	% Remove any existing `.used' file before writing the
+	% output file file. This avoids leaving the old `used'
+	% file lying around if compilation is interrupted after
+	% the new output file is written but before the new
+	% `.used' file is written.
+	%
+	module_name_to_file_name(ModuleName, ".used", no, UsageFileName, !IO),
+	io__remove_file(UsageFileName, _, !IO),
+
+	% magic sets can report errors.
+	module_info_num_errors(HLDS50, NumErrors),
+	( NumErrors = 0 ->
+		globals__io_lookup_bool_option(intermodule_analysis,
+			IntermodAnalysis, !IO),
+		( IntermodAnalysis = yes ->
+			module_info_analysis_info(HLDS50, AnalysisInfo),
 			analysis__write_analysis_files(
 				module_name_to_module_id(ModuleName),
-				AnalysisInfo)
-		    ;
-			[]
-		    ),
-
-		    mercury_compile__maybe_generate_rl_bytecode(HLDS50,
-				Verbose, MaybeRLFile),
-		    ( { Target = c ; Target = asm } ->
+				AnalysisInfo, !IO)
+		;
+			true
+		),
+		mercury_compile__maybe_generate_rl_bytecode(HLDS50,
+			Verbose, MaybeRLFile, !IO),
+		(
+			( Target = c
+			; Target = asm
+			)
+		->
 			%
 			% Produce the grade independent header file
 			% <module>.mh containing function prototypes
 			% for the `:- pragma export'ed procedures.
 			%
-		    	{ export__get_foreign_export_decls(HLDS50,
-				ExportDecls) },
-			export__produce_header_file(ExportDecls, ModuleName)
-		    ;
-		    	[]
-		    ),
-		    ( { AditiOnly = yes } ->
-		    	{ HLDS = HLDS50 }
-		    ; { Target = il } ->
-			{ HLDS = HLDS50 },
-			mercury_compile__mlds_backend(HLDS, MLDS),
-			( { TargetCodeOnly = yes } ->
-				mercury_compile__mlds_to_il_assembler(MLDS)
+			export__get_foreign_export_decls(HLDS50, ExportDecls),
+			export__produce_header_file(ExportDecls, ModuleName,
+				!IO)
+		;
+			true
+		),
+		( AditiOnly = yes ->
+			HLDS = HLDS50
+		; Target = il ->
+			HLDS = HLDS50,
+			mercury_compile__mlds_backend(HLDS, _, MLDS, !IO),
+			( TargetCodeOnly = yes ->
+				mercury_compile__mlds_to_il_assembler(MLDS,
+					!IO)
 			;
-				{ HasMain = mercury_compile__mlds_has_main(
-					MLDS) },
-				mercury_compile__mlds_to_il_assembler(MLDS),
-				io__output_stream(OutputStream),
+				HasMain = mercury_compile__mlds_has_main(
+					MLDS),
+				mercury_compile__mlds_to_il_assembler(MLDS,
+					!IO),
+				io__output_stream(OutputStream, !IO),
 				compile_target_code__il_assemble(OutputStream,
-					ModuleName, HasMain, Succeeded),
-				maybe_set_exit_status(Succeeded)
+					ModuleName, HasMain, Succeeded, !IO),
+				maybe_set_exit_status(Succeeded, !IO)
 			)
-		    ; { Target = java } ->
-			{ HLDS = HLDS50 },
-			mercury_compile__mlds_backend(HLDS, MLDS),
-			mercury_compile__mlds_to_java(MLDS),
-			( { TargetCodeOnly = yes } ->
-				[]
+		; Target = java ->
+			HLDS = HLDS50,
+			mercury_compile__mlds_backend(HLDS, _, MLDS, !IO),
+			mercury_compile__mlds_to_java(MLDS, !IO),
+			( TargetCodeOnly = yes ->
+				true
 			;
-				io__output_stream(OutputStream),
+				io__output_stream(OutputStream, !IO),
 				module_name_to_file_name(ModuleName,
-					".java", no, JavaFile),
+					".java", no, JavaFile, !IO),
 				compile_target_code__compile_java_file(
-					OutputStream, JavaFile, Succeeded),
-				maybe_set_exit_status(Succeeded)
+					OutputStream, JavaFile, Succeeded, !IO),
+				maybe_set_exit_status(Succeeded, !IO)
 			)
-		    ; { Target = asm } ->
-		    	% compile directly to assembler using the gcc back-end
-			{ HLDS = HLDS50 },
-			mercury_compile__mlds_backend(HLDS, MLDS),
+		; Target = asm ->
+			% compile directly to assembler using the gcc back-end
+			HLDS = HLDS50,
+			mercury_compile__mlds_backend(HLDS, _, MLDS, !IO),
 			mercury_compile__maybe_mlds_to_gcc(MLDS,
-				MaybeRLFile, ContainsCCode),
-			( { TargetCodeOnly = yes } ->
-				[]
+				MaybeRLFile, ContainsCCode, !IO),
+			( TargetCodeOnly = yes ->
+				true
 			;
 				% We don't invoke the assembler to produce an
 				% object file yet -- that is done at
@@ -1419,93 +1514,79 @@
 				% separate C file.  We need to invoke the
 				% C compiler on that.
 				%
-				( { ContainsCCode = yes } ->
-					get_linked_target_type(TargetType),
-					get_object_code_type(TargetType, PIC),
-					maybe_pic_object_file_extension(PIC,
-						Obj),
-					module_name_to_file_name(ModuleName,
-						".c", no, CCode_C_File),
-					{ ForeignModuleName =
-						foreign_language_module_name(
-							ModuleName, c) },
-					module_name_to_file_name(
-						ForeignModuleName, Obj,
-						yes, CCode_O_File),
-					io__output_stream(OutputStream),
-					compile_target_code__compile_c_file(
-						OutputStream, PIC,
-						CCode_C_File, CCode_O_File,
-						CompileOK),
-					maybe_set_exit_status(CompileOK),
-					% add this object file to the list
-					% of extra object files to link in
-					globals__io_lookup_accumulating_option(
-						link_objects, LinkObjects),
-					globals__io_set_option(link_objects,
-						accumulating([CCode_O_File |
-						LinkObjects]))
+				( ContainsCCode = yes ->
+					mercury_compile_asm_c_code(ModuleName,
+						!IO)
 				;
-					[]
+					true
 				)
 			)
-		    ; { HighLevelCode = yes } ->
-			{ HLDS = HLDS50 },
-			mercury_compile__mlds_backend(HLDS, MLDS),
+		; HighLevelCode = yes ->
+			HLDS = HLDS50,
+			mercury_compile__mlds_backend(HLDS, _, MLDS, !IO),
 			mercury_compile__mlds_to_high_level_c(MLDS,
-				MaybeRLFile),
-			( { TargetCodeOnly = yes } ->
-				[]
+				MaybeRLFile, !IO),
+			( TargetCodeOnly = yes ->
+				true
 			;
 				module_name_to_file_name(ModuleName, ".c", no,
-					C_File),
-				get_linked_target_type(TargetType),
-				get_object_code_type(TargetType, PIC),
-				maybe_pic_object_file_extension(PIC, Obj),
+					C_File, !IO),
+				get_linked_target_type(TargetType, !IO),
+				get_object_code_type(TargetType, PIC, !IO),
+				maybe_pic_object_file_extension(PIC, Obj, !IO),
 				module_name_to_file_name(ModuleName, Obj, yes,
-					O_File),
-				io__output_stream(OutputStream),
+					O_File, !IO),
+				io__output_stream(OutputStream, !IO),
 				compile_target_code__compile_c_file(
 					OutputStream, PIC, C_File, O_File,
-					CompileOK),
-				maybe_set_exit_status(CompileOK)
+					CompileOK, !IO),
+				maybe_set_exit_status(CompileOK, !IO)
 			)
-		    ;
+		;
 			mercury_compile__backend_pass(HLDS50, HLDS,
-				DeepProfilingStructures, GlobalData, LLDS),
+				DeepProfilingStructures, GlobalData, LLDS,
+				!IO),
 			mercury_compile__output_pass(HLDS, GlobalData, LLDS,
-				MaybeRLFile, ModuleName, _CompileErrors)
-		    ),
-		    recompilation__usage__write_usage_file(HLDS,
-		    	NestedSubModules, MaybeTimestamps),
-		    FindTimestampFiles(ModuleName, TimestampFiles),
-		    list__foldl(touch_datestamp, TimestampFiles)
-		;
-		    	% If the number of errors is > 0, make sure that
-			% the compiler exits with a non-zero exit
-			% status.
-		    io__get_exit_status(ExitStatus),
-		    ( { ExitStatus = 0 } ->
-		    	io__set_exit_status(1)
-		    ;
-		    	[]
-		    )
+				MaybeRLFile, ModuleName, _CompileErrors, !IO)
+		),
+		recompilation__usage__write_usage_file(HLDS,
+			NestedSubModules, MaybeTimestamps, !IO),
+		FindTimestampFiles(ModuleName, TimestampFiles, !IO),
+		list__foldl(touch_datestamp, TimestampFiles, !IO)
+	;
+		% If the number of errors is > 0, make sure that the compiler
+		% exits with a non-zero exit status.
+		io__get_exit_status(ExitStatus, !IO),
+		( ExitStatus = 0 ->
+			io__set_exit_status(1, !IO)
+			;
+			true
 		)
-	    )
-	;
-	    	% If the number of errors is > 0, make sure that
-		% the compiler exits with a non-zero exit
-		% status.
-	    io__get_exit_status(ExitStatus),
-	    ( { ExitStatus = 0 } ->
-	    	io__set_exit_status(1)
-	    ;
-	    	[]
-	    )
 	).
 
+:- pred mercury_compile_asm_c_code(module_name::in, io::di, io::uo) is det.
+
+mercury_compile_asm_c_code(ModuleName, !IO) :-
+	get_linked_target_type(TargetType, !IO),
+	get_object_code_type(TargetType, PIC, !IO),
+	maybe_pic_object_file_extension(PIC, Obj, !IO),
+	module_name_to_file_name(ModuleName, ".c", no, CCode_C_File, !IO),
+	ForeignModuleName = foreign_language_module_name(ModuleName, c),
+	module_name_to_file_name(ForeignModuleName, Obj, yes, CCode_O_File,
+		!IO),
+	io__output_stream(OutputStream, !IO),
+	compile_target_code__compile_c_file(OutputStream, PIC,
+		CCode_C_File, CCode_O_File, CompileOK, !IO),
+	maybe_set_exit_status(CompileOK, !IO),
+	% add this object file to the list
+	% of extra object files to link in
+	globals__io_lookup_accumulating_option(link_objects, LinkObjects, !IO),
+	globals__io_set_option(link_objects,
+		accumulating([CCode_O_File | LinkObjects]), !IO).
+
 	% return `yes' iff this module defines the main/2 entry point.
 :- func mercury_compile__mlds_has_main(mlds) = has_main.
+
 mercury_compile__mlds_has_main(MLDS) =
 	(
 		MLDS = mlds(_, _, _, Defns),
@@ -1516,591 +1597,589 @@
 		no_main
 	).
 
-:- pred get_linked_target_type(linked_target_type, io__state, io__state).
-:- mode get_linked_target_type(out, di, uo) is det.
+:- pred get_linked_target_type(linked_target_type::out, io::di, io::uo) is det.
 
-get_linked_target_type(LinkedTargetType) -->
-	globals__io_lookup_bool_option(compile_to_shared_lib, MakeSharedLib),
-	{ LinkedTargetType =
-		( MakeSharedLib = yes -> shared_library ; executable ) }.
+get_linked_target_type(LinkedTargetType, !IO) :-
+	globals__io_lookup_bool_option(compile_to_shared_lib, MakeSharedLib,
+		!IO),
+	( MakeSharedLib = yes ->
+		LinkedTargetType = shared_library
+	;
+		LinkedTargetType = executable
+	).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__pre_hlds_pass(module_imports, bool,
-		module_info, qual_info, maybe(module_timestamps),
-		bool, bool, bool, io__state, io__state).
-:- mode mercury_compile__pre_hlds_pass(in, in, out, out, out, out, out, out,
-		di, uo) is det.
-
-mercury_compile__pre_hlds_pass(ModuleImports0, DontWriteDFile0,
-		HLDS1, QualInfo, MaybeTimestamps,
-		UndefTypes, UndefModes, FoundError) -->
-	globals__io_lookup_bool_option(statistics, Stats),
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(invoked_by_mmc_make, MMCMake),
-	{ DontWriteDFile1 = DontWriteDFile0 `or` MMCMake },
+:- pred mercury_compile__pre_hlds_pass(module_imports::in, bool::in,
+	module_info::out, qual_info::out, maybe(module_timestamps)::out,
+	bool::out, bool::out, bool::out, io::di, io::uo) is det.
+
+mercury_compile__pre_hlds_pass(ModuleImports0, DontWriteDFile0, HLDS1,
+		QualInfo, MaybeTimestamps, UndefTypes, UndefModes, FoundError,
+		!IO) :-
+	globals__io_get_globals(Globals, !IO),
+	globals__lookup_bool_option(Globals, statistics, Stats),
+	globals__lookup_bool_option(Globals, verbose, Verbose),
+	globals__lookup_bool_option(Globals, invoked_by_mmc_make, MMCMake),
+	DontWriteDFile1 = DontWriteDFile0 `or` MMCMake,
 
 	% Don't write the `.d' file when making the `.opt' file because
 	% we can't work out the full transitive implementation dependencies.
-	globals__io_lookup_bool_option(make_optimization_interface,
+	globals__lookup_bool_option(Globals, make_optimization_interface,
 		MakeOptInt),
-	{ DontWriteDFile = DontWriteDFile1 `or` MakeOptInt },
+	DontWriteDFile = DontWriteDFile1 `or` MakeOptInt,
 
-	{ module_imports_get_module_name(ModuleImports0, Module) },
+	module_imports_get_module_name(ModuleImports0, Module),
 
-	( { DontWriteDFile = yes } ->
+	( DontWriteDFile = yes ->
 		% The only time the TransOptDeps are required is when
 		% creating the .trans_opt file.  If DontWriteDFile is yes,
 		% then error check only or type-check only is enabled, so
 		% we cant be creating the .trans_opt file.
-		{ MaybeTransOptDeps = no }
+		MaybeTransOptDeps = no
 	;
-		maybe_read_dependency_file(Module, MaybeTransOptDeps)
+		maybe_read_dependency_file(Module, MaybeTransOptDeps, !IO)
 	),
 
 	% Errors in .opt and .trans_opt files result in software errors.
 	mercury_compile__maybe_grab_optfiles(ModuleImports0, Verbose,
-		MaybeTransOptDeps, ModuleImports1, IntermodError),
+		MaybeTransOptDeps, ModuleImports1, IntermodError, !IO),
 
-	{ module_imports_get_items(ModuleImports1, Items1) },
-	{ MaybeTimestamps = ModuleImports1 ^ maybe_timestamps },
+	module_imports_get_items(ModuleImports1, Items1),
+	MaybeTimestamps = ModuleImports1 ^ maybe_timestamps,
 
 	mercury_compile__module_qualify_items(Items1, Items2, Module, Verbose,
-				Stats, MQInfo0, _, UndefTypes0, UndefModes0),
+		Stats, MQInfo0, _, UndefTypes0, UndefModes0, !IO),
 
-	{ mq_info_get_recompilation_info(MQInfo0, RecompInfo0) },
+	mq_info_get_recompilation_info(MQInfo0, RecompInfo0),
 	mercury_compile__expand_equiv_types(Module, Items2, Verbose, Stats,
-				Items, CircularTypes, EqvMap,
-				RecompInfo0, RecompInfo),
-	{ mq_info_set_recompilation_info(MQInfo0, RecompInfo, MQInfo) }, 
-	{ bool__or(UndefTypes0, CircularTypes, UndefTypes1) },
+		Items, CircularTypes, EqvMap, RecompInfo0, RecompInfo, !IO),
+	mq_info_set_recompilation_info(MQInfo0, RecompInfo, MQInfo),
+	bool__or(UndefTypes0, CircularTypes, UndefTypes1),
 
-	mercury_compile__make_hlds(Module, Items, MQInfo, EqvMap, Verbose, 
-			Stats, HLDS0, QualInfo,
-			UndefTypes2, UndefModes2, FoundError),
+	mercury_compile__make_hlds(Module, Items, MQInfo, EqvMap,
+		Verbose, Stats, HLDS0, QualInfo, UndefTypes2, UndefModes2,
+		FoundError, !IO),
 
-	{ bool__or(UndefTypes1, UndefTypes2, UndefTypes) },
-	{ bool__or(UndefModes0, UndefModes2, UndefModes) },
+	bool__or(UndefTypes1, UndefTypes2, UndefTypes),
+	bool__or(UndefModes0, UndefModes2, UndefModes),
 
-	mercury_compile__maybe_dump_hlds(HLDS0, "01", "initial"),
+	mercury_compile__maybe_dump_hlds(HLDS0, "01", "initial", !IO),
 
-	( { DontWriteDFile = yes } ->
-		[]
+	( DontWriteDFile = yes ->
+		true
 	;
-		{ module_info_get_all_deps(HLDS0, AllDeps) },
+		module_info_get_all_deps(HLDS0, AllDeps),
 		write_dependency_file(ModuleImports0, AllDeps,
-			MaybeTransOptDeps),
-		globals__io_lookup_bool_option(
+			MaybeTransOptDeps, !IO),
+		globals__lookup_bool_option(Globals,
 			generate_mmc_make_module_dependencies,
 			OutputMMCMakeDeps),
-		( { OutputMMCMakeDeps = yes } ->
-			make__write_module_dep_file(ModuleImports0)
+		( OutputMMCMakeDeps = yes ->
+			make__write_module_dep_file(ModuleImports0, !IO)
 		;
-			[]
+			true
 		)
 	),
 
 	% Only stop on syntax errors in .opt files.
-	( { FoundError = yes ; IntermodError = yes } ->
-		{ module_info_incr_errors(HLDS0, HLDS1) }
-	;	
-		{ HLDS1 = HLDS0 }
-	).
-
-:- pred mercury_compile__module_qualify_items(item_list, item_list,
-		module_name, bool, bool, mq_info, int, bool, bool,
-		io__state, io__state).
-:- mode mercury_compile__module_qualify_items(in, out, in, in, in, out, out,
-		out, out, di, uo) is det. 
-
-mercury_compile__module_qualify_items(Items0, Items, ModuleName, Verbose, 
-			Stats, MQInfo, NumErrors, UndefTypes, UndefModes) -->
-	maybe_write_string(Verbose, "% Module qualifying items...\n"),
-	maybe_flush_output(Verbose),
+	(
+		( FoundError = yes
+		; IntermodError = yes
+		)
+	->
+		module_info_incr_errors(HLDS0, HLDS1)
+	;
+		HLDS1 = HLDS0
+	).
+
+:- pred mercury_compile__module_qualify_items(item_list::in, item_list::out,
+	module_name::in, bool::in, bool::in, mq_info::out, int::out,
+	bool::out, bool::out, io::di, io::uo) is det.
+
+mercury_compile__module_qualify_items(Items0, Items, ModuleName,
+		Verbose, Stats, MQInfo, NumErrors, UndefTypes, UndefModes,
+		!IO) :-
+	maybe_write_string(Verbose, "% Module qualifying items...\n", !IO),
+	maybe_flush_output(Verbose, !IO),
 	module_qual__module_qualify_items(Items0, Items, ModuleName, yes,
-				MQInfo, NumErrors, UndefTypes, UndefModes),
-	maybe_write_string(Verbose, "% done.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__maybe_grab_optfiles(module_imports, bool,
-	 maybe(list(module_name)), module_imports, bool, io__state, io__state).
-:- mode mercury_compile__maybe_grab_optfiles(in, in, in, out, out, 
-	di, uo) is det.
-
-mercury_compile__maybe_grab_optfiles(Imports0, Verbose, MaybeTransOptDeps, 
-		Imports, Error) -->
-	globals__io_lookup_bool_option(intermodule_optimization, IntermodOpt),
-	globals__io_lookup_bool_option(use_opt_files, UseOptInt),
-	globals__io_lookup_bool_option(make_optimization_interface,
-						MakeOptInt),
-	globals__io_lookup_bool_option(transitive_optimization, TransOpt),
-	globals__io_lookup_bool_option(make_transitive_opt_interface,
+		MQInfo, NumErrors, UndefTypes, UndefModes, !IO),
+	maybe_write_string(Verbose, "% done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__maybe_grab_optfiles(module_imports::in, bool::in,
+	maybe(list(module_name))::in, module_imports::out, bool::out,
+	io::di, io::uo) is det.
+
+mercury_compile__maybe_grab_optfiles(Imports0, Verbose, MaybeTransOptDeps,
+		Imports, Error, !IO) :-
+	globals__io_get_globals(Globals, !IO),
+	globals__lookup_bool_option(Globals, intermodule_optimization,
+		IntermodOpt),
+	globals__lookup_bool_option(Globals, use_opt_files, UseOptInt),
+	globals__lookup_bool_option(Globals, make_optimization_interface,
+		MakeOptInt),
+	globals__lookup_bool_option(Globals, transitive_optimization,
+		TransOpt),
+	globals__lookup_bool_option(Globals, make_transitive_opt_interface,
 		MakeTransOptInt),
-	( { (UseOptInt = yes ; IntermodOpt = yes), MakeOptInt = no } ->
-		maybe_write_string(Verbose, "% Reading .opt files...\n"),
-		maybe_flush_output(Verbose),
-		intermod__grab_optfiles(Imports0, Imports1, Error1),
-		maybe_write_string(Verbose, "% Done.\n")
+	(
+		( UseOptInt = yes
+		; IntermodOpt = yes
+		),
+		MakeOptInt = no
+	->
+		maybe_write_string(Verbose, "% Reading .opt files...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		intermod__grab_optfiles(Imports0, Imports1, Error1, !IO),
+		maybe_write_string(Verbose, "% Done.\n", !IO)
 	;
-		{ Imports1 = Imports0 },
-		{ Error1 = no }
+		Imports1 = Imports0,
+		Error1 = no
 	),
-	( { MakeTransOptInt = yes } ->
-		( { MaybeTransOptDeps = yes(TransOptDeps) } ->
+	( MakeTransOptInt = yes ->
+		( MaybeTransOptDeps = yes(TransOptDeps) ->
 			% When creating the trans_opt file, only import the
 			% trans_opt files which are lower in the ordering.
-			trans_opt__grab_optfiles(Imports1, TransOptDeps, 
-				Imports, Error2)
+			trans_opt__grab_optfiles(Imports1, TransOptDeps,
+				Imports, Error2, !IO)
 		;
-			{ Imports = Imports1 },
-			{ Error2 = no },
-			{ module_imports_get_module_name(Imports,
-				ModuleName) },
-			globals__io_lookup_bool_option(
+			Imports = Imports1,
+			Error2 = no,
+			module_imports_get_module_name(Imports,
+				ModuleName),
+			globals__lookup_bool_option(Globals,
 				warn_missing_trans_opt_deps,
 				WarnNoTransOptDeps),
-			( { WarnNoTransOptDeps = yes } ->
-				{ prog_out__sym_name_to_string(ModuleName,
-					ModuleString) },
-				io__write_strings([
-				    "Warning: cannot read trans-opt ",
-				    "dependencies for module `",
-				    ModuleString, "'.\n",
-				    "  You need to remake ",
-				    "the dependencies.\n"]),
-				globals__io_lookup_bool_option(halt_at_warn,
-					Halt),
-				( { Halt = yes } ->
-					io__set_exit_status(1)
+			( WarnNoTransOptDeps = yes ->
+				prog_out__sym_name_to_string(ModuleName,
+					ModuleString),
+				Msg1 = "Warning: cannot read trans-opt " ++
+					"dependencies for module `" ++
+					ModuleString ++ "'.",
+				Msg2 = "You need to remake " ++
+					"the dependencies.",
+				write_error_pieces_plain([words(Msg1), nl,
+					words(Msg2)], !IO),
+				globals__lookup_bool_option(Globals,
+					halt_at_warn, Halt),
+				( Halt = yes ->
+					io__set_exit_status(1, !IO)
 				;
-					[]
+					true
 				)
 			;
-				[]
+				true
 			)
 		)
-	; { MakeOptInt = yes } ->
+	; MakeOptInt = yes ->
 		% If we're making the `.opt' file, then we can't
-		% read any `.trans_opt' files, since `.opt' files 
+		% read any `.trans_opt' files, since `.opt' files
 		% aren't allowed to depend on `.trans_opt' files.
-		{ Imports = Imports1 },
-		{ Error2 = no }
+		Imports = Imports1,
+		Error2 = no
 	;
-		( { TransOpt = yes } ->
+		( TransOpt = yes ->
 			% If transitive optimization is enabled, but we are
 			% not creating the .opt or .trans opt file, then import
 			% the trans_opt files for all the modules that are
 			% imported (or used), and for all ancestor modules.
-			{ list__condense(
-				[Imports0 ^ parent_deps, Imports0 ^ int_deps,
-					Imports0 ^ impl_deps],
-				TransOptFiles) },
+			list__condense([Imports0 ^ parent_deps,
+				Imports0 ^ int_deps, Imports0 ^ impl_deps],
+				TransOptFiles),
 			trans_opt__grab_optfiles(Imports1, TransOptFiles,
-				Imports, Error2)
+				Imports, Error2, !IO)
 		;
-			{ Imports = Imports1 },
-			{ Error2 = no }
+			Imports = Imports1,
+			Error2 = no
 		)
 	),
+	bool__or(Error1, Error2, Error).
 
-	{ bool__or(Error1, Error2, Error) }.
-
-:- pred mercury_compile__expand_equiv_types(module_name, item_list,
-	bool, bool, item_list, bool, eqv_map, maybe(recompilation_info),
-	maybe(recompilation_info), io__state, io__state).
-:- mode mercury_compile__expand_equiv_types(in, in, in, in, out,
-	out, out, in, out, di, uo) is det.
+:- pred mercury_compile__expand_equiv_types(module_name::in, item_list::in,
+	bool::in, bool::in, item_list::out, bool::out, eqv_map::out,
+	maybe(recompilation_info)::in, maybe(recompilation_info)::out,
+	io::di, io::uo) is det.
 
 mercury_compile__expand_equiv_types(ModuleName, Items0, Verbose, Stats,
-		Items, CircularTypes, EqvMap, RecompInfo0, RecompInfo) -->
-	maybe_write_string(Verbose, "% Expanding equivalence types..."),
-	maybe_flush_output(Verbose),
+		Items, CircularTypes, EqvMap, RecompInfo0, RecompInfo, !IO) :-
+	maybe_write_string(Verbose, "% Expanding equivalence types...", !IO),
+	maybe_flush_output(Verbose, !IO),
 	equiv_type__expand_eqv_types(ModuleName, Items0, Items, CircularTypes,
-		EqvMap, RecompInfo0, RecompInfo),
-	maybe_write_string(Verbose, " done.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__make_hlds(module_name, item_list, mq_info, eqv_map, 
-	bool, bool, module_info, qual_info, bool, bool, bool,
-	io__state, io__state).
-:- mode mercury_compile__make_hlds(in, in, in, in, in, in,
-	out, out, out, out, out, di, uo) is det.
+		EqvMap, RecompInfo0, RecompInfo, !IO),
+	maybe_write_string(Verbose, " done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__make_hlds(module_name::in, item_list::in, mq_info::in,
+	eqv_map::in, bool::in, bool::in, module_info::out, qual_info::out,
+	bool::out, bool::out, bool::out, io::di, io::uo) is det.
 
 mercury_compile__make_hlds(Module, Items, MQInfo, EqvMap, Verbose, Stats,
-		HLDS, QualInfo, UndefTypes, UndefModes, FoundSemanticError) -->
-	maybe_write_string(Verbose, "% Converting parse tree to hlds...\n"),
-	{ Prog = module(Module, Items) },
+		HLDS, QualInfo, UndefTypes, UndefModes, FoundSemanticError,
+		!IO) :-
+	maybe_write_string(Verbose, "% Converting parse tree to hlds...\n",
+		!IO),
+	Prog = module(Module, Items),
 	parse_tree_to_hlds(Prog, MQInfo, EqvMap, HLDS, QualInfo,
-		UndefTypes, UndefModes),
-	{ module_info_num_errors(HLDS, NumErrors) },
-	io__get_exit_status(Status),
-	( { Status \= 0 ; NumErrors > 0 } ->
-		{ FoundSemanticError = yes },
-		io__set_exit_status(1)
+		UndefTypes, UndefModes, !IO),
+	module_info_num_errors(HLDS, NumErrors),
+	io__get_exit_status(Status, !IO),
+	(
+		( Status \= 0
+		; NumErrors > 0
+		)
+	->
+		FoundSemanticError = yes,
+		io__set_exit_status(1, !IO)
 	;
-		{ FoundSemanticError = no }
+		FoundSemanticError = no
 	),
-	maybe_write_string(Verbose, "% done.\n"),
-	maybe_report_stats(Stats).
+	maybe_write_string(Verbose, "% done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__frontend_pass(module_info, qual_info, bool, bool,
-		bool, module_info, bool, io__state, io__state).
-:- mode mercury_compile__frontend_pass(in, in, in, in, in, out, out, di, uo)
-	is det.
+:- pred mercury_compile__frontend_pass(qual_info::in, bool::in, bool::in,
+	bool::in, bool::out, module_info::in, module_info::out,
+	io::di, io::uo) is det.
 
-mercury_compile__frontend_pass(HLDS1, QualInfo0, FoundUndefTypeError,
-		FoundUndefModeError, FoundError0, HLDS, FoundError) -->
+mercury_compile__frontend_pass(QualInfo0, FoundUndefTypeError,
+		FoundUndefModeError, !FoundError, !HLDS, !IO) :-
 	%
 	% We can't continue after an undefined type error, since
 	% typecheck would get internal errors
 	%
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-	maybe_write_string(Verbose, "% Type-checking...\n"),
-	( { FoundUndefTypeError = yes } ->
-	    { HLDS = HLDS1 },
-	    { FoundError = yes },
-	    maybe_write_string(Verbose,
-		    "% Program contains undefined type error(s).\n"),
-	    io__set_exit_status(1)
-	;
-		
-	    maybe_write_string(Verbose, 
-		"% Checking typeclass instances...\n"),
-	    check_typeclass__check_instance_decls(HLDS1, QualInfo0, HLDS2,
-		QualInfo, FoundTypeclassError),
-	    mercury_compile__maybe_dump_hlds(HLDS2, "02", "typeclass"),
-	    { make_hlds__set_module_recompilation_info(QualInfo,
-	    	HLDS2, HLDS2a) },
-
-	    globals__io_lookup_bool_option(intermodule_optimization, Intermod),
-	    globals__io_lookup_bool_option(use_opt_files, UseOptFiles),
-	    globals__io_lookup_bool_option(make_optimization_interface,
+	globals__io_get_globals(Globals, !IO),
+	( FoundUndefTypeError = yes ->
+		!:FoundError = yes,
+		globals__lookup_bool_option(Globals, verbose, Verbose),
+		maybe_write_string(Verbose,
+			"% Program contains undefined type error(s).\n", !IO),
+		io__set_exit_status(1, !IO)
+	;
+		mercury_compile__frontend_pass_no_type_error(QualInfo0,
+			FoundUndefModeError, !FoundError, !HLDS, !IO)
+	).
+
+:- pred mercury_compile__frontend_pass_no_type_error(qual_info::in,
+	bool::in, bool::in, bool::out, module_info::in, module_info::out,
+	io::di, io::uo) is det.
+
+mercury_compile__frontend_pass_no_type_error(QualInfo0,
+		FoundUndefModeError, !FoundError, !HLDS, !IO) :-
+	globals__io_get_globals(Globals, !IO),
+	globals__lookup_bool_option(Globals, verbose, Verbose),
+	globals__lookup_bool_option(Globals, statistics, Stats),
+	maybe_write_string(Verbose,
+		"% Checking typeclass instances...\n", !IO),
+	check_typeclass__check_instance_decls(QualInfo0, QualInfo, !HLDS,
+		FoundTypeclassError, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "02", "typeclass", !IO),
+	make_hlds__set_module_recompilation_info(QualInfo, !HLDS),
+
+	globals__lookup_bool_option(Globals, intermodule_optimization,
+		Intermod),
+	globals__lookup_bool_option(Globals, use_opt_files, UseOptFiles),
+	globals__lookup_bool_option(Globals, make_optimization_interface,
 		MakeOptInt),
-	    ( { (Intermod = yes; UseOptFiles = yes), MakeOptInt = no } ->
+	(
+		( Intermod = yes
+		; UseOptFiles = yes
+		),
+		MakeOptInt = no
+	->
 		% Eliminate unnecessary clauses from `.opt' files,
 		% to speed up compilation. This must be done after
 		% typeclass instances have been checked, since that
 		% fills in which pred_ids are needed by instance decls.
 		maybe_write_string(Verbose,
-			"% Eliminating dead predicates... "),
-		{ dead_pred_elim(HLDS2a, HLDS2b) },
-		maybe_write_string(Verbose, "done.\n"),
-		mercury_compile__maybe_dump_hlds(HLDS2b, "02b",
-				"dead_pred_elim")
-	    ;
-		{ HLDS2b = HLDS2a }
-	    ),
-
-	    %
-	    % Next typecheck the clauses.
-	    %
-	    typecheck(HLDS2b, HLDS3, FoundTypeError,
-	    		ExceededTypeCheckIterationLimit),
-	    ( { FoundTypeError = yes } ->
-		maybe_write_string(Verbose,
-			"% Program contains type error(s).\n"),
-		io__set_exit_status(1)
-	    ;
-		maybe_write_string(Verbose, "% Program is type-correct.\n")
-	    ),
-	    mercury_compile__maybe_dump_hlds(HLDS3, "03", "typecheck"),
-
-	    %
-	    % We can't continue after an undefined inst/mode
-	    % error, since propagate_types_into_proc_modes
-	    % (in post_typecheck.m -- called by purity.m)
-	    % and mode analysis would get internal errors.
-	    % Also mode analysis can loop if there are cyclic insts/modes.
-	    %
-	    % We can't continue if the type inference iteration
-	    % limit was exceeeded because the code to resolve
-	    % overloading in post_typecheck.m (called by purity.m)
-	    % could abort.
-	    ( { FoundUndefModeError = yes } ->
-		{ FoundError = yes },
-		{ HLDS = HLDS3 },
-		maybe_write_string(Verbose,
-	"% Program contains undefined inst or undefined mode error(s).\n"),
-		io__set_exit_status(1)
-	    ; { ExceededTypeCheckIterationLimit = yes } ->
+			"% Eliminating dead predicates... ", !IO),
+		dead_pred_elim(!HLDS),
+		maybe_write_string(Verbose, "done.\n", !IO),
+		mercury_compile__maybe_dump_hlds(!.HLDS, "02b",
+			"dead_pred_elim", !IO)
+	;
+		true
+	),
+
+	%
+	% Next typecheck the clauses.
+	%
+	maybe_write_string(Verbose,
+		"% Type-checking...\n", !IO),
+	typecheck(!HLDS, FoundTypeError, ExceededTypeCheckIterationLimit, !IO),
+	( FoundTypeError = yes ->
+		maybe_write_string(Verbose,
+			"% Program contains type error(s).\n", !IO),
+		io__set_exit_status(1, !IO)
+	;
+		maybe_write_string(Verbose,
+			"% Program is type-correct.\n", !IO)
+	),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "03", "typecheck", !IO),
+
+	%
+	% We can't continue after an undefined inst/mode
+	% error, since propagate_types_into_proc_modes
+	% (in post_typecheck.m -- called by purity.m)
+	% and mode analysis would get internal errors.
+	% Also mode analysis can loop if there are cyclic insts/modes.
+	%
+	% We can't continue if the type inference iteration
+	% limit was exceeeded because the code to resolve
+	% overloading in post_typecheck.m (called by purity.m)
+	% could abort.
+	( FoundUndefModeError = yes ->
+		!:FoundError = yes,
+		maybe_write_string(Verbose,
+			"% Program contains undefined inst " ++
+			"or undefined mode error(s).\n", !IO),
+		io__set_exit_status(1, !IO)
+	; ExceededTypeCheckIterationLimit = yes ->
 		% FoundTypeError will always be true here, so we've already
 		% printed a message about the program containing type errors.
-		{ FoundError = yes },
-		{ HLDS = HLDS3 },
-		io__set_exit_status(1)
-	    ;
-	        %
-	        % Run purity checking
-	        %
-		mercury_compile__puritycheck(FoundTypeError, HLDS3,
-			Verbose, Stats, HLDS4, FoundPostTypecheckError),
-		mercury_compile__maybe_dump_hlds(HLDS4, "04", "puritycheck"),
-
-	        %
-	        % Stop here if `--typecheck-only' was specified.
-	        %
-	        globals__io_lookup_bool_option(typecheck_only, TypecheckOnly),
-	        ( { TypecheckOnly = yes } ->
-		    { HLDS = HLDS4 },
-		    { bool__or(FoundTypeError, FoundTypeclassError,
-		    	FoundError) }
-	        ; 
-		    { FoundTypeError = yes
-		    ; FoundPostTypecheckError = yes 
-		    ; FoundTypeclassError = yes
-		    } 
+		!:FoundError = yes,
+		io__set_exit_status(1, !IO)
+	;
+		%
+		% Run purity checking
+		%
+		mercury_compile__puritycheck(Verbose, Stats, !HLDS,
+			FoundTypeError, FoundPostTypecheckError, !IO),
+		mercury_compile__maybe_dump_hlds(!.HLDS, "04", "puritycheck",
+			!IO),
+
+		%
+		% Stop here if `--typecheck-only' was specified.
+		%
+		globals__lookup_bool_option(Globals, typecheck_only,
+			TypecheckOnly),
+		( TypecheckOnly = yes ->
+			bool__or(FoundTypeError, FoundTypeclassError,
+				!:FoundError)
+		;
+			( FoundTypeError = yes
+			; FoundPostTypecheckError = yes
+			; FoundTypeclassError = yes
+			)
 		->
-		    %
-		    % XXX it would be nice if we could go on and mode-check
-		    % the predicates which didn't have type errors, but
-		    % we need to run polymorphism before running mode
-		    % analysis, and currently polymorphism may get internal
-		    % errors if any of the predicates are not type-correct.
-		    %
-		    { HLDS = HLDS4 },
-		    { FoundError = yes }
-		;
-		    % only write out the `.opt' file if there are no errors
-		    (
-		            { FoundError0 = no },
-			    { FoundUndefModeError = no }
-		    ->
-			    mercury_compile__maybe_write_optfile(MakeOptInt,
-		    		    HLDS4, HLDS5)
-		    ;
-			    { HLDS5 = HLDS4 }
-		    ),
-		    % if our job was to write out the `.opt' file,
-		    % then we're done
-		    ( { MakeOptInt = yes } ->
-		    	    { HLDS = HLDS5 },
-			    { bool__or(FoundTypeError, FoundTypeclassError,
-				    FoundError) }
-		    ;
-			    %
-			    % Now go ahead and do the rest of mode checking and
-			    % determinism analysis
-			    %
-			    mercury_compile__frontend_pass_2_by_phases(HLDS5,
-			    		HLDS, FoundModeOrDetError),
-			    { FoundError = FoundTypeError
-			    			`or` FoundModeOrDetError
-						`or` FoundTypeclassError }
-		    )
+			%
+			% XXX it would be nice if we could go on and mode-check
+			% the predicates which didn't have type errors, but
+			% we need to run polymorphism before running mode
+			% analysis, and currently polymorphism may get internal
+			% errors if any of the predicates are not type-correct.
+			%
+			!:FoundError = yes
+		;
+			% only write out the `.opt' file if there are no errors
+			(
+				!.FoundError = no,
+				FoundUndefModeError = no
+			->
+				mercury_compile__maybe_write_optfile(
+					MakeOptInt, !HLDS, !IO)
+			;
+				true
+			),
+			% if our job was to write out the `.opt' file,
+			% then we're done
+			( MakeOptInt = yes ->
+				bool__or(FoundTypeError, FoundTypeclassError,
+					!:FoundError)
+			;
+				%
+				% Now go ahead and do the rest of mode checking
+				% and determinism analysis
+				%
+				mercury_compile__frontend_pass_by_phases(!HLDS,
+					FoundModeOrDetError, !IO),
+				!:FoundError = FoundTypeError
+					`or` FoundModeOrDetError
+					`or` FoundTypeclassError
+			)
 		)
-	    )
 	).
 
 :- pred mercury_compile__maybe_write_optfile(bool::in, module_info::in,
-		module_info::out, io__state::di, io__state::uo) is det.
+	module_info::out, io__state::di, io__state::uo) is det.
 
-mercury_compile__maybe_write_optfile(MakeOptInt, HLDS0, HLDS) -->
-	globals__io_lookup_bool_option(intermodule_optimization, Intermod),
-	globals__io_lookup_bool_option(intermod_unused_args, IntermodArgs),
-	globals__io_lookup_accumulating_option(intermod_directories,
+mercury_compile__maybe_write_optfile(MakeOptInt, !HLDS, !IO) :-
+	globals__io_get_globals(Globals, !IO),
+	globals__lookup_bool_option(Globals, intermodule_optimization,
+		Intermod),
+	globals__lookup_bool_option(Globals, intermod_unused_args,
+		IntermodArgs),
+	globals__lookup_accumulating_option(Globals, intermod_directories,
 		IntermodDirs),
-	globals__io_lookup_bool_option(use_opt_files, UseOptFiles),
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-	globals__io_lookup_bool_option(termination, Termination),
+	globals__lookup_bool_option(Globals, use_opt_files, UseOptFiles),
+	globals__lookup_bool_option(Globals, verbose, Verbose),
+	globals__lookup_bool_option(Globals, statistics, Stats),
+	globals__lookup_bool_option(Globals, termination, Termination),
 
-	( { MakeOptInt = yes } ->
-		intermod__write_optfile(HLDS0, HLDS1),
+	( MakeOptInt = yes ->
+		intermod__write_optfile(!HLDS, !IO),
 
 		% If intermod_unused_args is being performed, run polymorphism,
 		% mode analysis and determinism analysis, then run unused_args
-		% to append the unused argument information to the `.opt.tmp' 
+		% to append the unused argument information to the `.opt.tmp'
 		% file written above.
-		( { IntermodArgs = yes ; Termination = yes } ->
-			mercury_compile__frontend_pass_2_by_phases(
-				HLDS1, HLDS2, FoundModeError),
-			( { FoundModeError = no } ->
-				( { IntermodArgs = yes } ->
+		(
+			( IntermodArgs = yes
+			; Termination = yes
+			)
+		->
+			mercury_compile__frontend_pass_by_phases(!HLDS,
+				FoundModeError, !IO),
+			( FoundModeError = no ->
+				( IntermodArgs = yes ->
 					mercury_compile__maybe_unused_args(
-						HLDS2, Verbose, Stats, HLDS3)
+						Verbose, Stats, !HLDS, !IO)
 				;
-					{ HLDS3 = HLDS2 }
+					true
 				),
-				( { Termination = yes } ->
+				( Termination = yes ->
 					mercury_compile__maybe_termination(
-						HLDS3, Verbose, Stats, HLDS)
+						Verbose, Stats, !HLDS, !IO)
 				;
-					{ HLDS = HLDS3 }
+					true
 				)
-					
 			;
-				io__set_exit_status(1),
-				{ HLDS = HLDS2 }
+				io__set_exit_status(1, !IO)
 			)
 		;
-			{ HLDS = HLDS1 }
+			true
 		),
-		{ module_info_name(HLDS, ModuleName) },
-		module_name_to_file_name(ModuleName, ".opt", yes, OptName),
-		update_interface(OptName),
-		touch_interface_datestamp(ModuleName, ".optdate")
+		module_info_name(!.HLDS, ModuleName),
+		module_name_to_file_name(ModuleName, ".opt", yes, OptName, !IO),
+		update_interface(OptName, !IO),
+		touch_interface_datestamp(ModuleName, ".optdate", !IO)
 	;
 		% If there is a `.opt' file for this module the import
 		% status of items in the `.opt' file needs to be updated.
-		( { Intermod = yes } ->
-			{ UpdateStatus = yes }
-		; { UseOptFiles = yes } ->
-			{ module_info_name(HLDS0, ModuleName) },
+		( Intermod = yes ->
+			UpdateStatus = yes
+		; UseOptFiles = yes ->
+			module_info_name(!.HLDS, ModuleName),
 			module_name_to_search_file_name(ModuleName,
-				".opt", OptName),
-			search_for_file(IntermodDirs, OptName, Found),
-			( { Found = ok(_) } ->
-				{ UpdateStatus = yes },
-				io__seen
+				".opt", OptName, !IO),
+			search_for_file(IntermodDirs, OptName, Found, !IO),
+			( Found = ok(_) ->
+				UpdateStatus = yes,
+				io__seen(!IO)
 			;
-				{ UpdateStatus = no }
+				UpdateStatus = no
 			)
 		;
-			{ UpdateStatus = no }
-		),	
-		{ is_bool(UpdateStatus) },
-		( { UpdateStatus = yes } ->
-			intermod__adjust_pred_import_status(HLDS0, HLDS)
+			UpdateStatus = no
+		),
+		is_bool(UpdateStatus),
+		( UpdateStatus = yes ->
+			intermod__adjust_pred_import_status(!HLDS, !IO)
 		;
-			{ HLDS = HLDS0 }
+			true
 		)
 	).
 
 :- pred is_bool(bool::in) is det.
+
 is_bool(_).
 
-:- pred mercury_compile__output_trans_opt_file(module_info, 
-	io__state, io__state).
-:- mode mercury_compile__output_trans_opt_file(in, di, uo) is det.
-mercury_compile__output_trans_opt_file(HLDS25) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-
-	mercury_compile__maybe_termination(HLDS25, Verbose, Stats, HLDS28),
-	mercury_compile__maybe_dump_hlds(HLDS28, "28", "termination"),
-
-	trans_opt__write_optfile(HLDS28).
-	
-:- pred mercury_compile__frontend_pass_2(module_info, module_info,
-	bool, io__state, io__state).
-% :- mode mercury_compile__frontend_pass_2(di, uo, out, di, uo) is det.
-:- mode mercury_compile__frontend_pass_2(in, out, out, di, uo) is det.
+:- pred mercury_compile__output_trans_opt_file(module_info::in,
+	io::di, io::uo) is det.
 
-mercury_compile__frontend_pass_2(HLDS0, HLDS, FoundError) -->
-	globals__io_lookup_bool_option(trad_passes, TradPasses),
-	(
-		{ TradPasses = no },
-		mercury_compile__frontend_pass_2_by_phases(HLDS0, HLDS,
-			FoundError)
-	;
-		{ TradPasses = yes },
-		mercury_compile__frontend_pass_2_by_preds(HLDS0, HLDS,
-			FoundError)
-	).
-
-:- pred mercury_compile__frontend_pass_2_by_phases(module_info, module_info,
-	bool, io__state, io__state).
-% :- mode mercury_compile__frontend_pass_2_by_phases(di, uo, out, di, uo)
-% is det.
-:- mode mercury_compile__frontend_pass_2_by_phases(in, out, out, di, uo) is det.
-
-mercury_compile__frontend_pass_2_by_phases(HLDS4, HLDS20, FoundError) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-
-	mercury_compile__maybe_polymorphism(HLDS4, Verbose, Stats, HLDS5),
-	mercury_compile__maybe_dump_hlds(HLDS5, "05", "polymorphism"),
-
-	mercury_compile__modecheck(HLDS5, Verbose, Stats, HLDS6,
-		FoundModeError, UnsafeToContinue),
-	mercury_compile__maybe_dump_hlds(HLDS6, "06", "modecheck"),
-
-	( { UnsafeToContinue = yes } ->
-		{ FoundError = yes },
-		{ HLDS12 = HLDS6 }
-	;
-		mercury_compile__detect_switches(HLDS6, Verbose, Stats, HLDS7),
-		mercury_compile__maybe_dump_hlds(HLDS7, "07", "switch_detect"),
-
-		mercury_compile__detect_cse(HLDS7, Verbose, Stats, HLDS8),
-		mercury_compile__maybe_dump_hlds(HLDS8, "08", "cse"),
-
-		mercury_compile__check_determinism(HLDS8, Verbose, Stats, HLDS9,
-			FoundDetError),
-		mercury_compile__maybe_dump_hlds(HLDS9, "09", "determinism"),
-
-		mercury_compile__check_unique_modes(HLDS9, Verbose, Stats,
-			HLDS10, FoundUniqError),
-		mercury_compile__maybe_dump_hlds(HLDS10, "10", "unique_modes"),
-
-		mercury_compile__check_stratification(HLDS10, Verbose, Stats, 
-			HLDS11, FoundStratError),
-		mercury_compile__maybe_dump_hlds(HLDS11, "11",
-			"stratification"),
-
-		mercury_compile__simplify(HLDS11, yes, no, Verbose, Stats,
-			process_all_nonimported_procs, HLDS12),
-		mercury_compile__maybe_dump_hlds(HLDS12, "12", "simplify"),
+mercury_compile__output_trans_opt_file(HLDS25, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+	mercury_compile__maybe_termination(Verbose, Stats, HLDS25, HLDS28, !IO),
+	mercury_compile__maybe_dump_hlds(HLDS28, "28", "termination", !IO),
+	trans_opt__write_optfile(HLDS28, !IO).
+
+:- pred mercury_compile__frontend_pass_by_phases(module_info::in,
+	module_info::out, bool::out, io::di, io::uo) is det.
+
+mercury_compile__frontend_pass_by_phases(!HLDS, FoundError, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+
+	mercury_compile__maybe_polymorphism(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "05", "polymorphism", !IO),
+
+	mercury_compile__modecheck(Verbose, Stats, !HLDS,
+		FoundModeError, UnsafeToContinue, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "06", "modecheck", !IO),
+
+	( UnsafeToContinue = yes ->
+		FoundError = yes
+	;
+		mercury_compile__detect_switches(Verbose, Stats, !HLDS, !IO),
+		mercury_compile__maybe_dump_hlds(!.HLDS, "07",
+			"switch_detect", !IO),
+
+		mercury_compile__detect_cse(Verbose, Stats, !HLDS, !IO),
+		mercury_compile__maybe_dump_hlds(!.HLDS, "08", "cse", !IO),
+
+		mercury_compile__check_determinism(Verbose, Stats, !HLDS,
+			FoundDetError, !IO),
+		mercury_compile__maybe_dump_hlds(!.HLDS, "09", "determinism",
+			!IO),
+
+		mercury_compile__check_unique_modes(Verbose, Stats, !HLDS,
+			FoundUniqError, !IO),
+		mercury_compile__maybe_dump_hlds(!.HLDS, "10", "unique_modes",
+			!IO),
+
+		mercury_compile__check_stratification(Verbose, Stats, !HLDS,
+			FoundStratError, !IO),
+		mercury_compile__maybe_dump_hlds(!.HLDS, "11",
+			"stratification", !IO),
+
+		mercury_compile__simplify(yes, no, Verbose, Stats,
+			process_all_nonimported_procs, !HLDS, !IO),
+		mercury_compile__maybe_dump_hlds(!.HLDS, "12", "simplify",
+			!IO),
 
 		%
 		% work out whether we encountered any errors
 		%
-		io__get_exit_status(ExitStatus),
+		io__get_exit_status(ExitStatus, !IO),
 		(
-			{ FoundModeError = no },
-			{ FoundDetError = no },
-			{ FoundUniqError = no },
-			{ FoundStratError = no },
+			FoundModeError = no,
+			FoundDetError = no,
+			FoundUniqError = no,
+			FoundStratError = no,
 			% Strictly speaking, we shouldn't need to check
 			% the exit status.  But the values returned for
 			% FoundModeError etc. aren't always correct.
-			{ ExitStatus = 0 }
+			ExitStatus = 0
 		->
-			{ FoundError = no }
+			FoundError = no
 		;
-			{ FoundError = yes }
+			FoundError = yes
 		)
 	),
-
-	{ HLDS20 = HLDS12 },
-	mercury_compile__maybe_dump_hlds(HLDS20, "20", "front_end").
-
-:- pred mercury_compile__frontend_pass_2_by_preds(module_info, module_info,
-	bool, io__state, io__state).
-% :- mode mercury_compile__frontend_pass_2_by_preds(di, uo, out, di, uo)
-%	is det.
-:- mode mercury_compile__frontend_pass_2_by_preds(in, out, out, di, uo)
-	is det.
-
-mercury_compile__frontend_pass_2_by_preds(HLDS0, HLDS, FoundError) -->
-	mercury_compile__frontend_pass_2_by_phases(HLDS0, HLDS, FoundError).
+	mercury_compile__maybe_dump_hlds(!.HLDS, "20", "front_end", !IO).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__middle_pass(module_name, module_info, module_info,
-	list(layout_data), io__state, io__state).
-% :- mode mercury_compile__middle_pass(in, di, uo, out, di, uo) is det.
-:- mode mercury_compile__middle_pass(in, in, out, out, di, uo) is det.
-
-mercury_compile__middle_pass(ModuleName, HLDS24, HLDS50,
-		DeepProfilingStructures) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
+:- pred mercury_compile__middle_pass(module_name::in, module_info::in,
+	module_info::out, list(layout_data)::out, io::di, io::uo) is det.
+
+mercury_compile__middle_pass(ModuleName, !HLDS, DeepProfilingStructs, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
 
-	mercury_compile__tabling(HLDS24, Verbose, HLDS25),
-	mercury_compile__maybe_dump_hlds(HLDS25, "25", "tabling"),
+	mercury_compile__tabling(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "25", "tabling", !IO),
 
-	mercury_compile__process_lambdas(HLDS25, Verbose, HLDS26),
-	mercury_compile__maybe_dump_hlds(HLDS26, "26", "lambda"),
+	mercury_compile__process_lambdas(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "26", "lambda", !IO),
 
-	mercury_compile__expand_equiv_types_hlds(HLDS26, Verbose, HLDS27),
-	mercury_compile__maybe_dump_hlds(HLDS26, "27", "equiv_types"),
+	mercury_compile__expand_equiv_types_hlds(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "27", "equiv_types", !IO),
 
 	%
 	% Uncomment the following code to check that unique mode analysis
@@ -2111,275 +2190,258 @@
 	% after optimizations because deforestation reruns it.
 	%
 
-	%mercury_compile__check_unique_modes(HLDS26, Verbose, Stats,
-	%		HLDS27, FoundUniqError),
-	%
-	%{ FoundUniqError = yes ->
+	% mercury_compile__check_unique_modes(Verbose, Stats, !HLDS,
+	%	FoundUniqError, !IO),
+	% ( FoundUniqError = yes ->
 	%	error("unique modes failed")
-	%;
+	% ;
 	%	true
-	%},
+	% ),
 
-	mercury_compile__maybe_termination(HLDS27, Verbose, Stats, HLDS28),
-	mercury_compile__maybe_dump_hlds(HLDS28, "28", "termination"),
+	mercury_compile__maybe_termination(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "28", "termination", !IO),
 
-	mercury_compile__maybe_type_ctor_infos(HLDS28, Verbose, Stats, HLDS29),
-	mercury_compile__maybe_dump_hlds(HLDS29, "29", "type_ctor_infos"),
+	mercury_compile__maybe_type_ctor_infos(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "29", "type_ctor_infos", !IO),
 
 	% warn_dead_procs must come after type_ctor_infos, so that it
 	% handles unification & comparison procedures correctly,
 	% but it must also come before optimizations such as higher-order
 	% specialization and inlining, which can make the original code
 	% for a procedure dead by inlining/specializing all uses of it.
-	mercury_compile__maybe_warn_dead_procs(HLDS29, Verbose, Stats, HLDS30),
-	mercury_compile__maybe_dump_hlds(HLDS30, "30", "warn_dead_procs"),
-
-	mercury_compile__maybe_bytecodes(HLDS30, ModuleName, Verbose, Stats),
+	mercury_compile__maybe_warn_dead_procs(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "30", "warn_dead_procs", !IO),
 
+	mercury_compile__maybe_bytecodes(!.HLDS, ModuleName, Verbose, Stats,
+		!IO),
 	% stage number 31 is used by mercury_compile__maybe_bytecodes
 
-	mercury_compile__maybe_higher_order(HLDS30, Verbose, Stats, HLDS32),
-	mercury_compile__maybe_dump_hlds(HLDS32, "32", "higher_order"),
+	mercury_compile__maybe_higher_order(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "32", "higher_order", !IO),
 
-	mercury_compile__maybe_introduce_accumulators(HLDS32,
-			Verbose, Stats, HLDS33),
-	mercury_compile__maybe_dump_hlds(HLDS33, "33", "accum"),
+	mercury_compile__maybe_introduce_accumulators(Verbose, Stats, !HLDS,
+		!IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "33", "accum", !IO),
 
-	mercury_compile__maybe_do_inlining(HLDS33, Verbose, Stats, HLDS34),
-	mercury_compile__maybe_dump_hlds(HLDS34, "34", "inlining"),
+	mercury_compile__maybe_do_inlining(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "34", "inlining", !IO),
 
 	% Hoisting loop invariants first invokes pass 35, "mark_static".
 	% "mark_static" is also run at stage 60.
 	%
-	mercury_compile__maybe_loop_inv(HLDS34, Verbose, Stats, HLDS36),
-	mercury_compile__maybe_dump_hlds(HLDS36, "36", "loop_inv"),
+	mercury_compile__maybe_loop_inv(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "36", "loop_inv", !IO),
 
-	mercury_compile__maybe_deforestation(HLDS36, Verbose, Stats, HLDS37),
-	mercury_compile__maybe_dump_hlds(HLDS37, "37", "deforestation"),
+	mercury_compile__maybe_deforestation(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "37", "deforestation", !IO),
 
-	mercury_compile__maybe_delay_construct(HLDS37, Verbose, Stats, HLDS38),
-	mercury_compile__maybe_dump_hlds(HLDS38, "38", "delay_construct"),
+	mercury_compile__maybe_delay_construct(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "38", "delay_construct", !IO),
 
-	mercury_compile__maybe_unused_args(HLDS38, Verbose, Stats, HLDS40),
-	mercury_compile__maybe_dump_hlds(HLDS40, "40", "unused_args"),
+	mercury_compile__maybe_unused_args(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "40", "unused_args", !IO),
 
-	mercury_compile__maybe_unneeded_code(HLDS40, Verbose, Stats, HLDS41),
-	mercury_compile__maybe_dump_hlds(HLDS41, "41", "unneeded_code"),
+	mercury_compile__maybe_unneeded_code(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "41", "unneeded_code", !IO),
 
-	mercury_compile__maybe_lco(HLDS41, Verbose, Stats, HLDS43),
-	mercury_compile__maybe_dump_hlds(HLDS43, "43", "lco"),
+	mercury_compile__maybe_lco(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "43", "lco", !IO),
+
+	mercury_compile__maybe_transform_aditi_builtins(Verbose, Stats, !HLDS,
+		!IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "44", "aditi_builtins", !IO),
 
-	mercury_compile__maybe_transform_aditi_builtins(HLDS43,
-		Verbose, Stats, HLDS44),
-	mercury_compile__maybe_dump_hlds(HLDS43, "44", "aditi_builtins"),
-	
 	% DNF transformations should be after inlining.
-	mercury_compile__maybe_transform_dnf(HLDS44, Verbose, Stats, HLDS45),
-	mercury_compile__maybe_dump_hlds(HLDS45, "45", "dnf"),
+	mercury_compile__maybe_transform_dnf(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "45", "dnf", !IO),
 
 	% Magic sets should be the last thing done to Aditi procedures
 	% before RL code generation, and must come immediately after DNF.
 	% Note that if this pass is done, it will also invokes dead_proc_elim
 	% (XXX which means dead_proc_elim may get done twice).
-	mercury_compile__maybe_magic(HLDS45, Verbose, Stats, HLDS47),
-	mercury_compile__maybe_dump_hlds(HLDS47, "47", "magic"),
+	mercury_compile__maybe_magic(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "47", "magic", !IO),
 
-	mercury_compile__maybe_eliminate_dead_procs(HLDS47, Verbose, Stats,
-		HLDS48),
-	mercury_compile__maybe_dump_hlds(HLDS48, "48", "dead_procs"),
+	mercury_compile__maybe_eliminate_dead_procs(Verbose, Stats, !HLDS,
+		!IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "48", "dead_procs", !IO),
 
 	% The term size profiling transformation should be after all
 	% transformations that construct terms of non-zero size. (Deep
 	% profiling does not construct non-zero size terms.)
-	mercury_compile__maybe_term_size_prof(HLDS48, Verbose, Stats, HLDS49),
-	mercury_compile__maybe_dump_hlds(HLDS49, "49", "term_size_prof"),
+	mercury_compile__maybe_term_size_prof(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "49", "term_size_prof", !IO),
 
 	% Deep profiling transformation should be done late in the piece
 	% since it munges the code a fair amount and introduces strange
 	% disjunctions that might confuse other hlds->hlds transformations.
-	mercury_compile__maybe_deep_profiling(HLDS49, Verbose, Stats, HLDS50,
-		DeepProfilingStructures),
-	mercury_compile__maybe_dump_hlds(HLDS50, "50", "deep_profiling"),
+	mercury_compile__maybe_deep_profiling(Verbose, Stats, !HLDS,
+		DeepProfilingStructs, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "50", "deep_profiling", !IO),
 
-	{ HLDS50 = HLDS51 },
-	mercury_compile__maybe_dump_hlds(HLDS51, "51", "middle_pass").
+	mercury_compile__maybe_dump_hlds(!.HLDS, "51", "middle_pass", !IO).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__maybe_generate_rl_bytecode(module_info, bool,
-		maybe(rl_file), io__state, io__state).
-:- mode mercury_compile__maybe_generate_rl_bytecode(in, in,
-		out, di, uo) is det.
+:- pred mercury_compile__maybe_generate_rl_bytecode(module_info::in, bool::in,
+	maybe(rl_file)::out, io::di, io::uo) is det.
 
 mercury_compile__maybe_generate_rl_bytecode(ModuleInfo,
-		Verbose, MaybeRLFile) -->
-	globals__io_lookup_bool_option(aditi, Aditi),
+		Verbose, MaybeRLFile, !IO) :-
+	globals__io_lookup_bool_option(aditi, Aditi, !IO),
 	(
-		{ Aditi = yes },
-		{ module_info_get_do_aditi_compilation(ModuleInfo,
-			AditiCompile) },
+		Aditi = yes,
+		module_info_get_do_aditi_compilation(ModuleInfo,
+			AditiCompile),
 		(
-			{ AditiCompile = do_aditi_compilation },
+			AditiCompile = do_aditi_compilation,
 
 			%
 			% Generate the RL procedures.
 			%
-			maybe_write_string(Verbose, "% Generating RL...\n"),
-			maybe_flush_output(Verbose),
-			rl_gen__module(ModuleInfo, RLProcs0),
+			maybe_write_string(Verbose,
+				"% Generating RL...\n", !IO),
+			maybe_flush_output(Verbose, !IO),
+			rl_gen__module(ModuleInfo, RLProcs0, !IO),
 			mercury_compile__maybe_dump_rl(RLProcs0,
-				ModuleInfo, "", ""),
+				ModuleInfo, "", "", !IO),
 
 			%
 			% Optimize the RL procedures.
 			%
-			rl_opt__procs(ModuleInfo, RLProcs0, RLProcs),
+			rl_opt__procs(ModuleInfo, RLProcs0, RLProcs, !IO),
 			mercury_compile__maybe_dump_rl(RLProcs,
-				ModuleInfo, "", ".opt"),
+				ModuleInfo, "", ".opt", !IO),
 
 			%
 			% Convert the RL procedures to bytecode.
 			%
 			rl_out__generate_rl_bytecode(ModuleInfo,
-				RLProcs, MaybeRLFile)
+				RLProcs, MaybeRLFile, !IO)
 		;
-			{ AditiCompile = no_aditi_compilation },
-			{ MaybeRLFile = no },
+			AditiCompile = no_aditi_compilation,
+			MaybeRLFile = no,
 
-			globals__io_lookup_bool_option(aditi_only, AditiOnly),
+			globals__io_lookup_bool_option(aditi_only, AditiOnly,
+				!IO),
 			(
-				{ AditiOnly = yes },
+				AditiOnly = yes,
 
 				% Always generate a `.rlo' file if compiling
 				% with `--aditi-only'.
-				{ RLProcs = [] },
+				RLProcs = [],
 				rl_out__generate_rl_bytecode(ModuleInfo,
-					RLProcs, _)
+					RLProcs, _, !IO)
 			;
-				{ AditiOnly = no }
+				AditiOnly = no
 			)
 		)
 	;
-		{ Aditi = no },
-		{ MaybeRLFile = no }
+		Aditi = no,
+		MaybeRLFile = no
 	).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__backend_pass(module_info, module_info,
-	list(layout_data), global_data, list(c_procedure),
-	io__state, io__state).
-% :- mode mercury_compile__backend_pass(di, uo, out, out, di, uo) is det.
-:- mode mercury_compile__backend_pass(in, out, in, out, out, di, uo) is det.
-
-mercury_compile__backend_pass(HLDS50, HLDS, DeepProfilingStructures,
-		GlobalData, LLDS) -->
-	{ module_info_name(HLDS50, ModuleName) },
-	globals__io_lookup_bool_option(unboxed_float, UnboxFloat),
-	globals__io_lookup_bool_option(common_data, DoCommonData),
-	{ StaticCellInfo0 = init_static_cell_info(ModuleName, UnboxFloat,
-		DoCommonData) },
-	{ global_data_init(DeepProfilingStructures, StaticCellInfo0,
-		GlobalData0) },
+:- pred mercury_compile__backend_pass(module_info::in, module_info::out,
+	list(layout_data)::in, global_data::out, list(c_procedure)::out,
+	io::di, io::uo) is det.
+
+mercury_compile__backend_pass(!HLDS, DeepProfilingStructures,
+		GlobalData, LLDS, !IO) :-
+	module_info_name(!.HLDS, ModuleName),
+	globals__io_lookup_bool_option(unboxed_float, UnboxFloat, !IO),
+	globals__io_lookup_bool_option(common_data, DoCommonData, !IO),
+	StaticCellInfo0 = init_static_cell_info(ModuleName, UnboxFloat,
+		DoCommonData),
+	global_data_init(DeepProfilingStructures, StaticCellInfo0,
+		GlobalData0),
 
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
 
 	% map_args_to_regs affects the interface to a predicate,
 	% so it must be done in one phase immediately before code generation
 
-	mercury_compile__map_args_to_regs(HLDS50, Verbose, Stats, HLDS51),
-	mercury_compile__maybe_dump_hlds(HLDS51, "51", "args_to_regs"),
+	mercury_compile__map_args_to_regs(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "51", "args_to_regs", !IO),
 
-	globals__io_lookup_bool_option(trad_passes, TradPasses),
+	globals__io_lookup_bool_option(trad_passes, TradPasses, !IO),
 	(
-		{ TradPasses = no },
-		mercury_compile__backend_pass_by_phases(HLDS51, HLDS,
-			GlobalData0, GlobalData, LLDS)
-	;
-		{ TradPasses = yes },
-		mercury_compile__backend_pass_by_preds(HLDS51, HLDS,
-			GlobalData0, GlobalData, LLDS)
+		TradPasses = no,
+		mercury_compile__backend_pass_by_phases(!HLDS,
+			GlobalData0, GlobalData, LLDS, !IO)
+	;
+		TradPasses = yes,
+		mercury_compile__backend_pass_by_preds(!HLDS,
+			GlobalData0, GlobalData, LLDS, !IO)
 	).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__backend_pass_by_phases(module_info, module_info,
-	global_data, global_data, list(c_procedure),
-	io__state, io__state).
-:- mode mercury_compile__backend_pass_by_phases(in, out, in, out, out, di, uo)
-	is det.
+:- pred mercury_compile__backend_pass_by_phases(module_info::in,
+	module_info::out, global_data::in, global_data::out,
+	list(c_procedure)::out, io::di, io::uo) is det.
 
-mercury_compile__backend_pass_by_phases(HLDS51, HLDS90,
-		GlobalData0, GlobalData, LLDS) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
+mercury_compile__backend_pass_by_phases(!HLDS, !GlobalData, LLDS, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
 
-	mercury_compile__maybe_saved_vars(HLDS51, Verbose, Stats, HLDS53),
-	mercury_compile__maybe_dump_hlds(HLDS53, "53", "saved_vars_const"),
+	mercury_compile__maybe_saved_vars(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "53", "saved_vars_const", !IO),
 
-	mercury_compile__maybe_stack_opt(HLDS53, Verbose, Stats, HLDS55),
-	mercury_compile__maybe_dump_hlds(HLDS55, "55", "saved_vars_cell"),
+	mercury_compile__maybe_stack_opt(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "55", "saved_vars_cell", !IO),
 
-	mercury_compile__maybe_followcode(HLDS55, Verbose, Stats, HLDS57),
-	mercury_compile__maybe_dump_hlds(HLDS57, "57", "followcode"),
+	mercury_compile__maybe_followcode(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "57", "followcode", !IO),
 
-	mercury_compile__simplify(HLDS57, no, yes, Verbose, Stats, 
-		process_all_nonimported_nonaditi_procs, HLDS59),
-	mercury_compile__maybe_dump_hlds(HLDS59, "59", "simplify2"),
+	mercury_compile__simplify(no, yes, Verbose, Stats,
+		process_all_nonimported_nonaditi_procs, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "59", "simplify2", !IO),
 
-	mercury_compile__compute_liveness(HLDS59, Verbose, Stats, HLDS61),
-	mercury_compile__maybe_dump_hlds(HLDS61, "61", "liveness"),
+	mercury_compile__compute_liveness(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "61", "liveness", !IO),
 
-	mercury_compile__compute_stack_vars(HLDS61, Verbose, Stats, HLDS65),
-	mercury_compile__maybe_dump_hlds(HLDS65, "65", "stackvars"),
+	mercury_compile__compute_stack_vars(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "65", "stackvars", !IO),
 
-	mercury_compile__allocate_store_map(HLDS65, Verbose, Stats, HLDS68),
-	mercury_compile__maybe_dump_hlds(HLDS68, "68", "store_map"),
+	mercury_compile__allocate_store_map(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "68", "store_map", !IO),
 
-	mercury_compile__maybe_goal_paths(HLDS68, Verbose, Stats, HLDS90),
-	mercury_compile__maybe_dump_hlds(HLDS90, "90", "precodegen"),
+	mercury_compile__maybe_goal_paths(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "90", "precodegen", !IO),
 
-	mercury_compile__generate_code(HLDS90, GlobalData0, Verbose, Stats,
-		GlobalData1, LLDS1),
+	mercury_compile__generate_code(!.HLDS, Verbose, Stats,
+		!GlobalData, LLDS1, !IO),
 
-	mercury_compile__maybe_generate_stack_layouts(HLDS90, GlobalData1,
-		LLDS1, Verbose, Stats, GlobalData),
-	% mercury_compile__maybe_dump_global_data(GlobalData),
+	mercury_compile__maybe_generate_stack_layouts(!.HLDS, LLDS1,
+		Verbose, Stats, !GlobalData, !IO),
+	% mercury_compile__maybe_dump_global_data(!.GlobalData, !IO),
 
-	mercury_compile__maybe_do_optimize(LLDS1, GlobalData, Verbose, Stats,
-		LLDS).
+	mercury_compile__maybe_do_optimize(!.GlobalData, Verbose, Stats,
+		LLDS1, LLDS, !IO).
 
-:- pred mercury_compile__backend_pass_by_preds(module_info, module_info,
-	global_data, global_data, list(c_procedure),
-	io__state, io__state).
-% :- mode mercury_compile__backend_pass_by_preds(di, uo, in, out, out, di, uo)
-%	is det.
-:- mode mercury_compile__backend_pass_by_preds(in, out, in, out, out, di, uo)
-	is det.
+:- pred mercury_compile__backend_pass_by_preds(module_info::in,
+	module_info::out, global_data::in, global_data::out,
+	list(c_procedure)::out, io::di, io::uo) is det.
 
-mercury_compile__backend_pass_by_preds(HLDS0, HLDS, GlobalData0, GlobalData,
-		LLDS) -->
-	{ module_info_predids(HLDS0, PredIds) },
-	mercury_compile__backend_pass_by_preds_2(PredIds, HLDS0, HLDS,
-		GlobalData0, GlobalData, LLDS).
-
-:- pred mercury_compile__backend_pass_by_preds_2(list(pred_id),
-	module_info, module_info, global_data, global_data, list(c_procedure),
-	io__state, io__state).
-% :- mode mercury_compile__backend_pass_by_preds_2(in, di, uo, in, out, out,
-%	di, uo) is det.
-:- mode mercury_compile__backend_pass_by_preds_2(in, in, out, in, out, out,
-	di, uo) is det.
+mercury_compile__backend_pass_by_preds(!HLDS, !GlobalData, LLDS, !IO) :-
+	module_info_predids(!.HLDS, PredIds),
+	mercury_compile__backend_pass_by_preds_2(PredIds, !HLDS, !GlobalData,
+		LLDS, !IO).
 
-mercury_compile__backend_pass_by_preds_2([], !ModuleInfo, !GlobalData, [],
-		!IO).
-mercury_compile__backend_pass_by_preds_2([PredId | PredIds], !ModuleInfo,
+:- pred mercury_compile__backend_pass_by_preds_2(list(pred_id)::in,
+	module_info::in, module_info::out, global_data::in, global_data::out,
+	list(c_procedure)::out, io::di, io::uo) is det.
+
+mercury_compile__backend_pass_by_preds_2([], !HLDS, !GlobalData, [], !IO).
+mercury_compile__backend_pass_by_preds_2([PredId | PredIds], !HLDS,
 		!GlobalData, Code, !IO) :-
-	module_info_preds(!.ModuleInfo, PredTable),
+	module_info_preds(!.HLDS, PredTable),
 	map__lookup(PredTable, PredId, PredInfo),
 	ProcIds = pred_info_non_imported_procids(PredInfo),
-	( 
+	(
 		( ProcIds = []
 		; hlds_pred__pred_info_is_aditi_relation(PredInfo)
 		)
@@ -2389,7 +2451,7 @@
 		globals__io_lookup_bool_option(verbose, Verbose, !IO),
 		( Verbose = yes ->
 			io__write_string("% Generating code for ", !IO),
-			hlds_out__write_pred_id(!.ModuleInfo, PredId, !IO),
+			hlds_out__write_pred_id(!.HLDS, PredId, !IO),
 			io__write_string("\n", !IO)
 		;
 			true
@@ -2397,760 +2459,745 @@
 		(
 			PredModule = pred_info_module(PredInfo),
 			PredName = pred_info_name(PredInfo),
-                        PredArity = pred_info_arity(PredInfo),
-                        no_type_info_builtin(PredModule, PredName,
-				PredArity)
+			PredArity = pred_info_arity(PredInfo),
+			no_type_info_builtin(PredModule, PredName, PredArity)
 		->
 				% These predicates should never be traced,
 				% since they do not obey typeinfo_liveness.
 				% Since they may be opt_imported into other
 				% modules, we must switch off the tracing
 				% of such preds on a pred-by-pred basis.
-			module_info_globals(!.ModuleInfo, Globals0),
+			module_info_globals(!.HLDS, Globals0),
 			globals__get_trace_level(Globals0, TraceLevel),
 			globals__set_trace_level_none(Globals0, Globals1),
-			module_info_set_globals(Globals1, !ModuleInfo),
+			module_info_set_globals(Globals1, !HLDS),
 			copy(Globals1, Globals1Unique),
 			globals__io_set_globals(Globals1Unique, !IO),
 			mercury_compile__backend_pass_by_preds_3(ProcIds,
-				PredId, PredInfo, !ModuleInfo, !GlobalData,
+				PredId, PredInfo, !HLDS, !GlobalData,
 				Code1, !IO),
-			module_info_globals(!.ModuleInfo, Globals2),
+			module_info_globals(!.HLDS, Globals2),
 			globals__set_trace_level(Globals2, TraceLevel,
 				Globals),
-			module_info_set_globals(Globals, !ModuleInfo),
+			module_info_set_globals(Globals, !HLDS),
 			copy(Globals, GlobalsUnique),
 			globals__io_set_globals(GlobalsUnique, !IO)
 		;
 			mercury_compile__backend_pass_by_preds_3(ProcIds,
-				PredId, PredInfo, !ModuleInfo, !GlobalData,
+				PredId, PredInfo, !HLDS, !GlobalData,
 				Code1, !IO)
 		)
 	),
-	mercury_compile__backend_pass_by_preds_2(PredIds, !ModuleInfo,
-		!GlobalData, Code2, !IO),
+	mercury_compile__backend_pass_by_preds_2(PredIds, !HLDS, !GlobalData,
+		Code2, !IO),
 	list__append(Code1, Code2, Code).
 
-:- pred mercury_compile__backend_pass_by_preds_3(list(proc_id), pred_id,
-	pred_info, module_info, module_info, global_data, global_data,
-	list(c_procedure), io__state, io__state).
-% :- mode mercury_compile__backend_pass_by_preds_3(in, in, in, di, uo, in, out,
-%	out, di, uo) is det.
-:- mode mercury_compile__backend_pass_by_preds_3(in, in, in, in, out, in, out,
-	out, di, uo) is det.
+:- pred mercury_compile__backend_pass_by_preds_3(list(proc_id)::in,
+	pred_id::in, pred_info::in, module_info::in, module_info::out,
+	global_data::in, global_data::out, list(c_procedure)::out,
+	io::di, io::uo) is det.
 
-mercury_compile__backend_pass_by_preds_3([], _, _, ModuleInfo, ModuleInfo,
-		GlobalData, GlobalData, []) --> [].
+mercury_compile__backend_pass_by_preds_3([], _, _, !HLDS, !GlobalData, [],
+		!IO).
 mercury_compile__backend_pass_by_preds_3([ProcId | ProcIds], PredId, PredInfo,
-		ModuleInfo0, ModuleInfo, GlobalData0, GlobalData,
-		[Proc | Procs]) -->
-	{ pred_info_procedures(PredInfo, ProcTable) },
-	{ map__lookup(ProcTable, ProcId, ProcInfo) },
-	mercury_compile__backend_pass_by_preds_4(PredInfo, ProcInfo,
-		ProcId, PredId, ModuleInfo0, ModuleInfo1,
-		GlobalData0, GlobalData1, Proc),
+		!HLDS, !GlobalData, [Proc | Procs], !IO) :-
+	pred_info_procedures(PredInfo, ProcTable),
+	map__lookup(ProcTable, ProcId, ProcInfo),
+	mercury_compile__backend_pass_by_preds_4(PredInfo, ProcInfo, _,
+		ProcId, PredId, !HLDS, !GlobalData, Proc, !IO),
 	mercury_compile__backend_pass_by_preds_3(ProcIds, PredId, PredInfo,
-		ModuleInfo1, ModuleInfo, GlobalData1, GlobalData, Procs).
+		!HLDS, !GlobalData, Procs, !IO).
 
-:- pred mercury_compile__backend_pass_by_preds_4(pred_info, proc_info,
-	proc_id, pred_id, module_info, module_info, global_data, global_data,
-	c_procedure, io__state, io__state).
-% :- mode mercury_compile__backend_pass_by_preds_4(in, in, in, in, di, uo,
-% 	in, out, out, di, uo) is det.
-:- mode mercury_compile__backend_pass_by_preds_4(in, in, in, in, in, out,
-	in, out, out, di, uo) is det.
-
-mercury_compile__backend_pass_by_preds_4(PredInfo, ProcInfo0, ProcId, PredId,
-		ModuleInfo0, ModuleInfo, GlobalData0, GlobalData, ProcCode) -->
-	{ module_info_globals(ModuleInfo0, Globals) },
-	{ globals__lookup_bool_option(Globals, optimize_saved_vars_const,
-		SavedVarsConst) },
+:- pred mercury_compile__backend_pass_by_preds_4(pred_info::in, proc_info::in,
+	proc_info::out, proc_id::in, pred_id::in,
+	module_info::in, module_info::out, global_data::in, global_data::out,
+	c_procedure::out, io::di, io::uo) is det.
+
+mercury_compile__backend_pass_by_preds_4(PredInfo, !ProcInfo, ProcId, PredId,
+		!HLDS, !GlobalData, ProcCode, !IO) :-
+	module_info_globals(!.HLDS, Globals),
+	globals__lookup_bool_option(Globals, optimize_saved_vars_const,
+		SavedVarsConst),
 	(
-		{ SavedVarsConst = yes },
-		saved_vars_proc(PredId, ProcId, ProcInfo0, ProcInfoSavedConst,
-			ModuleInfo0, ModuleInfoSavedConst)
-	;
-		{ SavedVarsConst = no },
-		{ ProcInfoSavedConst = ProcInfo0 },
-		{ ModuleInfoSavedConst = ModuleInfo0 }
+		SavedVarsConst = yes,
+		saved_vars_proc(PredId, ProcId, !ProcInfo, !HLDS, !IO)
+	;
+		SavedVarsConst = no
 	),
-	{ globals__lookup_bool_option(Globals, optimize_saved_vars_cell,
-		SavedVarsCell) },
+	globals__lookup_bool_option(Globals, optimize_saved_vars_cell,
+		SavedVarsCell),
 	(
-		{ SavedVarsCell = yes },
-		stack_opt_cell(PredId, ProcId,
-			ProcInfoSavedConst, ProcInfoSavedCell,
-			ModuleInfoSavedConst, ModuleInfoSavedCell)
-	;
-		{ SavedVarsCell = no },
-		{ ProcInfoSavedCell = ProcInfoSavedConst },
-		{ ModuleInfoSavedCell = ModuleInfoSavedConst }
+		SavedVarsCell = yes,
+		stack_opt_cell(PredId, ProcId, !ProcInfo, !HLDS, !IO)
+	;
+		SavedVarsCell = no
 	),
-	{ globals__lookup_bool_option(Globals, follow_code, FollowCode) },
-	{ globals__lookup_bool_option(Globals, prev_code, PrevCode) },
-	( { FollowCode = yes ; PrevCode = yes } ->
-		{ move_follow_code_in_proc(PredId, ProcId, PredInfo,
-			ProcInfoSavedCell, ProcInfoFollowCode,
-			ModuleInfoSavedCell, ModuleInfoFollow) }
+	globals__lookup_bool_option(Globals, follow_code, FollowCode),
+	globals__lookup_bool_option(Globals, prev_code, PrevCode),
+	(
+		( FollowCode = yes
+		; PrevCode = yes
+		)
+	->
+		move_follow_code_in_proc(PredId, ProcId, PredInfo,
+			!ProcInfo, !HLDS)
 	;
-		{ ProcInfoFollowCode = ProcInfoSavedCell },
-		{ ModuleInfoFollow = ModuleInfoSavedCell }
+		true
 	),
-	{ simplify__find_simplifications(no, Globals, Simplifications) },
+	simplify__find_simplifications(no, Globals, Simplifications),
 	simplify__proc([do_once | Simplifications], PredId, ProcId,
-		ModuleInfoFollow, ModuleInfoSimplify,
-		ProcInfoFollowCode, ProcInfoSimplify),
+		!HLDS, !ProcInfo, !IO),
 	write_proc_progress_message("% Computing liveness in ", PredId, ProcId,
-		ModuleInfoSimplify),
-	detect_liveness_proc(PredId, ProcId, ModuleInfoSimplify,
-		ProcInfoSimplify, ProcInfoLiveness),
+		!.HLDS, !IO),
+	detect_liveness_proc(PredId, ProcId, !.HLDS, !ProcInfo, !IO),
 	write_proc_progress_message("% Allocating stack slots in ", PredId,
-		ProcId, ModuleInfoSimplify),
-	allocate_stack_slots_in_proc(PredId, ProcId, ModuleInfoSimplify,
-		ProcInfoLiveness, ProcInfoStackSlot),
+		ProcId, !.HLDS, !IO),
+	allocate_stack_slots_in_proc(PredId, ProcId, !.HLDS, !ProcInfo, !IO),
 	write_proc_progress_message(
 		"% Allocating storage locations for live vars in ",
-		PredId, ProcId, ModuleInfoSimplify),
-	{ allocate_store_maps(final_allocation, PredId, ModuleInfoSimplify,
-		ProcInfoStackSlot, ProcInfoStoreAlloc) },
-	globals__io_get_trace_level(TraceLevel),
-	( { given_trace_level_is_none(TraceLevel) = no } ->
+		PredId, ProcId, !.HLDS, !IO),
+	allocate_store_maps(final_allocation, PredId, !.HLDS, !ProcInfo),
+	globals__io_get_trace_level(TraceLevel, !IO),
+	( given_trace_level_is_none(TraceLevel) = no ->
 		write_proc_progress_message(
 			"% Calculating goal paths in ",
-			PredId, ProcId, ModuleInfoSimplify),
-		{ goal_path__fill_slots(ModuleInfoSimplify,
-			ProcInfoStoreAlloc, ProcInfo) }
+			PredId, ProcId, !.HLDS, !IO),
+		goal_path__fill_slots(!.HLDS, !ProcInfo)
 	;
-		{ ProcInfo = ProcInfoStoreAlloc }
+		true
 	),
 	write_proc_progress_message(
 		"% Generating low-level (LLDS) code for ",
-		PredId, ProcId, ModuleInfoSimplify),
-	{ generate_proc_code(PredInfo, ProcInfo, ProcId, PredId,
-		ModuleInfoSimplify, GlobalData0, GlobalData1, ProcCode0) },
-	{ globals__lookup_bool_option(Globals, optimize, Optimize) },
+		PredId, ProcId, !.HLDS, !IO),
+	generate_proc_code(PredInfo, !.ProcInfo, ProcId, PredId, !.HLDS,
+		!GlobalData, ProcCode0),
+	globals__lookup_bool_option(Globals, optimize, Optimize),
 	(
-		{ Optimize = yes },
-		optimize__proc(ProcCode0, GlobalData1, ProcCode)
+		Optimize = yes,
+		optimize__proc(!.GlobalData, ProcCode0, ProcCode, !IO)
 	;
-		{ Optimize = no },
-		{ ProcCode = ProcCode0 }
+		Optimize = no,
+		ProcCode = ProcCode0
 	),
-	{ ProcCode = c_procedure(_, _, PredProcId, Instructions, _, _, _) },
+	ProcCode = c_procedure(_, _, PredProcId, Instructions, _, _, _),
 	write_proc_progress_message(
 		"% Generating call continuation information for ",
-		PredId, ProcId, ModuleInfoSimplify),
-	{ continuation_info__maybe_process_proc_llds(Instructions, PredProcId,
-		ModuleInfoSimplify, GlobalData1, GlobalData) },
-	{ ModuleInfo = ModuleInfoSimplify }.
+		PredId, ProcId, !.HLDS, !IO),
+	continuation_info__maybe_process_proc_llds(Instructions, PredProcId,
+		!.HLDS, !GlobalData).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__puritycheck(bool, module_info, bool, bool,
-				module_info, bool, io__state, io__state).
-:- mode mercury_compile__puritycheck(in, in, in, in, out, out, di, uo) is det.
-
-mercury_compile__puritycheck(FoundTypeError, HLDS0, Verbose, Stats,
-		HLDS, FoundPostTypecheckError) -->
-	{ module_info_num_errors(HLDS0, NumErrors0) },
-	puritycheck(FoundTypeError, FoundPostTypecheckError, HLDS0, HLDS),
-	{ module_info_num_errors(HLDS, NumErrors) },
-	( { NumErrors \= NumErrors0 } ->
+:- pred mercury_compile__puritycheck(bool::in, bool::in,
+	module_info::in, module_info::out, bool::in, bool::out,
+	io::di, io::uo) is det.
+
+mercury_compile__puritycheck(Verbose, Stats, !HLDS, FoundTypeError,
+		FoundPostTypecheckError, !IO) :-
+	module_info_num_errors(!.HLDS, NumErrors0),
+	puritycheck(FoundTypeError, FoundPostTypecheckError, !HLDS, !IO),
+	module_info_num_errors(!.HLDS, NumErrors),
+	( NumErrors \= NumErrors0 ->
 		maybe_write_string(Verbose,
-			"% Program contains purity error(s).\n"),
-		io__set_exit_status(1)
+			"% Program contains purity error(s).\n", !IO),
+		io__set_exit_status(1, !IO)
 	;
 		maybe_write_string(Verbose,
-			"% Program is purity-correct.\n")
+			"% Program is purity-correct.\n", !IO)
 	),
-	maybe_report_stats(Stats).
+	maybe_report_stats(Stats, !IO).
 
-:- pred mercury_compile__modecheck(module_info, bool, bool,
-				module_info, bool, bool, io__state, io__state).
-:- mode mercury_compile__modecheck(in, in, in, out, out, out, di, uo) is det.
-
-mercury_compile__modecheck(HLDS0, Verbose, Stats, HLDS, FoundModeError,
-		UnsafeToContinue) -->
-	{ module_info_num_errors(HLDS0, NumErrors0) },
-	modecheck(HLDS0, HLDS, UnsafeToContinue),
-	{ module_info_num_errors(HLDS, NumErrors) },
-	( { NumErrors \= NumErrors0 } ->
-		{ FoundModeError = yes },
+:- pred mercury_compile__modecheck(bool::in, bool::in,
+	module_info::in, module_info::out, bool::out,
+	bool::out, io::di, io::uo) is det.
+
+mercury_compile__modecheck(Verbose, Stats, !HLDS, FoundModeError,
+		UnsafeToContinue, !IO) :-
+	module_info_num_errors(!.HLDS, NumErrors0),
+	modecheck(!HLDS, UnsafeToContinue, !IO),
+	module_info_num_errors(!.HLDS, NumErrors),
+	( NumErrors \= NumErrors0 ->
+		FoundModeError = yes,
 		maybe_write_string(Verbose,
-			"% Program contains mode error(s).\n"),
-		io__set_exit_status(1)
+			"% Program contains mode error(s).\n", !IO),
+		io__set_exit_status(1, !IO)
 	;
-		{ FoundModeError = no },
+		FoundModeError = no,
 		maybe_write_string(Verbose,
-			"% Program is mode-correct.\n")
+			"% Program is mode-correct.\n", !IO)
 	),
-	maybe_report_stats(Stats).
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__detect_switches(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-:- pred mercury_compile__detect_switches(module_info, bool, bool, module_info,
-	io__state, io__state).
-:- mode mercury_compile__detect_switches(in, in, in, out, di, uo) is det.
-
-mercury_compile__detect_switches(HLDS0, Verbose, Stats, HLDS) -->
-	maybe_write_string(Verbose, "% Detecting switches...\n"),
-	maybe_flush_output(Verbose),
-	detect_switches(HLDS0, HLDS),
-	maybe_write_string(Verbose, "% done.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__detect_cse(module_info, bool, bool, module_info,
-	io__state, io__state).
-:- mode mercury_compile__detect_cse(in, in, in, out, di, uo) is det.
-
-mercury_compile__detect_cse(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(common_goal, CommonGoal),
-	( { CommonGoal = yes } ->
-		maybe_write_string(Verbose, "% Detecting common deconstructions...\n"),
-		detect_cse(HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ HLDS = HLDS0 }
-	).
-
-:- pred mercury_compile__check_determinism(module_info, bool, bool,
-	module_info, bool, io__state, io__state).
-:- mode mercury_compile__check_determinism(in, in, in, out, out, di, uo) is det.
-
-mercury_compile__check_determinism(HLDS0, Verbose, Stats, HLDS, FoundError) -->
-	{ module_info_num_errors(HLDS0, NumErrors0) },
-	determinism_pass(HLDS0, HLDS),
-	{ module_info_num_errors(HLDS, NumErrors) },
-	( { NumErrors \= NumErrors0 } ->
-		{ FoundError = yes },
+mercury_compile__detect_switches(Verbose, Stats, !HLDS, !IO) :-
+	maybe_write_string(Verbose, "% Detecting switches...\n", !IO),
+	maybe_flush_output(Verbose, !IO),
+	detect_switches(!HLDS, !IO),
+	maybe_write_string(Verbose, "% done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__detect_cse(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__detect_cse(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(common_goal, CommonGoal, !IO),
+	( CommonGoal = yes ->
+		maybe_write_string(Verbose,
+			"% Detecting common deconstructions...\n", !IO),
+		detect_cse(!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
+	).
+
+:- pred mercury_compile__check_determinism(bool::in, bool::in,
+	module_info::in, module_info::out, bool::out, io::di, io::uo) is det.
+
+mercury_compile__check_determinism(Verbose, Stats, !HLDS, FoundError, !IO) :-
+	module_info_num_errors(!.HLDS, NumErrors0),
+	determinism_pass(!HLDS, !IO),
+	module_info_num_errors(!.HLDS, NumErrors),
+	( NumErrors \= NumErrors0 ->
+		FoundError = yes,
 		maybe_write_string(Verbose,
-			"% Program contains determinism error(s).\n"),
-		io__set_exit_status(1)
+			"% Program contains determinism error(s).\n", !IO),
+		io__set_exit_status(1, !IO)
 	;
-		{ FoundError = no },
+		FoundError = no,
 		maybe_write_string(Verbose,
-			"% Program is determinism-correct.\n")
+			"% Program is determinism-correct.\n", !IO)
 	),
-	maybe_report_stats(Stats).
+	maybe_report_stats(Stats, !IO).
 
-:- pred mercury_compile__maybe_termination(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_termination(in, in, in, out, di, uo) is det.
-
-mercury_compile__maybe_termination(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(polymorphism, Polymorphism),
-	globals__io_lookup_bool_option(termination, Termination),
+:- pred mercury_compile__maybe_termination(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_termination(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_get_globals(Globals, !IO),
+	globals__lookup_bool_option(Globals, polymorphism, Polymorphism),
+	globals__lookup_bool_option(Globals, termination, Termination),
 	% Termination analysis requires polymorphism to be run,
-	% as termination analysis does not handle complex unification
-	( 
-		{ Polymorphism = yes },
-		{ Termination = yes }
+	% since it does not handle complex unification
+	(
+		Polymorphism = yes,
+		Termination = yes
 	->
-		maybe_write_string(Verbose, "% Detecting termination...\n"),
-		termination__pass(HLDS0, HLDS),
-		maybe_write_string(Verbose, "% Termination checking done.\n"),
-		maybe_report_stats(Stats)
+		maybe_write_string(Verbose,
+			"% Detecting termination...\n", !IO),
+		termination__pass(!HLDS, !IO),
+		maybe_write_string(Verbose,
+			"% Termination checking done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS = HLDS0 }
+		true
 	).
 
-:- pred mercury_compile__check_unique_modes(module_info, bool, bool,
-	module_info, bool, io__state, io__state).
-:- mode mercury_compile__check_unique_modes(in, in, in, out, out, di, uo)
-	is det.
+:- pred mercury_compile__check_unique_modes(bool::in, bool::in,
+	module_info::in, module_info::out, bool::out, io::di, io::uo) is det.
 
-mercury_compile__check_unique_modes(HLDS0, Verbose, Stats, HLDS, FoundError) -->
+mercury_compile__check_unique_modes(Verbose, Stats, !HLDS, FoundError, !IO) :-
 	maybe_write_string(Verbose,
-		"% Checking for backtracking over unique modes...\n"),
-	{ module_info_num_errors(HLDS0, NumErrors0) },
-	unique_modes__check_module(HLDS0, HLDS),
-	{ module_info_num_errors(HLDS, NumErrors) },
-	( { NumErrors \= NumErrors0 } ->
-		{ FoundError = yes },
+		"% Checking for backtracking over unique modes...\n", !IO),
+	module_info_num_errors(!.HLDS, NumErrors0),
+	unique_modes__check_module(!HLDS, !IO),
+	module_info_num_errors(!.HLDS, NumErrors),
+	( NumErrors \= NumErrors0 ->
+		FoundError = yes,
 		maybe_write_string(Verbose,
-			"% Program contains unique mode error(s).\n"),
-		io__set_exit_status(1)
+			"% Program contains unique mode error(s).\n", !IO),
+		io__set_exit_status(1, !IO)
 	;
-		{ FoundError = no },
+		FoundError = no,
 		maybe_write_string(Verbose,
-			"% Program is unique-mode-correct.\n")
+			"% Program is unique-mode-correct.\n", !IO)
 	),
-	maybe_report_stats(Stats).
+	maybe_report_stats(Stats, !IO).
 
-:- pred mercury_compile__check_stratification(module_info, bool, bool,
-	module_info, bool, io__state, io__state).
-:- mode mercury_compile__check_stratification(in, in, in, out, out, di, uo)
-	is det.
+:- pred mercury_compile__check_stratification(bool::in, bool::in,
+	module_info::in, module_info::out, bool::out, io::di, io::uo) is det.
 
-mercury_compile__check_stratification(HLDS0, Verbose, Stats, HLDS, 
-		FoundError) -->
-	{ module_info_stratified_preds(HLDS0, StratifiedPreds) },
-	globals__io_lookup_bool_option(warn_non_stratification, Warn),
+mercury_compile__check_stratification(Verbose, Stats, !HLDS, FoundError,
+		!IO) :-
+	module_info_stratified_preds(!.HLDS, StratifiedPreds),
+	globals__io_lookup_bool_option(warn_non_stratification, Warn, !IO),
 	(
-		  { \+ set__empty(StratifiedPreds)
-		  ; Warn = yes }
+		( \+ set__empty(StratifiedPreds)
+		; Warn = yes
+		)
 	->
 		maybe_write_string(Verbose,
-			"% Checking stratification...\n"),
-		io__get_exit_status(OldStatus),
-		io__set_exit_status(0),
-		stratify__check_stratification(HLDS0, HLDS),
-		io__get_exit_status(NewStatus),
-		( { NewStatus \= 0 } ->
-			{ FoundError = yes },
+			"% Checking stratification...\n", !IO),
+		io__get_exit_status(OldStatus, !IO),
+		io__set_exit_status(0, !IO),
+		stratify__check_stratification(!HLDS, !IO),
+		io__get_exit_status(NewStatus, !IO),
+		( NewStatus \= 0 ->
+			FoundError = yes,
 			maybe_write_string(Verbose,
-				"% Program contains stratification error(s).\n")
+				"% Program contains stratification " ++
+				"error(s).\n", !IO)
 		;
-			{ FoundError = no },
-			maybe_write_string(Verbose,
-				"% done.\n"),
-			io__set_exit_status(OldStatus)
+			FoundError = no,
+			maybe_write_string(Verbose, "% done.\n", !IO),
+			io__set_exit_status(OldStatus, !IO)
 		),
-		maybe_report_stats(Stats)
+		maybe_report_stats(Stats, !IO)
 	;
-		{ FoundError = no },
-		{ HLDS = HLDS0 }
+		FoundError = no
 	).
 
-:- pred mercury_compile__maybe_warn_dead_procs(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_warn_dead_procs(in, in, in, out, di, uo)
-	is det.
+:- pred mercury_compile__maybe_warn_dead_procs(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_warn_dead_procs(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(warn_dead_procs, WarnDead),
-	( { WarnDead = yes } ->
-		maybe_write_string(Verbose,
-			"% Warning about dead procedures...\n"),
-		maybe_flush_output(Verbose),
-		dead_proc_elim(warning_pass, HLDS0, _HLDS1),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats),
+mercury_compile__maybe_warn_dead_procs(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(warn_dead_procs, WarnDead, !IO),
+	( WarnDead = yes ->
+		maybe_write_string(Verbose,
+			"% Warning about dead procedures...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		dead_proc_elim(warning_pass, !.HLDS, _HLDS1, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 
 %		XXX The warning pass also does all the work of optimizing
-%		    away the dead procedures.  If we're optimizing, then
-%		    it would be nice if we could keep the HLDS that results.
-%                   However, because this pass gets run before type
-%		    specialization, dead code elimination at this point
-%		    incorrectly optimizes away procedures created for
-%		    `pragma type_spec' declarations.  So we can't use the
-%		    code below.  Instead we need to keep original HLDS.
+%		away the dead procedures.  If we're optimizing, then
+%		it would be nice if we could keep the HLDS that results.
+%		However, because this pass gets run before type
+%		specialization, dead code elimination at this point
+%		incorrectly optimizes away procedures created for
+%		`pragma type_spec' declarations.  So we can't use the
+%		code below.  Instead we need to keep original HLDS.
 %
 %		%%% globals__io_lookup_bool_option(optimize_dead_procs,
-%		%%% 	OptimizeDead),
-%		%%% ( { OptimizeDead = yes } ->
-%		%%% 	{ HLDS = HLDS1 }
+%		%%% 	OptimizeDead, !IO),
+%		%%% ( OptimizeDead = yes ->
+%		%%% 	!:HLDS = HLDS1
 %		%%% ;
-%		%%% 	{ HLDS = HLDS0 }
+%		%%% 	true
 %		%%% )
-		{ HLDS = HLDS0 }
 	;
-		{ HLDS = HLDS0 }
+		true
 	).
 
-:- pred mercury_compile__simplify(module_info, bool, bool, bool, bool,
-	pred(task, module_info, module_info, io__state, io__state), 
-	module_info, io__state, io__state).
-:- mode mercury_compile__simplify(in, in, in, in, in, 
-	pred(task, in, out, di, uo) is det, out, di, uo) is det.
-
-mercury_compile__simplify(HLDS0, Warn, Once, Verbose, Stats, Process, HLDS) -->
-	maybe_write_string(Verbose, "% Simplifying goals...\n"),
-	maybe_flush_output(Verbose),
-	globals__io_get_globals(Globals),
-	{ simplify__find_simplifications(Warn, Globals, Simplifications0) },
-	( { Once = yes } ->
-		{ Simplifications = [do_once | Simplifications0] }
+:- pred mercury_compile__simplify(bool::in, bool::in, bool::in, bool::in,
+	pred(task, module_info, module_info, io, io)::in(pred(task, in, out,
+	di, uo) is det), module_info::in, module_info::out, io::di, io::uo)
+	is det.
+
+mercury_compile__simplify(Warn, Once, Verbose, Stats, Process, !HLDS, !IO) :-
+	maybe_write_string(Verbose, "% Simplifying goals...\n", !IO),
+	maybe_flush_output(Verbose, !IO),
+	globals__io_get_globals(Globals, !IO),
+	simplify__find_simplifications(Warn, Globals, Simplifications0),
+	( Once = yes ->
+		Simplifications = [do_once | Simplifications0]
 	;
-		{ Simplifications = Simplifications0 }
+		Simplifications = Simplifications0
 	),
 	call(Process, update_pred_error(simplify__pred(Simplifications)),
-		HLDS0, HLDS),
-	maybe_write_string(Verbose, "% done.\n"),
-	maybe_report_stats(Stats).
+		!HLDS, !IO),
+	maybe_write_string(Verbose, "% done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__maybe_mark_static_terms(module_info, bool, bool,
-		module_info, io__state, io__state).
-:- mode mercury_compile__maybe_mark_static_terms(in, in, in, out, di, uo)
-		is det.
-
-mercury_compile__maybe_mark_static_terms(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(static_ground_terms, StaticGroundTerms),
-	( { StaticGroundTerms = yes } ->
+:- pred mercury_compile__maybe_mark_static_terms(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_mark_static_terms(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(static_ground_terms, StaticGroundTerms,
+		!IO),
+	( StaticGroundTerms = yes ->
 		maybe_write_string(Verbose,
-			"% Marking static ground terms...\n"),
-		maybe_flush_output(Verbose),
+			"% Marking static ground terms...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_procs(update_proc(mark_static_terms),
-			HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+			!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS = HLDS0 }
+		true
 	).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__maybe_add_trail_ops(module_info, bool, bool,
-		module_info, io__state, io__state).
-:- mode mercury_compile__maybe_add_trail_ops(in, in, in, out, di, uo)
-		is det.
-
-mercury_compile__maybe_add_trail_ops(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(use_trail, UseTrail),
-	( { UseTrail = yes } ->
+:- pred mercury_compile__maybe_add_trail_ops(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_add_trail_ops(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(use_trail, UseTrail, !IO),
+	( UseTrail = yes ->
 		maybe_write_string(Verbose,
-			"% Adding trailing operations...\n"),
-		maybe_flush_output(Verbose),
+			"% Adding trailing operations...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_procs(update_proc(add_trail_ops),
-			HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+			!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS = HLDS0 }
+		true
 	).
 
-:- pred mercury_compile__maybe_add_heap_ops(module_info, bool, bool,
-		module_info, io__state, io__state).
-:- mode mercury_compile__maybe_add_heap_ops(in, in, in, out, di, uo)
-		is det.
+:- pred mercury_compile__maybe_add_heap_ops(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_add_heap_ops(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_get_gc_method(GC),
+mercury_compile__maybe_add_heap_ops(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_get_gc_method(GC, !IO),
 	globals__io_lookup_bool_option(reclaim_heap_on_semidet_failure,
-		SemidetReclaim),
+		SemidetReclaim, !IO),
 	globals__io_lookup_bool_option(reclaim_heap_on_nondet_failure,
-		NondetReclaim),
-	( { gc_is_conservative(GC) = yes } ->
+		NondetReclaim, !IO),
+	(
+		gc_is_conservative(GC) = yes
+	->
 		% we can't do heap reclamation with conservative GC
-		{ HLDS = HLDS0 }
-	; { SemidetReclaim = no, NondetReclaim = no } ->
-		{ HLDS = HLDS0 }
-	; { SemidetReclaim = yes, NondetReclaim = yes } ->
+		true
+	;
+		SemidetReclaim = no,
+		NondetReclaim = no
+	->
+		true
+	;
+		SemidetReclaim = yes,
+		NondetReclaim = yes
+	->
 		maybe_write_string(Verbose,
-			"% Adding heap reclamation operations...\n"),
-		maybe_flush_output(Verbose),
+			"% Adding heap reclamation operations...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_procs(update_proc(add_heap_ops),
-			HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
-	;
-		io__write_strings([
-			"Sorry, not implemented: `--high-level-code' and\n",
-			"`--(no-)reclaim-heap-on-{semidet/nondet}-failure'.\n",
-			"Use `--(no-)reclaim-heap-on-failure' instead.\n"
-		]),
-		io__set_exit_status(1),
-		{ HLDS = HLDS0 }
+			!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		Msg = "Sorry, not implemented: `--high-level-code' and " ++
+			"just one of " ++
+			"`--reclaim-heap-on-semidet-failure' and " ++
+			"`--reclaim-heap-on-nondet-failure'. " ++
+			"Use `--(no-)reclaim-heap-on-failure' instead.",
+		write_error_pieces_plain([words(Msg)], !IO),
+		io__set_exit_status(1, !IO)
 	).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__maybe_write_dependency_graph(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_write_dependency_graph(in, in, in, out, di, uo)
-	is det.
+:- pred mercury_compile__maybe_write_dependency_graph(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_write_dependency_graph(ModuleInfo0, Verbose, Stats,
-		ModuleInfo) -->
-	globals__io_lookup_bool_option(show_dependency_graph, ShowDepGraph),
-	( { ShowDepGraph = yes } ->
-		maybe_write_string(Verbose, "% Writing dependency graph..."),
-		{ module_info_name(ModuleInfo0, ModuleName) },
+mercury_compile__maybe_write_dependency_graph(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(show_dependency_graph, ShowDepGraph,
+		!IO),
+	( ShowDepGraph = yes ->
+		maybe_write_string(Verbose,
+			"% Writing dependency graph...", !IO),
+		module_info_name(!.HLDS, ModuleName),
 		module_name_to_file_name(ModuleName, ".dependency_graph", yes,
-			FileName),
-		io__open_output(FileName, Res),
-		( { Res = ok(FileStream) } ->
-			io__set_output_stream(FileStream, OutputStream),
-			dependency_graph__write_dependency_graph(ModuleInfo0,
-							ModuleInfo),
-			io__set_output_stream(OutputStream, _),
-			io__close_output(FileStream),
-			maybe_write_string(Verbose, " done.\n")
+			FileName, !IO),
+		io__open_output(FileName, Res, !IO),
+		( Res = ok(FileStream) ->
+			io__set_output_stream(FileStream, OutputStream, !IO),
+			dependency_graph__write_dependency_graph(!HLDS, !IO),
+			io__set_output_stream(OutputStream, _, !IO),
+			io__close_output(FileStream, !IO),
+			maybe_write_string(Verbose, " done.\n", !IO)
 		;
-			report_error("unable to write dependency graph."),
-			{ ModuleInfo0 = ModuleInfo }
+			report_error("unable to write dependency graph.", !IO)
 		),
-		maybe_report_stats(Stats)
+		maybe_report_stats(Stats, !IO)
 	;
-		{ ModuleInfo0 = ModuleInfo }
+		true
 	).
 
 	% Outputs the file <module_name>.prof, which contains the static
 	% call graph in terms of label names, if the profiling flag is enabled.
 
-:- pred mercury_compile__maybe_output_prof_call_graph(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_output_prof_call_graph(in, in, in, out, di, uo)
-	is det.
+:- pred mercury_compile__maybe_output_prof_call_graph(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_output_prof_call_graph(ModuleInfo0, Verbose, Stats,
-		ModuleInfo) -->
-	globals__io_lookup_bool_option(profile_calls, ProfileCalls),
-	globals__io_lookup_bool_option(profile_time, ProfileTime),
+mercury_compile__maybe_output_prof_call_graph(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(profile_calls, ProfileCalls, !IO),
+	globals__io_lookup_bool_option(profile_time, ProfileTime, !IO),
 	(
-		{ ProfileCalls = yes ; ProfileTime = yes }
+		( ProfileCalls = yes
+		; ProfileTime = yes
+		)
 	->
-		maybe_write_string(Verbose, "% Outputing profiling call graph..."),
-		maybe_flush_output(Verbose),
-		{ module_info_name(ModuleInfo0, ModuleName) },
+		maybe_write_string(Verbose,
+			"% Outputing profiling call graph...", !IO),
+		maybe_flush_output(Verbose, !IO),
+		module_info_name(!.HLDS, ModuleName),
 		module_name_to_file_name(ModuleName, ".prof", yes,
-						ProfFileName),
-		io__open_output(ProfFileName, Res),
-		(
-			{ Res = ok(FileStream) }
-		->
-			io__set_output_stream(FileStream, OutputStream),
-			dependency_graph__write_prof_dependency_graph(
-						ModuleInfo0, ModuleInfo),
-			io__set_output_stream(OutputStream, _),
-			io__close_output(FileStream)
+			ProfFileName, !IO),
+		io__open_output(ProfFileName, Res, !IO),
+		( Res = ok(FileStream) ->
+			io__set_output_stream(FileStream, OutputStream, !IO),
+			dependency_graph__write_prof_dependency_graph(!HLDS,
+				!IO),
+			io__set_output_stream(OutputStream, _, !IO),
+			io__close_output(FileStream, !IO)
 		;
-			report_error("unable to write profiling static call graph."),
-			{ ModuleInfo = ModuleInfo0 }
+			report_error("unable to write profiling " ++
+				"static call graph.", !IO)
 		),
-		maybe_write_string(Verbose, " done.\n"),
-		maybe_report_stats(Stats)
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ ModuleInfo = ModuleInfo0 }
+		true
 	).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__maybe_generate_schemas(module_info, bool,
-		io__state, io__state).
-:- mode mercury_compile__maybe_generate_schemas(in, in, di, uo) is det.
-
-mercury_compile__maybe_generate_schemas(ModuleInfo, Verbose) -->
-	globals__io_lookup_bool_option(generate_schemas, Generate),
-	( { Generate = yes } ->
-		maybe_write_string(Verbose, "% Writing schema file..."),
-		rl_out__generate_schema_file(ModuleInfo),
-		maybe_write_string(Verbose, " done.\n")
+:- pred mercury_compile__maybe_generate_schemas(module_info::in,
+	bool::in, bool::in, io::di, io::uo) is det.
+
+mercury_compile__maybe_generate_schemas(ModuleInfo, Verbose, Stats, !IO) :-
+	globals__io_lookup_bool_option(generate_schemas, Generate, !IO),
+	( Generate = yes ->
+		maybe_write_string(Verbose, "% Writing schema file...", !IO),
+		rl_out__generate_schema_file(ModuleInfo, !IO),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		[]
+		true
 	).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__tabling(module_info, bool, module_info,
-	io__state, io__state).
-:- mode mercury_compile__tabling(in, in, out, di, uo) is det.
+:- pred mercury_compile__tabling(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__tabling(HLDS0, Verbose, HLDS) -->
+mercury_compile__tabling(Verbose, Stats, !HLDS, !IO) :-
 	maybe_write_string(Verbose,
-		"% Transforming tabled predicates..."),
-	maybe_flush_output(Verbose),
-	table_gen__process_module(HLDS0, HLDS),
-	maybe_write_string(Verbose, " done.\n").
+		"% Transforming tabled predicates...", !IO),
+	maybe_flush_output(Verbose, !IO),
+	table_gen__process_module(!HLDS, !IO),
+	maybe_write_string(Verbose, " done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__process_lambdas(module_info, bool, module_info,
-	io__state, io__state).
-:- mode mercury_compile__process_lambdas(in, in, out, di, uo) is det.
+:- pred mercury_compile__process_lambdas(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__process_lambdas(HLDS0, Verbose, HLDS) -->
+mercury_compile__process_lambdas(Verbose, Stats, !HLDS, !IO) :-
 	maybe_write_string(Verbose,
-		"% Transforming lambda expressions..."),
-	maybe_flush_output(Verbose),
-	{ lambda__process_module(HLDS0, HLDS) },
-	maybe_write_string(Verbose, " done.\n").
+		"% Transforming lambda expressions...", !IO),
+	maybe_flush_output(Verbose, !IO),
+	lambda__process_module(!HLDS),
+	maybe_write_string(Verbose, " done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__expand_equiv_types_hlds(module_info, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__expand_equiv_types_hlds(in, in, out, di, uo) is det.
+:- pred mercury_compile__expand_equiv_types_hlds(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__expand_equiv_types_hlds(HLDS0, Verbose, HLDS) -->
+mercury_compile__expand_equiv_types_hlds(Verbose, Stats, !HLDS, !IO) :-
 	maybe_write_string(Verbose,
-		"% Fully expanding equivalence types..."),
-	maybe_flush_output(Verbose),
-	{ equiv_type_hlds__replace_in_hlds(HLDS0, HLDS) },
-	maybe_write_string(Verbose, " done.\n").
+		"% Fully expanding equivalence types...", !IO),
+	maybe_flush_output(Verbose, !IO),
+	equiv_type_hlds__replace_in_hlds(!HLDS),
+	maybe_write_string(Verbose, " done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
 
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__maybe_polymorphism(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_polymorphism(in, in, in, out, di, uo) is det.
-
-mercury_compile__maybe_polymorphism(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(polymorphism, Polymorphism),
-	( { Polymorphism = yes } ->
-		maybe_write_string(Verbose,
-			"% Transforming polymorphic unifications..."),
-		maybe_flush_output(Verbose),
-		polymorphism__process_module(HLDS0, HLDS),
-		maybe_write_string(Verbose, " done.\n"),
-		maybe_report_stats(Stats)
+:- pred mercury_compile__maybe_polymorphism(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_polymorphism(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(polymorphism, Polymorphism, !IO),
+	( Polymorphism = yes ->
+		maybe_write_string(Verbose,
+			"% Transforming polymorphic unifications...", !IO),
+		maybe_flush_output(Verbose, !IO),
+		polymorphism__process_module(!HLDS, !IO),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
 		% The --no-polymorphism option really doesn't make much
 		% sense anymore, because the polymorphism pass is necessary
 		% for the proper mode analysis of code using existential
 		% types.
-		{ error("sorry, `--no-polymorphism' is no longer supported") }
+		error("sorry, `--no-polymorphism' is no longer supported")
 	).
 
-:- pred mercury_compile__maybe_type_ctor_infos(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_type_ctor_infos(in, in, in, out, di, uo) is det.
+:- pred mercury_compile__maybe_type_ctor_infos(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_type_ctor_infos(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(type_ctor_info, TypeCtorInfoOption),
-	( 
-		{ TypeCtorInfoOption = yes } 
-	->
+mercury_compile__maybe_type_ctor_infos(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(type_ctor_info, TypeCtorInfo, !IO),
+	( TypeCtorInfo = yes ->
 		maybe_write_string(Verbose,
-			"% Generating type_ctor_info structures..."),
-		maybe_flush_output(Verbose),
-		{ type_ctor_info__generate_hlds(HLDS0, HLDS) },
-		maybe_write_string(Verbose, " done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ HLDS0 = HLDS }
-	).
-
-:- pred mercury_compile__maybe_bytecodes(module_info, module_name, bool, bool,
-	io__state, io__state).
-:- mode mercury_compile__maybe_bytecodes(in, in, in, in, di, uo) is det.
-
-mercury_compile__maybe_bytecodes(HLDS0, ModuleName, Verbose, Stats) -->
-	globals__io_lookup_bool_option(generate_bytecode, GenBytecode),
-	( { GenBytecode = yes } ->
-		mercury_compile__map_args_to_regs(HLDS0, Verbose, Stats, HLDS1),
+			"% Generating type_ctor_info structures...", !IO),
+		maybe_flush_output(Verbose, !IO),
+		type_ctor_info__generate_hlds(!HLDS),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
+	).
+
+:- pred mercury_compile__maybe_bytecodes(module_info::in, module_name::in,
+	bool::in, bool::in, io::di, io::uo) is det.
+
+mercury_compile__maybe_bytecodes(HLDS0, ModuleName, Verbose, Stats, !IO) :-
+	globals__io_lookup_bool_option(generate_bytecode, GenBytecode, !IO),
+	( GenBytecode = yes ->
+		mercury_compile__map_args_to_regs(Verbose, Stats, HLDS0, HLDS1,
+			!IO),
 		mercury_compile__maybe_dump_hlds(HLDS1, "31",
-			"bytecode_args_to_regs"),
+			"bytecode_args_to_regs", !IO),
 		maybe_write_string(Verbose,
-			"% Generating bytecodes...\n"),
-		maybe_flush_output(Verbose),
-		bytecode_gen__module(HLDS1, Bytecode),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats),
+			"% Generating bytecodes...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		bytecode_gen__module(HLDS1, Bytecode, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO),
 		module_name_to_file_name(ModuleName, ".bytedebug", yes,
-			BytedebugFile),
+			BytedebugFile, !IO),
 		maybe_write_string(Verbose,
-			"% Writing bytecodes to `"),
-		maybe_write_string(Verbose, BytedebugFile),
-		maybe_write_string(Verbose, "'..."),
-		maybe_flush_output(Verbose),
-		debug_bytecode_file(BytedebugFile, Bytecode),
-		maybe_write_string(Verbose, " done.\n"),
-		module_name_to_file_name(ModuleName, ".mbc", yes, BytecodeFile),
-		maybe_write_string(Verbose,
-			"% Writing bytecodes to `"),
-		maybe_write_string(Verbose, BytecodeFile),
-		maybe_write_string(Verbose, "'..."),
-		maybe_flush_output(Verbose),
-		output_bytecode_file(BytecodeFile, Bytecode),
-		maybe_write_string(Verbose, " done.\n"),
-		maybe_report_stats(Stats)
-	;
-		[]
-	).
-
-:- pred mercury_compile__maybe_higher_order(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_higher_order(in, in, in, out, di, uo)
-	is det.
-
-mercury_compile__maybe_higher_order(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(optimize_higher_order, HigherOrder),
+			"% Writing bytecodes to `", !IO),
+		maybe_write_string(Verbose, BytedebugFile, !IO),
+		maybe_write_string(Verbose, "'...", !IO),
+		maybe_flush_output(Verbose, !IO),
+		debug_bytecode_file(BytedebugFile, Bytecode, !IO),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		module_name_to_file_name(ModuleName, ".mbc", yes,
+			BytecodeFile, !IO),
+		maybe_write_string(Verbose,
+			"% Writing bytecodes to `", !IO),
+		maybe_write_string(Verbose, BytecodeFile, !IO),
+		maybe_write_string(Verbose, "'...", !IO),
+		maybe_flush_output(Verbose, !IO),
+		output_bytecode_file(BytecodeFile, Bytecode, !IO),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
+	).
+
+:- pred mercury_compile__maybe_higher_order(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_higher_order(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(optimize_higher_order, HigherOrder,
+		!IO),
 	% --type-specialization implies --user-guided-type-specialization.
-	globals__io_lookup_bool_option(user_guided_type_specialization, Types),
+	globals__io_lookup_bool_option(user_guided_type_specialization, Types,
+		!IO),
 
 	% Always produce the specialized versions for which
 	% `:- pragma type_spec' declarations exist, because
 	% importing modules might call them.
-	{ module_info_type_spec_info(HLDS0, TypeSpecInfo) },
-	{ TypeSpecInfo = type_spec_info(TypeSpecPreds, _, _, _) },
-
-	( { HigherOrder = yes ; Types = yes ; \+ set__empty(TypeSpecPreds) } ->
+	module_info_type_spec_info(!.HLDS, TypeSpecInfo),
+	TypeSpecInfo = type_spec_info(TypeSpecPreds, _, _, _),
+	(
+		( HigherOrder = yes
+		; Types = yes
+		; \+ set__empty(TypeSpecPreds)
+		)
+	->
 		maybe_write_string(Verbose,
-		"% Specializing higher-order and polymorphic predicates...\n"),
-		maybe_flush_output(Verbose),
-		
-		specialize_higher_order(HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+			"% Specializing higher-order and " ++
+			"polymorphic predicates...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+
+		specialize_higher_order(!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS0 = HLDS }
+		true
 	).
 
-:- pred mercury_compile__maybe_do_inlining(module_info, bool, bool, module_info,
-	io__state, io__state).
-:- mode mercury_compile__maybe_do_inlining(in, in, in, out, di, uo) is det.
+:- pred mercury_compile__maybe_do_inlining(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_do_inlining(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(inline_simple, Simple),
-	globals__io_lookup_bool_option(inline_single_use, SingleUse),
-	globals__io_lookup_int_option(inline_compound_threshold, Threshold),
+mercury_compile__maybe_do_inlining(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(inline_simple, Simple, !IO),
+	globals__io_lookup_bool_option(inline_single_use, SingleUse, !IO),
+	globals__io_lookup_int_option(inline_compound_threshold, Threshold,
+		!IO),
 	(
-		{ Simple = yes ; SingleUse = yes ; Threshold > 0 }
+		( Simple = yes
+		; SingleUse = yes
+		; Threshold > 0
+		)
 	->
-		maybe_write_string(Verbose, "% Inlining...\n"),
-		maybe_flush_output(Verbose),
-		inlining(HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+		maybe_write_string(Verbose, "% Inlining...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		inlining(!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS = HLDS0 }
+		true
 	).
 
-:- pred mercury_compile__maybe_deforestation(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_deforestation(in, in, in, out, di, uo) is det.
+:- pred mercury_compile__maybe_deforestation(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_deforestation(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(deforestation, Deforest),
+mercury_compile__maybe_deforestation(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(deforestation, Deforest, !IO),
 
 	% --constraint-propagation implies --local-constraint-propagation.
 	globals__io_lookup_bool_option(local_constraint_propagation,
-		Constraints),
-	( { Deforest = yes ; Constraints = yes } ->
-		{ Deforest = no, Constraints = no, 
+		Constraints, !IO),
+	(
+		( Deforest = yes
+		; Constraints = yes
+		)
+	->
+		(
+			Deforest = no,
+			Constraints = no,
 			error("mercury_compile__maybe_deforestation")
-		; Deforest = yes, Constraints = yes,
+		;
+			Deforest = yes,
+			Constraints = yes,
 			Msg = "% Deforestation and constraint propagation...\n"
-		; Deforest = yes, Constraints = no,
+		;
+			Deforest = yes,
+			Constraints = no,
 			Msg = "% Deforestation...\n"
-		; Deforest = no, Constraints = yes,
+		;
+			Deforest = no,
+			Constraints = yes,
 			Msg = "% Constraint propagation...\n"
-		},
-		maybe_write_string(Verbose, Msg),
-		maybe_flush_output(Verbose),
-		deforestation(HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ HLDS0 = HLDS }
-	).
-
-:- pred mercury_compile__maybe_transform_dnf(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_transform_dnf(in, in, in, out, di, uo) is det.
-
-mercury_compile__maybe_transform_dnf(HLDS0, Verbose, Stats, HLDS) -->
-	{ module_info_get_do_aditi_compilation(HLDS0, Aditi) },
-	( { Aditi = do_aditi_compilation } ->
-		maybe_write_string(Verbose, "% Disjunctive normal form transformation..."),
-		maybe_flush_output(Verbose),
-		{ module_info_predids(HLDS0, PredIds) },
-		{ set__init(AditiPreds0) },
-		{ list__foldl(add_aditi_procs(HLDS0),
-			PredIds, AditiPreds0, AditiPreds) },
-		{ dnf__transform_module(HLDS0, no, yes(AditiPreds), HLDS) },
-		maybe_write_string(Verbose, " done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ HLDS0 = HLDS }
-	).
-	
-:- pred add_aditi_procs(module_info, pred_id, 
-		set(pred_proc_id), set(pred_proc_id)).
-:- mode add_aditi_procs(in, in, in, out) is det.
+		),
+		maybe_write_string(Verbose, Msg, !IO),
+		maybe_flush_output(Verbose, !IO),
+		deforestation(!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
+	).
+
+:- pred mercury_compile__maybe_transform_dnf(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_transform_dnf(Verbose, Stats, !HLDS, !IO) :-
+	module_info_get_do_aditi_compilation(!.HLDS, Aditi),
+	( Aditi = do_aditi_compilation ->
+		maybe_write_string(Verbose,
+			"% Disjunctive normal form transformation...", !IO),
+		maybe_flush_output(Verbose, !IO),
+		module_info_predids(!.HLDS, PredIds),
+		set__init(AditiPreds0),
+		list__foldl(add_aditi_procs(!.HLDS),
+			PredIds, AditiPreds0, AditiPreds),
+		dnf__transform_module(no, yes(AditiPreds), !HLDS),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
+	).
+
+:- pred add_aditi_procs(module_info::in, pred_id::in,
+	set(pred_proc_id)::in, set(pred_proc_id)::out) is det.
 
 add_aditi_procs(HLDS0, PredId, AditiPreds0, AditiPreds) :-
 	module_info_pred_info(HLDS0, PredId, PredInfo),
@@ -3164,129 +3211,133 @@
 		AditiPreds = AditiPreds0
 	).
 
-:- pred mercury_compile__maybe_loop_inv(module_info::in,
-	bool::in, bool::in, module_info::out, io__state::di, io__state::uo)
-	is det.
-
-mercury_compile__maybe_loop_inv(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(loop_invariants, LoopInv),
-	( { LoopInv = yes } ->
+:- pred mercury_compile__maybe_loop_inv(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
+mercury_compile__maybe_loop_inv(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(loop_invariants, LoopInv, !IO),
+	( LoopInv = yes ->
 			% We run the mark_static pass because we need
 			% the construct_how flag to be valid.
 			%
-		mercury_compile__maybe_mark_static_terms(HLDS0, Verbose, Stats,
-			HLDS1),
-		mercury_compile__maybe_dump_hlds(HLDS1, "35", "mark_static"),
+		mercury_compile__maybe_mark_static_terms(Verbose, Stats,
+			!HLDS, !IO),
+		mercury_compile__maybe_dump_hlds(!.HLDS, "35", "mark_static",
+			!IO),
 
 		maybe_write_string(Verbose,
-			"% Hoisting loop invariants...\n"),
-		maybe_flush_output(Verbose),
+			"% Hoisting loop invariants...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_procs(
 			update_module(hoist_loop_invariants),
-			HLDS1, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+			!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS0 = HLDS }
+		true
 	).
 
-:- pred mercury_compile__maybe_delay_construct(module_info::in,
-	bool::in, bool::in, module_info::out, io__state::di, io__state::uo)
-	is det.
+:- pred mercury_compile__maybe_delay_construct(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_delay_construct(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(delay_construct, DelayConstruct),
-	( { DelayConstruct = yes } ->
+mercury_compile__maybe_delay_construct(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(delay_construct, DelayConstruct, !IO),
+	( DelayConstruct = yes ->
 		maybe_write_string(Verbose,
-			"% Delaying construction unifications ...\n"),
-		maybe_flush_output(Verbose),
+			"% Delaying construction unifications ...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_procs(
 			update_proc_io(delay_construct_proc),
-			HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ HLDS0 = HLDS }
-	).
-
-:- pred mercury_compile__maybe_unused_args(module_info, bool, bool, module_info,
-	io__state, io__state).
-:- mode mercury_compile__maybe_unused_args(in, in, in, out, di, uo) is det.
-
-mercury_compile__maybe_unused_args(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(intermod_unused_args, Intermod),
-	globals__io_lookup_bool_option(optimize_unused_args, Optimize),
-	globals__io_lookup_bool_option(warn_unused_args, Warn),
-	( { Optimize = yes; Warn = yes ; Intermod = yes } ->
-		maybe_write_string(Verbose, "% Finding unused arguments ...\n"),
-		maybe_flush_output(Verbose),
-		unused_args__process_module(HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ HLDS0 = HLDS }
-	).
-
-:- pred mercury_compile__maybe_unneeded_code(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_unneeded_code(in, in, in, out, di, uo) is det.
-
-mercury_compile__maybe_unneeded_code(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(unneeded_code, UnneededCode),
-	( { UnneededCode = yes } ->
-		maybe_write_string(Verbose, "% Removing unneeded code from procedure bodies...\n"),
-		maybe_flush_output(Verbose),
-		process_all_nonimported_procs(
-			update_module_io(unneeded_code__process_proc_msg),
-			HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+			!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS0 = HLDS }
+		true
 	).
 
-:- pred mercury_compile__maybe_magic(module_info, bool, bool,
-		module_info, io__state, io__state).
-:- mode mercury_compile__maybe_magic(in, in, in, out, di, uo) is det.
+:- pred mercury_compile__maybe_unused_args(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_magic(HLDS0, Verbose, Stats, HLDS) -->
-	{ module_info_get_do_aditi_compilation(HLDS0, Aditi) },
-	( { Aditi = do_aditi_compilation } ->
-		maybe_write_string(Verbose, "% Supplementary magic sets transformation..."),
-		maybe_flush_output(Verbose),
-		magic__process_module(HLDS0, HLDS),
-		maybe_report_stats(Stats)
+mercury_compile__maybe_unused_args(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_get_globals(Globals, !IO),
+	globals__lookup_bool_option(Globals, intermod_unused_args, Intermod),
+	globals__lookup_bool_option(Globals, optimize_unused_args, Optimize),
+	globals__lookup_bool_option(Globals, warn_unused_args, Warn),
+	(
+		( Optimize = yes
+		; Warn = yes
+		; Intermod = yes
+		)
+	->
+		maybe_write_string(Verbose,
+			"% Finding unused arguments ...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		unused_args__process_module(!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS0 = HLDS }
+		true
 	).
 
-:- pred mercury_compile__maybe_eliminate_dead_procs(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_eliminate_dead_procs(in, in, in, out, di, uo)
-	is det.
+:- pred mercury_compile__maybe_unneeded_code(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_eliminate_dead_procs(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(optimize_dead_procs, Dead),
-	( { Dead = yes } ->
+mercury_compile__maybe_unneeded_code(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(unneeded_code, UnneededCode, !IO),
+	( UnneededCode = yes ->
 		maybe_write_string(Verbose,
-			"% Eliminating dead procedures...\n"),
-		maybe_flush_output(Verbose),
-		dead_proc_elim(final_optimization_pass, HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+			"% Removing unneeded code from procedure bodies...\n",
+			!IO),
+		maybe_flush_output(Verbose, !IO),
+		process_all_nonimported_procs(
+			update_module_io(unneeded_code__process_proc_msg),
+			!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS0 = HLDS }
+		true
 	).
 
-:- pred mercury_compile__maybe_term_size_prof(module_info::in,
-	bool::in, bool::in, module_info::out, io__state::di, io__state::uo)
-	is det.
+:- pred mercury_compile__maybe_magic(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_magic(Verbose, Stats, !HLDS, !IO) :-
+	module_info_get_do_aditi_compilation(!.HLDS, Aditi),
+	( Aditi = do_aditi_compilation ->
+		maybe_write_string(Verbose,
+			"% Supplementary magic sets transformation...", !IO),
+		maybe_flush_output(Verbose, !IO),
+		magic__process_module(!HLDS, !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
+	).
 
-mercury_compile__maybe_term_size_prof(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(record_term_sizes_as_words, AsWords),
-	globals__io_lookup_bool_option(record_term_sizes_as_cells, AsCells),
-	{
+:- pred mercury_compile__maybe_eliminate_dead_procs(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_eliminate_dead_procs(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(optimize_dead_procs, Dead, !IO),
+	( Dead = yes ->
+		maybe_write_string(Verbose,
+			"% Eliminating dead procedures...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		dead_proc_elim(final_optimization_pass, !HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
+	).
+
+:- pred mercury_compile__maybe_term_size_prof(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_term_size_prof(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(record_term_sizes_as_words, AsWords,
+		!IO),
+	globals__io_lookup_bool_option(record_term_sizes_as_cells, AsCells,
+		!IO),
+	(
 		AsWords = yes,
 		AsCells = yes,
 		error("mercury_compile__maybe_term_size_prof: "
@@ -3303,273 +3354,258 @@
 		AsWords = no,
 		AsCells = no,
 		MaybeTransform = no
-	},
+	),
 	(
-		{ MaybeTransform = yes(Transform) },
+		MaybeTransform = yes(Transform),
 		maybe_write_string(Verbose,
-			"% Applying term size profiling transformation...\n"),
-		maybe_flush_output(Verbose),
+			"% Applying term size profiling transformation...\n",
+			!IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_nonaditi_procs(
 			update_module_io(
 				size_prof__process_proc_msg(Transform)),
-			HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+			!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ MaybeTransform = no },
-		{ HLDS0 = HLDS }
+		MaybeTransform = no
 	).
 
-:- pred mercury_compile__maybe_deep_profiling(module_info, bool, bool,
-	module_info, list(layout_data), io__state, io__state).
-:- mode mercury_compile__maybe_deep_profiling(in, in, in, out, out, di, uo)
-	is det.
-
-mercury_compile__maybe_deep_profiling(HLDS0, Verbose, Stats, HLDS,
-		DeepProfilingStructures) -->
-	globals__io_lookup_bool_option(profile_deep, Dead),
-	( { Dead = yes } ->
-		maybe_write_string(Verbose,
-			"% Applying deep profiling transformation...\n"),
-		maybe_flush_output(Verbose),
-		apply_deep_profiling_transformation(HLDS0, HLDS,
-			DeepProfilingStructures),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ HLDS0 = HLDS },
-		{ DeepProfilingStructures = [] }
-	).
-
-:- pred mercury_compile__maybe_introduce_accumulators(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_introduce_accumulators(in, in, in, out, di, uo)
-	is det.
-
-mercury_compile__maybe_introduce_accumulators(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(introduce_accumulators, Optimize),
-	( { Optimize = yes } ->
+:- pred mercury_compile__maybe_deep_profiling(bool::in, bool::in,
+	module_info::in, module_info::out, list(layout_data)::out,
+	io::di, io::uo) is det.
+
+mercury_compile__maybe_deep_profiling(Verbose, Stats, !HLDS,
+		DeepProfStructs, !IO) :-
+	globals__io_lookup_bool_option(profile_deep, Dead, !IO),
+	( Dead = yes ->
+		maybe_write_string(Verbose,
+			"% Applying deep profiling transformation...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		apply_deep_profiling_transformation(!HLDS, DeepProfStructs,
+			!IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		DeepProfStructs = []
+	).
+
+:- pred mercury_compile__maybe_introduce_accumulators(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_introduce_accumulators(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(introduce_accumulators, Optimize, !IO),
+	( Optimize = yes ->
 		maybe_write_string(Verbose,
-				"% Attempting to introduce accumulators...\n"),
-		maybe_flush_output(Verbose),
+			"% Attempting to introduce accumulators...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_procs(
 			update_module_io(accumulator__process_proc),
-			HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+			!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS0 = HLDS }
+		true
 	).
 
+:- pred mercury_compile__maybe_lco(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-:- pred mercury_compile__maybe_lco(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_lco(in, in, in, out, di, uo)
-	is det.
-
-mercury_compile__maybe_lco(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(optimize_constructor_last_call, LCO),
-	( { LCO = yes } ->
-		maybe_write_string(Verbose, "% Looking for LCO modulo constructor application ...\n"),
-		maybe_flush_output(Verbose),
+mercury_compile__maybe_lco(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(optimize_constructor_last_call, LCO,
+		!IO),
+	( LCO = yes ->
+		maybe_write_string(Verbose,
+			"% Looking for LCO modulo " ++
+			"constructor application ...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_nonaditi_procs(
-			update_proc_io(lco_modulo_constructors), HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ HLDS0 = HLDS }
-	).
-
-:- pred mercury_compile__maybe_transform_aditi_builtins(module_info,
-	bool, bool, module_info, io__state, io__state).
-:- mode mercury_compile__maybe_transform_aditi_builtins(in, in, in, out,
-	di, uo) is det.
-
-mercury_compile__maybe_transform_aditi_builtins(HLDS0,
-		Verbose, Stats, HLDS) -->
-	{ module_info_get_do_aditi_compilation(HLDS0, Aditi) },
-	( { Aditi = do_aditi_compilation } ->
-		maybe_write_string(Verbose,
-			"% Transforming away RL builtins...\n"),
-		maybe_flush_output(Verbose),
-		transform_aditi_builtins(HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-                maybe_report_stats(Stats)
+			update_proc_io(lco_modulo_constructors), !HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS0 = HLDS }
+		true
+	).
+
+:- pred mercury_compile__maybe_transform_aditi_builtins(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_transform_aditi_builtins(Verbose, Stats, !HLDS, !IO) :-
+	module_info_get_do_aditi_compilation(!.HLDS, Aditi),
+	( Aditi = do_aditi_compilation ->
+		maybe_write_string(Verbose,
+			"% Transforming away RL builtins...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		transform_aditi_builtins(!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
 	).
 
 %-----------------------------------------------------------------------------%
 
 % The backend passes
 
-:- pred mercury_compile__map_args_to_regs(module_info, bool, bool, module_info,
-	io__state, io__state).
-:- mode mercury_compile__map_args_to_regs(in, in, in, out, di, uo) is det.
-
-mercury_compile__map_args_to_regs(HLDS0, Verbose, Stats, HLDS) -->
-	maybe_write_string(Verbose, "% Mapping args to regs..."),
-	maybe_flush_output(Verbose),
-	{ generate_arg_info(HLDS0, HLDS) },
-	maybe_write_string(Verbose, " done.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__maybe_saved_vars(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_saved_vars(in, in, in, out, di, uo)
-	is det.
+:- pred mercury_compile__map_args_to_regs(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_saved_vars(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(optimize_saved_vars_const, SavedVars),
-	( { SavedVars = yes } ->
+mercury_compile__map_args_to_regs(Verbose, Stats, !HLDS, !IO) :-
+	maybe_write_string(Verbose, "% Mapping args to regs...", !IO),
+	maybe_flush_output(Verbose, !IO),
+	generate_arg_info(!HLDS),
+	maybe_write_string(Verbose, " done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__maybe_saved_vars(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_saved_vars(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(optimize_saved_vars_const, SavedVars,
+		!IO),
+	( SavedVars = yes ->
 		maybe_write_string(Verbose,
-			"% Minimizing variable saves using constants...\n"),
-		maybe_flush_output(Verbose),
-		process_all_nonimported_procs(update_module_io(
-			saved_vars_proc), HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
+			"% Minimizing variable saves using constants...\n",
+			!IO),
+		maybe_flush_output(Verbose, !IO),
+		process_all_nonimported_procs(
+			update_module_io(saved_vars_proc), !HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS0 = HLDS }
+		true
 	).
 
-:- pred mercury_compile__maybe_stack_opt(module_info::in, bool::in, bool::in,
-	module_info::out, io__state::di, io__state::uo) is det.
-
-mercury_compile__maybe_stack_opt(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(optimize_saved_vars_cell, SavedVars),
-	( { SavedVars = yes } ->
-		maybe_write_string(Verbose,
-			"% Minimizing variable saves using cells...\n"),
-		maybe_flush_output(Verbose),
-		process_all_nonimported_procs(update_module_io(
-			stack_opt_cell), HLDS0, HLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ HLDS0 = HLDS }
-	).
-
-:- pred mercury_compile__maybe_followcode(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_followcode(in, in, in, out, di, uo)
-	is det.
+:- pred mercury_compile__maybe_stack_opt(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_followcode(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_lookup_bool_option(follow_code, FollowCode),
-	globals__io_lookup_bool_option(prev_code, PrevCode),
-	( { FollowCode = yes ; PrevCode = yes } ->
-		maybe_write_string(Verbose, "% Migrating branch code..."),
-		maybe_flush_output(Verbose),
+mercury_compile__maybe_stack_opt(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(optimize_saved_vars_cell, SavedVars,
+		!IO),
+	( SavedVars = yes ->
+		maybe_write_string(Verbose,
+			"% Minimizing variable saves using cells...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		process_all_nonimported_procs(update_module_io(stack_opt_cell),
+			!HLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
+	).
+
+:- pred mercury_compile__maybe_followcode(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_followcode(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_lookup_bool_option(follow_code, FollowCode, !IO),
+	globals__io_lookup_bool_option(prev_code, PrevCode, !IO),
+	(
+		( FollowCode = yes
+		; PrevCode = yes
+		)
+	->
+		maybe_write_string(Verbose, "% Migrating branch code...", !IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_nonaditi_procs(update_module(
-			move_follow_code_in_proc), HLDS0, HLDS),
-		maybe_write_string(Verbose, " done.\n"),
-		maybe_report_stats(Stats)
+			move_follow_code_in_proc), !HLDS, !IO),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS0 = HLDS }
+		true
 	).
 
-:- pred mercury_compile__compute_liveness(module_info, bool, bool, module_info,
-	io__state, io__state).
-:- mode mercury_compile__compute_liveness(in, in, in, out, di, uo) is det.
+:- pred mercury_compile__compute_liveness(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
 
-mercury_compile__compute_liveness(HLDS0, Verbose, Stats, HLDS) -->
-	maybe_write_string(Verbose, "% Computing liveness...\n"),
-	maybe_flush_output(Verbose),
+mercury_compile__compute_liveness(Verbose, Stats, !HLDS, !IO) :-
+	maybe_write_string(Verbose, "% Computing liveness...\n", !IO),
+	maybe_flush_output(Verbose, !IO),
 	process_all_nonimported_nonaditi_procs(
 		update_proc_io(detect_liveness_proc),
-		HLDS0, HLDS),
-	maybe_write_string(Verbose, "% done.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__compute_stack_vars(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__compute_stack_vars(in, in, in, out, di, uo) is det.
-
-mercury_compile__compute_stack_vars(HLDS0, Verbose, Stats, HLDS) -->
-	maybe_write_string(Verbose, "% Computing stack vars..."),
-	maybe_flush_output(Verbose),
+		!HLDS, !IO),
+	maybe_write_string(Verbose, "% done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__compute_stack_vars(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__compute_stack_vars(Verbose, Stats, !HLDS, !IO) :-
+	maybe_write_string(Verbose, "% Computing stack vars...", !IO),
+	maybe_flush_output(Verbose, !IO),
 	process_all_nonimported_nonaditi_procs(
-		update_proc_io(allocate_stack_slots_in_proc),
-		HLDS0, HLDS),
-	maybe_write_string(Verbose, " done.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__allocate_store_map(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__allocate_store_map(in, in, in, out, di, uo) is det.
-
-mercury_compile__allocate_store_map(HLDS0, Verbose, Stats, HLDS) -->
-	maybe_write_string(Verbose, "% Allocating store map..."),
-	maybe_flush_output(Verbose),
+		update_proc_io(allocate_stack_slots_in_proc), !HLDS, !IO),
+	maybe_write_string(Verbose, " done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__allocate_store_map(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__allocate_store_map(Verbose, Stats, !HLDS, !IO) :-
+	maybe_write_string(Verbose, "% Allocating store map...", !IO),
+	maybe_flush_output(Verbose, !IO),
 	process_all_nonimported_nonaditi_procs(
 		update_proc_predid(allocate_store_maps(final_allocation)),
-		HLDS0, HLDS),
-	maybe_write_string(Verbose, " done.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__maybe_goal_paths(module_info, bool, bool,
-	module_info, io__state, io__state).
-:- mode mercury_compile__maybe_goal_paths(in, in, in, out, di, uo) is det.
-
-mercury_compile__maybe_goal_paths(HLDS0, Verbose, Stats, HLDS) -->
-	globals__io_get_trace_level(TraceLevel),
-	( { given_trace_level_is_none(TraceLevel) = no } ->
-		maybe_write_string(Verbose, "% Calculating goal paths..."),
-		maybe_flush_output(Verbose),
+		!HLDS, !IO),
+	maybe_write_string(Verbose, " done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__maybe_goal_paths(bool::in, bool::in,
+	module_info::in, module_info::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_goal_paths(Verbose, Stats, !HLDS, !IO) :-
+	globals__io_get_trace_level(TraceLevel, !IO),
+	( given_trace_level_is_none(TraceLevel) = no ->
+		maybe_write_string(Verbose,
+			"% Calculating goal paths...", !IO),
+		maybe_flush_output(Verbose, !IO),
 		process_all_nonimported_procs(
-			update_proc(goal_path__fill_slots),
-			HLDS0, HLDS),
-		maybe_write_string(Verbose, " done.\n"),
-		maybe_report_stats(Stats)
+			update_proc(goal_path__fill_slots), !HLDS, !IO),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		true
+	).
+
+:- pred mercury_compile__generate_code(module_info::in, bool::in, bool::in,
+	global_data::in, global_data::out, list(c_procedure)::out,
+	io::di, io::uo) is det.
+
+mercury_compile__generate_code(HLDS, Verbose, Stats, !GlobalData, LLDS, !IO) :-
+	maybe_write_string(Verbose, "% Generating code...\n", !IO),
+	maybe_flush_output(Verbose, !IO),
+	generate_code(HLDS, !GlobalData, LLDS, !IO),
+	maybe_write_string(Verbose, "% done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__maybe_do_optimize(global_data::in, bool::in, bool::in,
+	list(c_procedure)::in, list(c_procedure)::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_do_optimize(GlobalData, Verbose, Stats, !LLDS, !IO) :-
+	globals__io_lookup_bool_option(optimize, Optimize, !IO),
+	( Optimize = yes ->
+		maybe_write_string(Verbose,
+			"% Doing optimizations...\n", !IO),
+		maybe_flush_output(Verbose, !IO),
+		optimize_main(GlobalData, !LLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
 	;
-		{ HLDS = HLDS0 }
+		true
 	).
 
-:- pred mercury_compile__generate_code(module_info, global_data, bool, bool,
-	global_data, list(c_procedure), io__state, io__state).
-:- mode mercury_compile__generate_code(in, in, in, in, out, out, di, uo)
-	is det.
-
-mercury_compile__generate_code(HLDS0, GlobalData0, Verbose, Stats,
-		GlobalData, LLDS) -->
-	maybe_write_string(Verbose, "% Generating code...\n"),
-	maybe_flush_output(Verbose),
-	generate_code(HLDS0, GlobalData0, GlobalData, LLDS),
-	maybe_write_string(Verbose, "% done.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__maybe_do_optimize(list(c_procedure), global_data,
-	bool, bool, list(c_procedure), io__state, io__state).
-:- mode mercury_compile__maybe_do_optimize(in, in, in, in, out, di, uo) is det.
-
-mercury_compile__maybe_do_optimize(LLDS0, GlobalData, Verbose, Stats, LLDS) -->
-	globals__io_lookup_bool_option(optimize, Optimize),
-	( { Optimize = yes } ->
-		maybe_write_string(Verbose,
-			"% Doing optimizations...\n"),
-		maybe_flush_output(Verbose),
-		optimize_main(LLDS0, GlobalData, LLDS),
-		maybe_write_string(Verbose, "% done.\n"),
-		maybe_report_stats(Stats)
-	;
-		{ LLDS = LLDS0 }
-	).
-
-:- pred mercury_compile__maybe_generate_stack_layouts(module_info, global_data,
-	list(c_procedure), bool, bool, global_data, io__state, io__state).
-:- mode mercury_compile__maybe_generate_stack_layouts(in, in, in, in, in, out, 
-	di, uo) is det.
+:- pred mercury_compile__maybe_generate_stack_layouts(module_info::in,
+	list(c_procedure)::in, bool::in, bool::in,
+	global_data::in, global_data::out, io::di, io::uo) is det.
 
-mercury_compile__maybe_generate_stack_layouts(ModuleInfo0, GlobalData0, LLDS0,
-		Verbose, Stats, GlobalData) -->
+mercury_compile__maybe_generate_stack_layouts(HLDS, LLDS, Verbose, Stats,
+		!GlobalData, !IO) :-
 	maybe_write_string(Verbose,
-		"% Generating call continuation information..."),
-	maybe_flush_output(Verbose),
-	{ continuation_info__maybe_process_llds(LLDS0, ModuleInfo0,
-		GlobalData0, GlobalData) },
-	maybe_write_string(Verbose, " done.\n"),
-	maybe_report_stats(Stats).
+		"% Generating call continuation information...", !IO),
+	maybe_flush_output(Verbose, !IO),
+	continuation_info__maybe_process_llds(LLDS, HLDS, !GlobalData),
+	maybe_write_string(Verbose, " done.\n", !IO),
+	maybe_report_stats(Stats, !IO).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
@@ -3577,25 +3613,24 @@
 %
 % Gather together the information from the HLDS, given the foreign
 % language we are going to use, that is used for the foreign language
-% interface.  
+% interface.
 % This stuff mostly just gets passed directly to the LLDS unchanged, but
 % we do do a bit of code generation -- for example, we call
 % export__get_foreign_export_{decls,defns} here, which do the generation
 % of C code for `pragma export' declarations.
 %
 
-:- pred get_c_interface_info(module_info, foreign_language, 
-		foreign_interface_info).
-:- mode get_c_interface_info(in, in, out) is det.
+:- pred get_c_interface_info(module_info::in, foreign_language::in,
+	foreign_interface_info::out) is det.
 
 get_c_interface_info(HLDS, UseForeignLanguage, Foreign_InterfaceInfo) :-
 	module_info_name(HLDS, ModuleName),
 	module_info_get_foreign_decl(HLDS, ForeignDecls),
 	module_info_get_foreign_import_module(HLDS, ForeignImports),
 	module_info_get_foreign_body_code(HLDS, ForeignBodyCode),
-	foreign__filter_decls(UseForeignLanguage, ForeignDecls, 
+	foreign__filter_decls(UseForeignLanguage, ForeignDecls,
 		WantedForeignDecls, _OtherDecls),
-	foreign__filter_imports(UseForeignLanguage, ForeignImports, 
+	foreign__filter_imports(UseForeignLanguage, ForeignImports,
 		WantedForeignImports, _OtherImports),
 	foreign__filter_bodys(UseForeignLanguage, ForeignBodyCode,
 		WantedForeignBodys, _OtherBodys),
@@ -3611,15 +3646,14 @@
 
 % The LLDS output pass
 
-:- pred mercury_compile__output_pass(module_info, global_data,
-	list(c_procedure), maybe(rl_file), module_name, bool,
-	io__state, io__state).
-:- mode mercury_compile__output_pass(in, in, in, in, in, out, di, uo) is det.
+:- pred mercury_compile__output_pass(module_info::in, global_data::in,
+	list(c_procedure)::in, maybe(rl_file)::in, module_name::in, bool::out,
+	io::di, io::uo) is det.
 
 mercury_compile__output_pass(HLDS, GlobalData0, Procs, MaybeRLFile,
-		ModuleName, CompileErrors) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
+		ModuleName, CompileErrors, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
 	%
 	% Here we generate the LLDS representations for
 	% various data structures used for RTTI, type classes,
@@ -3627,10 +3661,11 @@
 	% XXX this should perhaps be part of backend_pass
 	% rather than output_pass.
 	%
-	{ type_ctor_info__generate_rtti(HLDS, TypeCtorRttiData) },
-	{ base_typeclass_info__generate_rtti(HLDS, OldTypeClassInfoRttiData) },
-	globals__io_lookup_bool_option(new_type_class_rtti, NewTypeClassRtti),
-	{
+	type_ctor_info__generate_rtti(HLDS, TypeCtorRttiData),
+	base_typeclass_info__generate_rtti(HLDS, OldTypeClassInfoRttiData),
+	globals__io_lookup_bool_option(new_type_class_rtti, NewTypeClassRtti,
+		!IO),
+	(
 		NewTypeClassRtti = no,
 		TypeClassInfoRttiData = OldTypeClassInfoRttiData
 	;
@@ -3638,99 +3673,98 @@
 		type_class_info__generate_rtti(HLDS, NewTypeClassInfoRttiData),
 		list__append(OldTypeClassInfoRttiData, NewTypeClassInfoRttiData,
 			TypeClassInfoRttiData)
-	},
-	{ list__map(llds__wrap_rtti_data, TypeCtorRttiData, TypeCtorTables) },
-	{ list__map(llds__wrap_rtti_data, TypeClassInfoRttiData,
-		TypeClassInfos) },
-	{ stack_layout__generate_llds(HLDS, GlobalData0, GlobalData,
-		StackLayouts, LayoutLabels) },
+	),
+	list__map(llds__wrap_rtti_data, TypeCtorRttiData, TypeCtorTables),
+	list__map(llds__wrap_rtti_data, TypeClassInfoRttiData,
+		TypeClassInfos),
+	stack_layout__generate_llds(HLDS, GlobalData0, GlobalData,
+		StackLayouts, LayoutLabels),
 	%
 	% Here we perform some optimizations on the LLDS data.
 	% XXX this should perhaps be part of backend_pass
 	% rather than output_pass.
 	%
 	% XXX We assume that the foreign language we use is C
-	{ get_c_interface_info(HLDS, c, C_InterfaceInfo) },
-	{ global_data_get_all_proc_vars(GlobalData, GlobalVars) },
-	{ global_data_get_all_deep_prof_data(GlobalData, DeepProfData) },
-	{ global_data_get_all_closure_layouts(GlobalData, ClosureLayouts) },
-	{ global_data_get_static_cell_info(GlobalData, StaticCellInfo) },
-	{ StaticCells = get_static_cells(StaticCellInfo) },
+	get_c_interface_info(HLDS, c, C_InterfaceInfo),
+	global_data_get_all_proc_vars(GlobalData, GlobalVars),
+	global_data_get_all_deep_prof_data(GlobalData, DeepProfData),
+	global_data_get_all_closure_layouts(GlobalData, ClosureLayouts),
+	global_data_get_static_cell_info(GlobalData, StaticCellInfo),
+	StaticCells = get_static_cells(StaticCellInfo),
 
 	%
 	% Next we put it all together and output it to one or more C files.
 	%
-	{ list__condense([StaticCells, ClosureLayouts, StackLayouts,
-		DeepProfData, TypeCtorTables, TypeClassInfos], AllData) },
+	list__condense([StaticCells, ClosureLayouts, StackLayouts,
+		DeepProfData, TypeCtorTables, TypeClassInfos], AllData),
 	mercury_compile__construct_c_file(HLDS, C_InterfaceInfo,
-		Procs, GlobalVars, AllData, CFile, NumChunks),
+		Procs, GlobalVars, AllData, CFile, NumChunks, !IO),
 	mercury_compile__output_llds(ModuleName, CFile, LayoutLabels,
-		MaybeRLFile, Verbose, Stats),
+		MaybeRLFile, Verbose, Stats, !IO),
 
-	{ C_InterfaceInfo = foreign_interface_info(_, _, _, _,
-					C_ExportDecls, _) },
-	export__produce_header_file(C_ExportDecls, ModuleName),
+	C_InterfaceInfo = foreign_interface_info(_, _, _, _,
+		C_ExportDecls, _),
+	export__produce_header_file(C_ExportDecls, ModuleName, !IO),
 
 	%
 	% Finally we invoke the C compiler to compile it.
 	%
-	globals__io_lookup_bool_option(target_code_only, TargetCodeOnly),
-	( { TargetCodeOnly = no } ->
-		io__output_stream(OutputStream),
+	globals__io_lookup_bool_option(target_code_only, TargetCodeOnly, !IO),
+	( TargetCodeOnly = no ->
+		io__output_stream(OutputStream, !IO),
 		mercury_compile__c_to_obj(OutputStream,
-			ModuleName, NumChunks, CompileOK),
-		maybe_set_exit_status(CompileOK),
-		{ bool__not(CompileOK, CompileErrors) }
+			ModuleName, NumChunks, CompileOK, !IO),
+		maybe_set_exit_status(CompileOK, !IO),
+		bool__not(CompileOK, CompileErrors)
 	;
-		{ CompileErrors = no }
+		CompileErrors = no
 	).
 
 	% Split the code up into bite-size chunks for the C compiler.
 
-:- pred mercury_compile__construct_c_file(module_info, foreign_interface_info,
-	list(c_procedure), list(comp_gen_c_var), list(comp_gen_c_data),
-	c_file, int, io__state, io__state).
-:- mode mercury_compile__construct_c_file(in, in, in, in, in, out, out, di, uo)
-	is det.
+:- pred mercury_compile__construct_c_file(module_info::in,
+	foreign_interface_info::in, list(c_procedure)::in,
+	list(comp_gen_c_var)::in, list(comp_gen_c_data)::in,
+	c_file::out, int::out, io::di, io::uo) is det.
 
 mercury_compile__construct_c_file(_Module,
 		C_InterfaceInfo, Procedures, GlobalVars,
-		AllData, CFile, ComponentCount) -->
-	{ C_InterfaceInfo = foreign_interface_info(ModuleSymName,
+		AllData, CFile, ComponentCount, !IO) :-
+	C_InterfaceInfo = foreign_interface_info(ModuleSymName,
 		C_HeaderCode0, C_Includes, C_BodyCode0,
-		_C_ExportDecls, C_ExportDefns) },
-	{ MangledModuleName = sym_name_mangle(ModuleSymName) },
-	{ string__append(MangledModuleName, "_module", ModuleName) },
-	globals__io_lookup_int_option(procs_per_c_function, ProcsPerFunc),
-	{ get_c_body_code(C_BodyCode0, C_BodyCode) },
-	( { ProcsPerFunc = 0 } ->
+		_C_ExportDecls, C_ExportDefns),
+	MangledModuleName = sym_name_mangle(ModuleSymName),
+	string__append(MangledModuleName, "_module", ModuleName),
+	globals__io_lookup_int_option(procs_per_c_function, ProcsPerFunc, !IO),
+	get_c_body_code(C_BodyCode0, C_BodyCode),
+	( ProcsPerFunc = 0 ->
 		% ProcsPerFunc = 0 really means infinity -
 		% we store all the procs in a single function.
-		{ ChunkedModules = [comp_gen_c_module(ModuleName,
-			Procedures)] }
+		ChunkedModules = [comp_gen_c_module(ModuleName,
+			Procedures)]
 	;
-		{ list__chunk(Procedures, ProcsPerFunc, ChunkedProcs) },
-		{ mercury_compile__combine_chunks(ChunkedProcs, ModuleName,
-			ChunkedModules) }
+		list__chunk(Procedures, ProcsPerFunc, ChunkedProcs),
+		mercury_compile__combine_chunks(ChunkedProcs, ModuleName,
+			ChunkedModules)
 	),
 	list__map_foldl(make_foreign_import_header_code, C_Includes,
-		C_HeaderCode1),
+		C_HeaderCode1, !IO),
 
-	{ make_decl_guards(ModuleSymName, Start, End) },
-	{ C_HeaderCode = [End | C_HeaderCode0] ++ [Start | C_HeaderCode1] },
+	make_decl_guards(ModuleSymName, Start, End),
+	C_HeaderCode = [End | C_HeaderCode0] ++ [Start | C_HeaderCode1],
 
-	{ CFile = c_file(ModuleSymName, C_HeaderCode, C_BodyCode,
-		C_ExportDefns, GlobalVars, AllData, ChunkedModules) },
-	{ list__length(C_BodyCode, UserCCodeCount) },
-	{ list__length(C_ExportDefns, ExportCount) },
-	{ list__length(GlobalVars, CompGenVarCount) },
-	{ list__length(AllData, CompGenDataCount) },
-	{ list__length(ChunkedModules, CompGenCodeCount) },
-	{ ComponentCount = UserCCodeCount + ExportCount
-		+ CompGenVarCount + CompGenDataCount + CompGenCodeCount }.
+	CFile = c_file(ModuleSymName, C_HeaderCode, C_BodyCode,
+		C_ExportDefns, GlobalVars, AllData, ChunkedModules),
+	list__length(C_BodyCode, UserCCodeCount),
+	list__length(C_ExportDefns, ExportCount),
+	list__length(GlobalVars, CompGenVarCount),
+	list__length(AllData, CompGenDataCount),
+	list__length(ChunkedModules, CompGenCodeCount),
+	ComponentCount = UserCCodeCount + ExportCount
+		+ CompGenVarCount + CompGenDataCount + CompGenCodeCount.
 
-:- pred make_decl_guards(sym_name::in,
-		foreign_decl_code::out, foreign_decl_code::out) is det.
+:- pred make_decl_guards(sym_name::in, foreign_decl_code::out,
+	foreign_decl_code::out) is det.
 
 make_decl_guards(ModuleName, StartGuard, EndGuard) :-
 	Define = decl_guard(ModuleName),
@@ -3739,57 +3773,53 @@
 	StartGuard = foreign_decl_code(c, Start, term__context_init),
 	EndGuard = foreign_decl_code(c, End, term__context_init).
 
-:- pred make_foreign_import_header_code(foreign_import_module,
-		foreign_decl_code, io__state, io__state).
-:- mode make_foreign_import_header_code(in, out, di, uo) is det.
-
-make_foreign_import_header_code(
-		foreign_import_module(Lang, ModuleName, Context),
-		Include) -->
+:- pred make_foreign_import_header_code(foreign_import_module::in,
+	foreign_decl_code::out, io::di, io::uo) is det.
+
+make_foreign_import_header_code(ForeignImportModule, Include, !IO) :-
+	ForeignImportModule = foreign_import_module(Lang, ModuleName, Context),
 	(
-		{ Lang = c },
+		Lang = c,
 		module_name_to_search_file_name(ModuleName, ".mh",
-			HeaderFileName),
-		{ string__append_list(
+			HeaderFileName, !IO),
+		string__append_list(
 			["#include """, HeaderFileName, """\n"],
-			IncludeString) },
-		{ Include = foreign_decl_code(c, IncludeString, Context) }
+			IncludeString),
+		Include = foreign_decl_code(c, IncludeString, Context)
 	;
-		{ Lang = csharp },
-		{ error("sorry.
-:- import_module not yet implemented: `:- pragma foreign_import_module' for C#") }
+		Lang = csharp,
+		error("sorry. :- import_module not yet implemented: " ++
+			"`:- pragma foreign_import_module' for C#")
 	;
-		{ Lang = managed_cplusplus },
-		{ error("sorry.
-:- import_module not yet implemented: `:- pragma foreign_import_module' for Managed C++") }
+		Lang = managed_cplusplus,
+		error("sorry. :- import_module not yet implemented: " ++
+			"`:- pragma foreign_import_module' for Managed C++")
 	;
-		{ Lang = il },
-		{ error("sorry.
-:- import_module not yet implemented: `:- pragma foreign_import_module' for IL") }
+		Lang = il,
+		error("sorry. :- import_module not yet implemented: " ++
+			"`:- pragma foreign_import_module' for IL")
 	;
-		{ Lang = java },
-		{ error("sorry.
-:- import_module not yet implemented: `:- pragma foreign_import_module' for Java") }
+		Lang = java,
+		error("sorry. :- import_module not yet implemented: " ++
+			"`:- pragma foreign_import_module' for Java")
 	).
 
-:- pred get_c_body_code(foreign_body_info, list(user_foreign_code)).
-:- mode get_c_body_code(in, out) is det.
+:- pred get_c_body_code(foreign_body_info::in, list(user_foreign_code)::out)
+	is det.
 
 get_c_body_code([], []).
 get_c_body_code([foreign_body_code(Lang, Code, Context) | CodesAndContexts],
 		[user_foreign_code(Lang, Code, Context) | C_Modules]) :-
 	get_c_body_code(CodesAndContexts, C_Modules).
 
-:- pred mercury_compile__combine_chunks(list(list(c_procedure)), string,
-	list(comp_gen_c_module)).
-:- mode mercury_compile__combine_chunks(in, in, out) is det.
+:- pred mercury_compile__combine_chunks(list(list(c_procedure))::in, string::in,
+	list(comp_gen_c_module)::out) is det.
 
 mercury_compile__combine_chunks(ChunkList, ModName, Modules) :-
 	mercury_compile__combine_chunks_2(ChunkList, ModName, 0, Modules).
 
-:- pred mercury_compile__combine_chunks_2(list(list(c_procedure)),
-	string, int, list(comp_gen_c_module)).
-:- mode mercury_compile__combine_chunks_2(in, in, in, out) is det.
+:- pred mercury_compile__combine_chunks_2(list(list(c_procedure))::in,
+	string::in, int::in, list(comp_gen_c_module)::out) is det.
 
 mercury_compile__combine_chunks_2([], _ModName, _N, []).
 mercury_compile__combine_chunks_2([Chunk | Chunks], ModuleName, Num,
@@ -3800,122 +3830,119 @@
 	Num1 = Num + 1,
 	mercury_compile__combine_chunks_2(Chunks, ModuleName, Num1, Modules).
 
-:- pred mercury_compile__output_llds(module_name, c_file,
-	map(llds__label, llds__data_addr), maybe(rl_file), bool, bool,
-	io__state, io__state).
-:- mode mercury_compile__output_llds(in, in, in, in, in, in, di, uo) is det.
+:- pred mercury_compile__output_llds(module_name::in, c_file::in,
+	map(llds__label, llds__data_addr)::in, maybe(rl_file)::in,
+	bool::in, bool::in, io::di, io::uo) is det.
 
 mercury_compile__output_llds(ModuleName, LLDS0, StackLayoutLabels, MaybeRLFile,
-		Verbose, Stats) -->
-	maybe_write_string(Verbose, "% Writing output to `"),
-	module_name_to_file_name(ModuleName, ".c", yes, FileName),
-	maybe_write_string(Verbose, FileName),
-	maybe_write_string(Verbose, "'..."),
-	maybe_flush_output(Verbose),
-	transform_llds(LLDS0, LLDS),
-	output_llds(LLDS, StackLayoutLabels, MaybeRLFile),
-	maybe_write_string(Verbose, " done.\n"),
-	maybe_flush_output(Verbose),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__c_to_obj(io__output_stream, module_name,
-		int, bool, io__state, io__state).
-:- mode mercury_compile__c_to_obj(in, in, in, out, di, uo) is det.
-
-mercury_compile__c_to_obj(ErrorStream, ModuleName, NumChunks, Succeeded) -->
-	globals__io_lookup_bool_option(split_c_files, SplitFiles),
-	( { SplitFiles = yes } ->
+		Verbose, Stats, !IO) :-
+	maybe_write_string(Verbose, "% Writing output to `", !IO),
+	module_name_to_file_name(ModuleName, ".c", yes, FileName, !IO),
+	maybe_write_string(Verbose, FileName, !IO),
+	maybe_write_string(Verbose, "'...", !IO),
+	maybe_flush_output(Verbose, !IO),
+	transform_llds(LLDS0, LLDS, !IO),
+	output_llds(LLDS, StackLayoutLabels, MaybeRLFile, !IO),
+	maybe_write_string(Verbose, " done.\n", !IO),
+	maybe_flush_output(Verbose, !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__c_to_obj(io__output_stream::in, module_name::in,
+	int::in, bool::out, io::di, io::uo) is det.
+
+mercury_compile__c_to_obj(ErrorStream, ModuleName, NumChunks, Succeeded,
+		!IO) :-
+	globals__io_lookup_bool_option(split_c_files, SplitFiles, !IO),
+	( SplitFiles = yes ->
 		compile_target_code__split_c_to_obj(ErrorStream, ModuleName,
-			NumChunks, Succeeded)
+			NumChunks, Succeeded, !IO)
 	;
-		get_linked_target_type(LinkedTargetType),
-		get_object_code_type(LinkedTargetType, PIC),
-		maybe_pic_object_file_extension(PIC, Obj),
-		module_name_to_file_name(ModuleName, ".c", no, C_File),
-		module_name_to_file_name(ModuleName, Obj, yes, O_File),
+		get_linked_target_type(LinkedTargetType, !IO),
+		get_object_code_type(LinkedTargetType, PIC, !IO),
+		maybe_pic_object_file_extension(PIC, Obj, !IO),
+		module_name_to_file_name(ModuleName, ".c", no, C_File, !IO),
+		module_name_to_file_name(ModuleName, Obj, yes, O_File, !IO),
 		compile_target_code__compile_c_file(ErrorStream, PIC,
-			C_File, O_File, Succeeded)
+			C_File, O_File, Succeeded, !IO)
 	).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
-% The MLDS-based alternative backend
+% The MLDS backend
+
+:- pred mercury_compile__mlds_backend(module_info::in, module_info::out,
+	mlds::out, io::di, io::uo) is det.
+
+mercury_compile__mlds_backend(!HLDS, MLDS, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+
+	mercury_compile__simplify(no, yes, Verbose, Stats,
+		process_all_nonimported_nonaditi_procs, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "53", "simplify2", !IO),
+
+	mercury_compile__maybe_add_trail_ops(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "55", "add_trail_ops", !IO),
 
-:- pred mercury_compile__mlds_backend(module_info, mlds, io__state, io__state).
-:- mode mercury_compile__mlds_backend(in, out, di, uo) is det.
+	mercury_compile__maybe_add_heap_ops(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "57", "add_heap_ops", !IO),
 
-mercury_compile__mlds_backend(HLDS51, MLDS) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-
-	mercury_compile__simplify(HLDS51, no, yes, Verbose, Stats, 
-		process_all_nonimported_nonaditi_procs, HLDS53),
-	mercury_compile__maybe_dump_hlds(HLDS53, "53", "simplify2"),
-
-	mercury_compile__maybe_add_trail_ops(HLDS53, Verbose, Stats,
-		HLDS55),
-	mercury_compile__maybe_dump_hlds(HLDS55, "55", "add_trail_ops"),
-
-	mercury_compile__maybe_add_heap_ops(HLDS55, Verbose, Stats,
-		HLDS57),
-	mercury_compile__maybe_dump_hlds(HLDS57, "57", "add_heap_ops"),
-
-	mercury_compile__maybe_mark_static_terms(HLDS57, Verbose, Stats,
-		HLDS60),
-	mercury_compile__maybe_dump_hlds(HLDS60, "60", "mark_static"),
+	mercury_compile__maybe_mark_static_terms(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "60", "mark_static", !IO),
 
 	% We need to do map_args_to_regs, even though that module is meant
 	% for the LLDS back-end, because with the MLDS back-end the arg_infos
 	% that map_args_to_regs generates are used by continuation_info.m,
 	% which is used by ml_unify_gen.m when outputting closure layout
 	% structs.
-	mercury_compile__map_args_to_regs(HLDS60, Verbose, Stats, HLDS70),
-	mercury_compile__maybe_dump_hlds(HLDS70, "70", "args_to_regs"),
+	mercury_compile__map_args_to_regs(Verbose, Stats, !HLDS, !IO),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "70", "args_to_regs", !IO),
 
-	{ HLDS = HLDS70 },
-	mercury_compile__maybe_dump_hlds(HLDS, "99", "final"),
+	mercury_compile__maybe_dump_hlds(!.HLDS, "99", "final", !IO),
 
-	maybe_write_string(Verbose, "% Converting HLDS to MLDS...\n"),
-	ml_code_gen(HLDS, MLDS0),
-	maybe_write_string(Verbose, "% done.\n"),
-	maybe_report_stats(Stats),
-	mercury_compile__maybe_dump_mlds(MLDS0, "0", "initial"),
-
-	maybe_write_string(Verbose, "% Generating RTTI data...\n"),
-	{ mercury_compile__mlds_gen_rtti_data(HLDS, MLDS0, MLDS10) },
-	maybe_write_string(Verbose, "% done.\n"),
-	maybe_report_stats(Stats),
-	mercury_compile__maybe_dump_mlds(MLDS10, "10", "rtti"),
+	maybe_write_string(Verbose, "% Converting HLDS to MLDS...\n", !IO),
+	ml_code_gen(!.HLDS, MLDS0, !IO),
+	maybe_write_string(Verbose, "% done.\n", !IO),
+	maybe_report_stats(Stats, !IO),
+	mercury_compile__maybe_dump_mlds(MLDS0, "0", "initial", !IO),
+
+	maybe_write_string(Verbose, "% Generating RTTI data...\n", !IO),
+	mercury_compile__mlds_gen_rtti_data(!.HLDS, MLDS0, MLDS10),
+	maybe_write_string(Verbose, "% done.\n", !IO),
+	maybe_report_stats(Stats, !IO),
+	mercury_compile__maybe_dump_mlds(MLDS10, "10", "rtti", !IO),
 
 	% Detection of tail calls needs to occur before the
 	% chain_gc_stack_frame pass of ml_elim_nested,
 	% because we need to unlink the stack frame from the
 	% stack chain before tail calls.
-	globals__io_lookup_bool_option(optimize_tailcalls, OptimizeTailCalls),
-	( { OptimizeTailCalls = yes } ->
-		maybe_write_string(Verbose, 
-			"% Detecting tail calls...\n"),
-		ml_mark_tailcalls(MLDS10, MLDS20),
-		maybe_write_string(Verbose, "% done.\n")
+	globals__io_lookup_bool_option(optimize_tailcalls, OptimizeTailCalls,
+		!IO),
+	( OptimizeTailCalls = yes ->
+		maybe_write_string(Verbose,
+			"% Detecting tail calls...\n", !IO),
+		ml_mark_tailcalls(MLDS10, MLDS20, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO)
 	;
-		{ MLDS10 = MLDS20 }
+		MLDS10 = MLDS20
 	),
-	maybe_report_stats(Stats),
-	mercury_compile__maybe_dump_mlds(MLDS20, "20", "tailcalls"),
+	maybe_report_stats(Stats, !IO),
+	mercury_compile__maybe_dump_mlds(MLDS20, "20", "tailcalls", !IO),
 
 	% Warning about non-tail calls needs to come after detection
 	% of tail calls
-	globals__io_lookup_bool_option(warn_non_tail_recursion, WarnTailCalls),
-	( { OptimizeTailCalls = yes, WarnTailCalls = yes } ->
-		maybe_write_string(Verbose, 
-			"% Warning about non-tail recursive calls...\n"),
-		ml_warn_tailcalls(MLDS20),
-		maybe_write_string(Verbose, "% done.\n")
+	globals__io_lookup_bool_option(warn_non_tail_recursion, WarnTailCalls,
+		!IO),
+	( OptimizeTailCalls = yes, WarnTailCalls = yes ->
+		maybe_write_string(Verbose,
+			"% Warning about non-tail recursive calls...\n", !IO),
+		ml_warn_tailcalls(MLDS20, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO)
 	;
-		[]
+		true
 	),
-	maybe_report_stats(Stats),
+	maybe_report_stats(Stats, !IO),
 
 	% run the ml_optimize pass before ml_elim_nested,
 	% so that we eliminate as many local variables as possible
@@ -3928,23 +3955,23 @@
 	% However, we need to disable optimize_initializations,
 	% because ml_elim_nested doesn't correctly handle
 	% code containing initializations.
-	globals__io_lookup_bool_option(optimize, Optimize),
-	( { Optimize = yes } ->
+	globals__io_lookup_bool_option(optimize, Optimize, !IO),
+	( Optimize = yes ->
 		globals__io_lookup_bool_option(optimize_initializations,
-			OptimizeInitializations),
-		globals__io_set_option(optimize_initializations, bool(no)),
-
-		maybe_write_string(Verbose, "% Optimizing MLDS...\n"),
-		ml_optimize__optimize(MLDS20, MLDS25),
-		maybe_write_string(Verbose, "% done.\n"),
+			OptimizeInitializations, !IO),
+		globals__io_set_option(optimize_initializations, bool(no),
+			!IO),
+		maybe_write_string(Verbose, "% Optimizing MLDS...\n", !IO),
+		ml_optimize__optimize(MLDS20, MLDS25, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO),
 
 		globals__io_set_option(optimize_initializations,
-			bool(OptimizeInitializations))
+			bool(OptimizeInitializations), !IO)
 	;
-		{ MLDS25 = MLDS20 }
+		MLDS25 = MLDS20
 	),
-	maybe_report_stats(Stats),
-	mercury_compile__maybe_dump_mlds(MLDS25, "25", "optimize1"),
+	maybe_report_stats(Stats, !IO),
+	mercury_compile__maybe_dump_mlds(MLDS25, "25", "optimize1", !IO),
 
 	%
 	% Note that we call ml_elim_nested twice --
@@ -3958,50 +3985,50 @@
 	% generates.
 	%
 
-	globals__io_get_gc_method(GC),
-	( { GC = accurate } ->
+	globals__io_get_gc_method(GC, !IO),
+	( GC = accurate ->
 		maybe_write_string(Verbose,
-			"% Threading GC stack frames...\n"),
-		ml_elim_nested(chain_gc_stack_frames, MLDS25, MLDS30),
-		maybe_write_string(Verbose, "% done.\n")
+			"% Threading GC stack frames...\n", !IO),
+		ml_elim_nested(chain_gc_stack_frames, MLDS25, MLDS30, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO)
 	;
-		{ MLDS30 = MLDS25 }
+		MLDS30 = MLDS25
 	),
-	maybe_report_stats(Stats),
-	mercury_compile__maybe_dump_mlds(MLDS30, "30", "gc_frames"),
+	maybe_report_stats(Stats, !IO),
+	mercury_compile__maybe_dump_mlds(MLDS30, "30", "gc_frames", !IO),
 
-	globals__io_lookup_bool_option(gcc_nested_functions, NestedFuncs),
-	( { NestedFuncs = no } ->
+	globals__io_lookup_bool_option(gcc_nested_functions, NestedFuncs, !IO),
+	( NestedFuncs = no ->
 		maybe_write_string(Verbose,
-			"% Flattening nested functions...\n"),
-		ml_elim_nested(hoist_nested_funcs, MLDS30, MLDS35),
-		maybe_write_string(Verbose, "% done.\n")
+			"% Flattening nested functions...\n", !IO),
+		ml_elim_nested(hoist_nested_funcs, MLDS30, MLDS35, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO)
 	;
-		{ MLDS35 = MLDS30 }
+		MLDS35 = MLDS30
 	),
-	maybe_report_stats(Stats),
-	mercury_compile__maybe_dump_mlds(MLDS35, "35", "nested_funcs"),
+	maybe_report_stats(Stats, !IO),
+	mercury_compile__maybe_dump_mlds(MLDS35, "35", "nested_funcs", !IO),
 
 	% run the ml_optimize pass again after ml_elim_nested,
 	% to do optimize_initializations.  (It may also help pick
 	% up some additional optimization opportunities for the
 	% other optimizations in this pass.)
-	( { Optimize = yes } ->
-		maybe_write_string(Verbose, "% Optimizing MLDS again...\n"),
-		ml_optimize__optimize(MLDS35, MLDS40),
-		maybe_write_string(Verbose, "% done.\n")
+	( Optimize = yes ->
+		maybe_write_string(Verbose,
+			"% Optimizing MLDS again...\n", !IO),
+		ml_optimize__optimize(MLDS35, MLDS40, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO)
 	;
-		{ MLDS40 = MLDS35 }
+		MLDS40 = MLDS35
 	),
-	maybe_report_stats(Stats),
-	mercury_compile__maybe_dump_mlds(MLDS40, "40", "optimize2"),
-
-	{ MLDS = MLDS40 },
-	mercury_compile__maybe_dump_mlds(MLDS, "99", "final").
+	maybe_report_stats(Stats, !IO),
+	mercury_compile__maybe_dump_mlds(MLDS40, "40", "optimize2", !IO),
 
+	MLDS = MLDS40,
+	mercury_compile__maybe_dump_mlds(MLDS, "99", "final", !IO).
 
-:- pred mercury_compile__mlds_gen_rtti_data(module_info, mlds, mlds).
-:- mode mercury_compile__mlds_gen_rtti_data(in, in, out) is det.
+:- pred mercury_compile__mlds_gen_rtti_data(module_info::in,
+	mlds::in, mlds::out) is det.
 
 mercury_compile__mlds_gen_rtti_data(HLDS, MLDS0, MLDS) :-
 	type_ctor_info__generate_rtti(HLDS, TypeCtorRtti),
@@ -4014,81 +4041,79 @@
 
 % The `--high-level-C' MLDS output pass
 
-:- pred mercury_compile__mlds_to_high_level_c(mlds, maybe(rl_file),
-		io__state, io__state).
-:- mode mercury_compile__mlds_to_high_level_c(in, in, di, uo) is det.
-
-mercury_compile__mlds_to_high_level_c(MLDS, MaybeRLFile) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-
-	maybe_write_string(Verbose, "% Converting MLDS to C...\n"),
-	mlds_to_c__output_mlds(MLDS, MaybeRLFile, ""),
-	maybe_write_string(Verbose, "% Finished converting MLDS to C.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__mlds_to_java(mlds, io__state, io__state).
-:- mode mercury_compile__mlds_to_java(in, di, uo) is det.
-
-mercury_compile__mlds_to_java(MLDS) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-
-	maybe_write_string(Verbose, "% Converting MLDS to Java...\n"),
-	mlds_to_java__output_mlds(MLDS),
-	maybe_write_string(Verbose, "% Finished converting MLDS to Java.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__maybe_mlds_to_gcc(mlds, maybe(rl_file),
-		bool, io__state, io__state).
-:- mode mercury_compile__maybe_mlds_to_gcc(in, in, out, di, uo) is det.
-
-mercury_compile__maybe_mlds_to_gcc(MLDS, MaybeRLFile, ContainsCCode) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
+:- pred mercury_compile__mlds_to_high_level_c(mlds::in, maybe(rl_file)::in,
+	io::di, io::uo) is det.
+
+mercury_compile__mlds_to_high_level_c(MLDS, MaybeRLFile, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+
+	maybe_write_string(Verbose, "% Converting MLDS to C...\n", !IO),
+	mlds_to_c__output_mlds(MLDS, MaybeRLFile, "", !IO),
+	maybe_write_string(Verbose, "% Finished converting MLDS to C.\n", !IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__mlds_to_java(mlds::in, io::di, io::uo) is det.
+
+mercury_compile__mlds_to_java(MLDS, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+
+	maybe_write_string(Verbose, "% Converting MLDS to Java...\n", !IO),
+	mlds_to_java__output_mlds(MLDS, !IO),
+	maybe_write_string(Verbose, "% Finished converting MLDS to Java.\n",
+		!IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__maybe_mlds_to_gcc(mlds::in, maybe(rl_file)::in,
+	bool::out, io::di, io::uo) is det.
+
+mercury_compile__maybe_mlds_to_gcc(MLDS, MaybeRLFile, ContainsCCode, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
 
 	maybe_write_string(Verbose,
-		"% Passing MLDS to GCC and compiling to assembler...\n"),
-	maybe_mlds_to_gcc__compile_to_asm(MLDS, MaybeRLFile, ContainsCCode),
-	maybe_write_string(Verbose, "% Finished compiling to assembler.\n"),
-	maybe_report_stats(Stats).
-
-:- pred mercury_compile__mlds_to_il_assembler(mlds, io__state, io__state).
-:- mode mercury_compile__mlds_to_il_assembler(in, di, uo) is det.
-
-mercury_compile__mlds_to_il_assembler(MLDS) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-
-	maybe_write_string(Verbose, "% Converting MLDS to IL...\n"),
-	mlds_to_ilasm__output_mlds(MLDS),
-	maybe_write_string(Verbose, "% Finished converting MLDS to IL.\n"),
-	maybe_report_stats(Stats).
+		"% Passing MLDS to GCC and compiling to assembler...\n", !IO),
+	maybe_mlds_to_gcc__compile_to_asm(MLDS, MaybeRLFile, ContainsCCode,
+		!IO),
+	maybe_write_string(Verbose, "% Finished compiling to assembler.\n",
+		!IO),
+	maybe_report_stats(Stats, !IO).
+
+:- pred mercury_compile__mlds_to_il_assembler(mlds::in, io::di, io::uo) is det.
+
+mercury_compile__mlds_to_il_assembler(MLDS, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+
+	maybe_write_string(Verbose, "% Converting MLDS to IL...\n", !IO),
+	mlds_to_ilasm__output_mlds(MLDS, !IO),
+	maybe_write_string(Verbose, "% Finished converting MLDS to IL.\n",
+		!IO),
+	maybe_report_stats(Stats, !IO).
 
 %-----------------------------------------------------------------------------%
 %-----------------------------------------------------------------------------%
 
-:- pred mercury_compile__maybe_dump_hlds(module_info, string, string,
-	io__state, io__state).
-:- mode mercury_compile__maybe_dump_hlds(in, in, in, di, uo) is det.
+:- pred mercury_compile__maybe_dump_hlds(module_info::in, string::in,
+	string::in, io::di, io::uo) is det.
 
-mercury_compile__maybe_dump_hlds(HLDS, StageNum, StageName) -->
-	globals__io_lookup_accumulating_option(dump_hlds, DumpStages),
-	(
-		{ should_dump_stage(StageNum, StageName, DumpStages) }
-	->
-		{ module_info_name(HLDS, ModuleName) },
+mercury_compile__maybe_dump_hlds(HLDS, StageNum, StageName, !IO) :-
+	globals__io_lookup_accumulating_option(dump_hlds, DumpStages, !IO),
+	( should_dump_stage(StageNum, StageName, DumpStages) ->
+		module_info_name(HLDS, ModuleName),
 		module_name_to_file_name(ModuleName, ".hlds_dump", yes,
-			BaseFileName),
-		{ string__append_list(
+			BaseFileName, !IO),
+		string__append_list(
 			[BaseFileName, ".", StageNum, "-", StageName],
-			DumpFile) },
-		mercury_compile__dump_hlds(DumpFile, HLDS)
+			DumpFile),
+		mercury_compile__dump_hlds(DumpFile, HLDS, !IO)
 	;
-		[]
+		true
 	).
 
 :- pred should_dump_stage(string::in, string::in, list(string)::in) is semidet.
+
 should_dump_stage(StageNum, StageName, DumpStages) :-
 	(
 		list__member(StageNum, DumpStages)
@@ -4112,122 +4137,121 @@
 		StageInt >= FromInt
 	).
 
-:- pred mercury_compile__dump_hlds(string, module_info, io__state, io__state).
-:- mode mercury_compile__dump_hlds(in, in, di, uo) is det.
+:- pred mercury_compile__dump_hlds(string::in, module_info::in,
+	io::di, io::uo) is det.
 
-mercury_compile__dump_hlds(DumpFile, HLDS) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-	maybe_write_string(Verbose, "% Dumping out HLDS to `"),
-	maybe_write_string(Verbose, DumpFile),
-	maybe_write_string(Verbose, "'..."),
-	maybe_flush_output(Verbose),
-	io__open_output(DumpFile, Res),
-	( { Res = ok(FileStream) } ->
-		io__set_output_stream(FileStream, OutputStream),
-		hlds_out__write_hlds(0, HLDS),
-		io__set_output_stream(OutputStream, _),
-		io__close_output(FileStream),
-		maybe_write_string(Verbose, " done.\n"),
-		maybe_report_stats(Stats)
-	;
-		maybe_write_string(Verbose, "\n"),
-		{ string__append_list(["can't open file `",
-			DumpFile, "' for output."], ErrorMessage) },
-		report_error(ErrorMessage)
-	).
-
-:- pred mercury_compile__maybe_dump_mlds(mlds, string, string,
-	io__state, io__state).
-:- mode mercury_compile__maybe_dump_mlds(in, in, in, di, uo) is det.
-
-mercury_compile__maybe_dump_mlds(MLDS, StageNum, StageName) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_accumulating_option(dump_mlds, DumpStages),
+mercury_compile__dump_hlds(DumpFile, HLDS, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+	maybe_write_string(Verbose, "% Dumping out HLDS to `", !IO),
+	maybe_write_string(Verbose, DumpFile, !IO),
+	maybe_write_string(Verbose, "'...", !IO),
+	maybe_flush_output(Verbose, !IO),
+	io__open_output(DumpFile, Res, !IO),
+	( Res = ok(FileStream) ->
+		io__set_output_stream(FileStream, OutputStream, !IO),
+		hlds_out__write_hlds(0, HLDS, !IO),
+		io__set_output_stream(OutputStream, _, !IO),
+		io__close_output(FileStream, !IO),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		maybe_write_string(Verbose, "\n", !IO),
+		string__append_list(["can't open file `",
+			DumpFile, "' for output."], ErrorMessage),
+		report_error(ErrorMessage, !IO)
+	).
+
+:- pred mercury_compile__maybe_dump_mlds(mlds::in, string::in, string::in,
+	io::di, io::uo) is det.
+
+mercury_compile__maybe_dump_mlds(MLDS, StageNum, StageName, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_accumulating_option(dump_mlds, DumpStages, !IO),
 	globals__io_lookup_accumulating_option(verbose_dump_mlds,
-		VerboseDumpStages),
-	( { should_dump_stage(StageNum, StageName, DumpStages) } ->
-		maybe_write_string(Verbose, "% Dumping out MLDS as C...\n"),
-		maybe_flush_output(Verbose),
-		{ string__append_list(["_dump.", StageNum, "-", StageName],
-			DumpSuffix) },
-		mlds_to_c__output_mlds(MLDS, no, DumpSuffix),
-		maybe_write_string(Verbose, "% done.\n")
+		VerboseDumpStages, !IO),
+	( should_dump_stage(StageNum, StageName, DumpStages) ->
+		maybe_write_string(Verbose, "% Dumping out MLDS as C...\n",
+			!IO),
+		maybe_flush_output(Verbose, !IO),
+		string__append_list(["_dump.", StageNum, "-", StageName],
+			DumpSuffix),
+		mlds_to_c__output_mlds(MLDS, no, DumpSuffix, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO)
 	;
-		[]
+		true
 	),
-	( { should_dump_stage(StageNum, StageName, VerboseDumpStages) } ->
-		maybe_write_string(Verbose, "% Dumping out raw MLDS...\n"),
-		{ ModuleName = mlds__get_module_name(MLDS) },
+	( should_dump_stage(StageNum, StageName, VerboseDumpStages) ->
+		maybe_write_string(Verbose, "% Dumping out raw MLDS...\n", !IO),
+		ModuleName = mlds__get_module_name(MLDS),
 		module_name_to_file_name(ModuleName, ".mlds_dump", yes,
-			BaseFileName),
-		{ string__append_list(
+			BaseFileName, !IO),
+		string__append_list(
 			[BaseFileName, ".", StageNum, "-", StageName],
-			DumpFile) },
-		mercury_compile__dump_mlds(DumpFile, MLDS),
-		maybe_write_string(Verbose, "% done.\n")
-	;
-		[]
-	).
-
-:- pred mercury_compile__dump_mlds(string, mlds, io__state, io__state).
-:- mode mercury_compile__dump_mlds(in, in, di, uo) is det.
-
-mercury_compile__dump_mlds(DumpFile, MLDS) -->
-	globals__io_lookup_bool_option(verbose, Verbose),
-	globals__io_lookup_bool_option(statistics, Stats),
-	maybe_write_string(Verbose, "% Dumping out MLDS to `"),
-	maybe_write_string(Verbose, DumpFile),
-	maybe_write_string(Verbose, "'..."),
-	maybe_flush_output(Verbose),
-	io__open_output(DumpFile, Res),
-	( { Res = ok(FileStream) } ->
-		io__set_output_stream(FileStream, OutputStream),
-		pprint__write(80, pprint__to_doc(MLDS)),
-		io__nl,
-		io__set_output_stream(OutputStream, _),
-		io__close_output(FileStream),
-		maybe_write_string(Verbose, " done.\n"),
-		maybe_report_stats(Stats)
-	;
-		maybe_write_string(Verbose, "\n"),
-		{ string__append_list(["can't open file `",
-			DumpFile, "' for output."], ErrorMessage) },
-		report_error(ErrorMessage)
-	).
-
-:- pred mercury_compile__maybe_dump_rl(list(rl_proc), module_info,
-		string, string, io__state, io__state).
-:- mode mercury_compile__maybe_dump_rl(in, in, in, in, di, uo) is det.
-
-mercury_compile__maybe_dump_rl(Procs, ModuleInfo, _StageNum, StageName) -->
-	globals__io_lookup_bool_option(dump_rl, Dump),
-	( { Dump = yes } ->
-		{ module_info_name(ModuleInfo, ModuleName0) },
-		{ prog_out__sym_name_to_string(ModuleName0, ModuleName) },
-		{ string__append_list([ModuleName, ".rl_dump", StageName],
-			DumpFile) },
-		globals__io_lookup_bool_option(verbose, Verbose),
-		maybe_write_string(Verbose, "% Dumping out RL to `"),
-		maybe_write_string(Verbose, DumpFile),
-		maybe_write_string(Verbose, "'..."),
-		maybe_flush_output(Verbose),
-		io__open_output(DumpFile, Res),
-		( { Res = ok(FileStream) } ->
-			io__set_output_stream(FileStream, OutputStream),
-			list__foldl(rl_dump__write_procedure(ModuleInfo), 
-				Procs),
-			io__set_output_stream(OutputStream, _),
-			io__close_output(FileStream),
-			maybe_write_string(Verbose, " done.\n")
-		;
-			maybe_write_string(Verbose, "\n"),
-			{ string__append_list(["can't open file `",
-				DumpFile, "' for output."], ErrorMessage) },
-			report_error(ErrorMessage)
+			DumpFile),
+		mercury_compile__dump_mlds(DumpFile, MLDS, !IO),
+		maybe_write_string(Verbose, "% done.\n", !IO)
+	;
+		true
+	).
+
+:- pred mercury_compile__dump_mlds(string::in, mlds::in,
+	io::di, io::uo) is det.
+
+mercury_compile__dump_mlds(DumpFile, MLDS, !IO) :-
+	globals__io_lookup_bool_option(verbose, Verbose, !IO),
+	globals__io_lookup_bool_option(statistics, Stats, !IO),
+	maybe_write_string(Verbose, "% Dumping out MLDS to `", !IO),
+	maybe_write_string(Verbose, DumpFile, !IO),
+	maybe_write_string(Verbose, "'...", !IO),
+	maybe_flush_output(Verbose, !IO),
+	io__open_output(DumpFile, Res, !IO),
+	( Res = ok(FileStream) ->
+		io__set_output_stream(FileStream, OutputStream, !IO),
+		pprint__write(80, pprint__to_doc(MLDS), !IO),
+		io__nl(!IO),
+		io__set_output_stream(OutputStream, _, !IO),
+		io__close_output(FileStream, !IO),
+		maybe_write_string(Verbose, " done.\n", !IO),
+		maybe_report_stats(Stats, !IO)
+	;
+		maybe_write_string(Verbose, "\n", !IO),
+		string__append_list(["can't open file `",
+			DumpFile, "' for output."], ErrorMessage),
+		report_error(ErrorMessage, !IO)
+	).
+
+:- pred mercury_compile__maybe_dump_rl(list(rl_proc)::in, module_info::in,
+	string::in, string::in, io::di, io::uo) is det.
+
+mercury_compile__maybe_dump_rl(Procs, ModuleInfo, _StageNum, StageName, !IO) :-
+	globals__io_lookup_bool_option(dump_rl, Dump, !IO),
+	( Dump = yes ->
+		module_info_name(ModuleInfo, ModuleName0),
+		prog_out__sym_name_to_string(ModuleName0, ModuleName),
+		string__append_list([ModuleName, ".rl_dump", StageName],
+			DumpFile),
+		globals__io_lookup_bool_option(verbose, Verbose, !IO),
+		maybe_write_string(Verbose, "% Dumping out RL to `", !IO),
+		maybe_write_string(Verbose, DumpFile, !IO),
+		maybe_write_string(Verbose, "'...", !IO),
+		maybe_flush_output(Verbose, !IO),
+		io__open_output(DumpFile, Res, !IO),
+		( Res = ok(FileStream) ->
+			io__set_output_stream(FileStream, OutputStream, !IO),
+			list__foldl(rl_dump__write_procedure(ModuleInfo),
+				Procs, !IO),
+			io__set_output_stream(OutputStream, _, !IO),
+			io__close_output(FileStream, !IO),
+			maybe_write_string(Verbose, " done.\n", !IO)
+		;
+			maybe_write_string(Verbose, "\n", !IO),
+			string__append_list(["can't open file `",
+				DumpFile, "' for output."], ErrorMessage),
+			report_error(ErrorMessage, !IO)
 		)
 	;
-		[]
+		true
 	).
 
 %-----------------------------------------------------------------------------%
Index: compiler/optimize.m
===================================================================
RCS file: /home/mercury/mercury1/repository/mercury/compiler/optimize.m,v
retrieving revision 1.40
diff -u -r1.40 optimize.m
--- compiler/optimize.m	8 Jan 2004 06:52:36 -0000	1.40
+++ compiler/optimize.m	28 Jan 2004 05:00:20 -0000
@@ -19,11 +19,11 @@
 
 :- import_module io, list.
 
-:- pred optimize_main(list(c_procedure)::in, global_data::in,
-	list(c_procedure)::out, io__state::di, io__state::uo) is det.
+:- pred optimize_main(global_data::in,
+	list(c_procedure)::in, list(c_procedure)::out, io::di, io::uo) is det.
 
-:- pred optimize__proc(c_procedure::in, global_data::in,
-	c_procedure::out, io__state::di, io__state::uo) is det.
+:- pred optimize__proc(global_data::in, c_procedure::in, c_procedure::out,
+	io::di, io::uo) is det.
 
 %-----------------------------------------------------------------------------%
 
@@ -52,12 +52,10 @@
 :- import_module bool, int, string.
 :- import_module map, set, std_util, require, counter.
 
-optimize_main([], _, []) --> [].
-optimize_main([Proc0 | Procs0], GlobalData, [Proc | Procs]) -->
-	optimize__proc(Proc0, GlobalData, Proc),
-	optimize_main(Procs0, GlobalData, Procs).
+optimize_main(GlobalData, !Procs, !IO) :-
+	list__map_foldl(optimize__proc(GlobalData), !Procs, !IO).
 
-optimize__proc(CProc0, GlobalData, CProc) -->
+optimize__proc(GlobalData, CProc0, CProc) -->
 	{ CProc0 = c_procedure(Name, Arity, PredProcId, Instrs0,
 		ProcLabel, C0, MayAlterRtti) },
 	optimize__init_opt_debug_info(Name, Arity, PredProcId, Instrs0, C0,
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/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/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/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 java
cvs diff: Diffing java/library
cvs diff: Diffing java/runtime
cvs diff: Diffing library
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 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
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
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