When the environment variable LIBCLANG_RESOURCE_USAGE is set, teach
libclang to emit information about resource usage after parsing, code
completion, etc.


git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@130946 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/tools/libclang/CIndex.cpp b/tools/libclang/CIndex.cpp
index 7e697a7..9bd83a5 100644
--- a/tools/libclang/CIndex.cpp
+++ b/tools/libclang/CIndex.cpp
@@ -2560,8 +2560,10 @@
     fprintf(stderr, "}\n");
     
     return 0;
+  } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
+    PrintLibclangResourceUsage(PTUI.result);
   }
-
+  
   return PTUI.result;
 }
 
@@ -2574,7 +2576,10 @@
   if (!TU)
     return 1;
   
-  return static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
+  int result = static_cast<ASTUnit *>(TU->TUData)->Save(FileName);
+  if (getenv("LIBCLANG_RESOURCE_USAGE"))
+    PrintLibclangResourceUsage(TU);
+  return result;
 }
 
 void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
@@ -2650,8 +2655,8 @@
     fprintf(stderr, "libclang: crash detected during reparsing\n");
     static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
     return 1;
-  }
-
+  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
+    PrintLibclangResourceUsage(TU);
 
   return RTUI.result;
 }
@@ -5349,6 +5354,16 @@
 
 } // end extern "C"
 
+void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
+  CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
+  for (unsigned I = 0; I != Usage.numEntries; ++I)
+    fprintf(stderr, "  %s: %lu\n", 
+            clang_getTUResourceUsageName(Usage.entries[I].kind),
+            Usage.entries[I].amount);
+  
+  clang_disposeCXTUResourceUsage(Usage);
+}
+
 //===----------------------------------------------------------------------===//
 // Misc. utility functions.
 //===----------------------------------------------------------------------===//
diff --git a/tools/libclang/CIndexCodeCompletion.cpp b/tools/libclang/CIndexCodeCompletion.cpp
index e85e802..0c8317e 100644
--- a/tools/libclang/CIndexCodeCompletion.cpp
+++ b/tools/libclang/CIndexCodeCompletion.cpp
@@ -498,7 +498,8 @@
     fprintf(stderr, "libclang: crash detected in code completion\n");
     static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true);
     return 0;
-  }
+  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
+    PrintLibclangResourceUsage(TU);
 
   return CCAI.result;
 }
diff --git a/tools/libclang/CIndexer.h b/tools/libclang/CIndexer.h
index b40891a..45d0831 100644
--- a/tools/libclang/CIndexer.h
+++ b/tools/libclang/CIndexer.h
@@ -77,6 +77,9 @@
   /// \return False if a crash was detected.
   bool RunSafely(llvm::CrashRecoveryContext &CRC,
                  void (*Fn)(void*), void *UserData, unsigned Size = 0);
+
+  /// \brief Print libclang's resource usage to standard error.
+  void PrintLibclangResourceUsage(CXTranslationUnit TU);
 }
 
 #endif