Reduce unnecessary rebuilds of .dex files with restat=1

The .dex.toc files are created by dexdump, which outputs all
information in a .dex file which may affect compilation of
other modules.

For prebuilt java libraries and static java libraries, we'll
output empty .toc files and don't set restat=1. .dex.toc files
are necessary even for static java libraries because they can
be referenced by LOCAL_JAVA_LIBRARIES (instead of
LOCAL_STATIC_JAVA_LIBRARIES).

We don't use this optimization for apps build. We cannot build
dexdump for apps build due to lack of libc++.

Performance:

$ m && touch \
  frameworks/base/core/java/com/google/android/util/Procedure.java \
  && time m
Before: 3m48s
After: 1m46s

Bug: 24597504
Change-Id: Id1665923b414dee705dc60af4c021390a19ea26f
diff --git a/core/definitions.mk b/core/definitions.mk
index 5119d65..742a56c 100644
--- a/core/definitions.mk
+++ b/core/definitions.mk
@@ -1948,9 +1948,9 @@
 endef
 endif
 
-## Rule to creates a table of contents from a .jar file.
+## Rule to create a table of contents from a .jar file.
 ## Must be called with $(eval).
-# $1: A .jar file
+# $(1): A .jar file
 define _transform-jar-to-toc
 $1.toc: $1 | $(IJAR)
 	@echo Generating TOC: $$@
@@ -1959,11 +1959,40 @@
 endef
 
 ## Define a rule which generates .jar.toc and mark it as .KATI_RESTAT.
+# $(1): A .jar file
 define define-jar-to-toc-rule
 $(eval $(call _transform-jar-to-toc,$1))\
 $(eval .KATI_RESTAT: $1.toc)
 endef
 
+ifeq (,$(TARGET_BUILD_APPS))
+
+## Rule to create a table of contents from a .dex file.
+## Must be called with $(eval).
+# $(1): The directory which contains classes*.dex files
+define _transform-dex-to-toc
+$1/classes.dex.toc: PRIVATE_INPUT_DEX_FILES := $1/classes*.dex
+$1/classes.dex.toc: $1/classes.dex $(DEXDUMP)
+	@echo Generating TOC: $$@
+	$(hide) $(DEXDUMP) -l xml $$(PRIVATE_INPUT_DEX_FILES) > $$@.tmp
+	$$(call commit-change-for-toc,$$@)
+endef
+
+## Define a rule which generates .dex.toc and mark it as .KATI_RESTAT.
+# $(1): The directory which contains classes*.dex files
+define define-dex-to-toc-rule
+$(eval $(call _transform-dex-to-toc,$1))\
+$(eval .KATI_RESTAT: $1/classes.dex.toc)
+endef
+
+else
+
+# Turn off .toc optimization for apps build as we cannot build dexdump.
+define define-dex-to-toc-rule
+endef
+
+endif  # TARGET_BUILD_APPS
+
 
 # Invoke Jack to compile java from source to jack files without shrink or obfuscation.
 #