Update Clang for 3.5 rebase (r209713).

Change-Id: I8c9133b0f8f776dc915f270b60f94962e771bc83
diff --git a/tools/c-arcmt-test/Makefile b/tools/c-arcmt-test/Makefile
index 6ac5e20..0be3bc1 100644
--- a/tools/c-arcmt-test/Makefile
+++ b/tools/c-arcmt-test/Makefile
@@ -27,9 +27,12 @@
 # when -static is given to linker on cygming.
 USEDLIBS = clang.a \
 	   clangARCMigrate.a \
+	   clangIndex.a \
+	   clangFormat.a \
+	   clangTooling.a \
 	   clangRewriteFrontend.a \
 	   clangRewriteCore.a \
-	   clangIndex.a clangFrontend.a clangDriver.a \
+	   clangFrontend.a clangDriver.a \
 	   clangStaticAnalyzerCheckers.a clangStaticAnalyzerCore.a \
 	   clangSerialization.a clangParse.a clangSema.a \
 	   clangAnalysis.a clangEdit.a clangAST.a clangLex.a clangBasic.a
diff --git a/tools/c-index-test/c-index-test.c b/tools/c-index-test/c-index-test.c
index f6b5510..dcae670 100644
--- a/tools/c-index-test/c-index-test.c
+++ b/tools/c-index-test/c-index-test.c
@@ -3,6 +3,7 @@
 #include "clang-c/Index.h"
 #include "clang-c/CXCompilationDatabase.h"
 #include "clang-c/BuildSystem.h"
+#include "clang-c/Documentation.h"
 #include "llvm/Config/config.h"
 #include <ctype.h>
 #include <stdlib.h>
@@ -541,33 +542,23 @@
   printf("]");
 }
 
-typedef struct {
-  const char *CommentSchemaFile;
+static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
 #ifdef CLANG_HAVE_LIBXML
   xmlRelaxNGParserCtxtPtr RNGParser;
   xmlRelaxNGPtr Schema;
-#endif
-} CommentXMLValidationData;
-
-static void ValidateCommentXML(const char *Str,
-                               CommentXMLValidationData *ValidationData) {
-#ifdef CLANG_HAVE_LIBXML
   xmlDocPtr Doc;
   xmlRelaxNGValidCtxtPtr ValidationCtxt;
   int status;
 
-  if (!ValidationData || !ValidationData->CommentSchemaFile)
+  if (!CommentSchemaFile)
     return;
 
-  if (!ValidationData->RNGParser) {
-    ValidationData->RNGParser =
-        xmlRelaxNGNewParserCtxt(ValidationData->CommentSchemaFile);
-    ValidationData->Schema = xmlRelaxNGParse(ValidationData->RNGParser);
-  }
-  if (!ValidationData->RNGParser) {
+  RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
+  if (!RNGParser) {
     printf(" libXMLError");
     return;
   }
+  Schema = xmlRelaxNGParse(RNGParser);
 
   Doc = xmlParseDoc((const xmlChar *) Str);
 
@@ -577,7 +568,7 @@
     return;
   }
 
-  ValidationCtxt = xmlRelaxNGNewValidCtxt(ValidationData->Schema);
+  ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
   status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
   if (!status)
     printf(" CommentXMLValid");
@@ -589,11 +580,13 @@
 
   xmlRelaxNGFreeValidCtxt(ValidationCtxt);
   xmlFreeDoc(Doc);
+  xmlRelaxNGFree(Schema);
+  xmlRelaxNGFreeParserCtxt(RNGParser);
 #endif
 }
 
 static void PrintCursorComments(CXCursor Cursor,
-                                CommentXMLValidationData *ValidationData) {
+                                const char *CommentSchemaFile) {
   {
     CXString RawComment;
     const char *RawCommentCString;
@@ -624,7 +617,7 @@
         CXString XML;
         XML = clang_FullComment_getAsXML(Comment);
         PrintCXStringWithPrefix("FullCommentAsXML", XML);
-        ValidateCommentXML(clang_getCString(XML), ValidationData);
+        ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
         clang_disposeString(XML);
       }
 
@@ -646,8 +639,7 @@
   return (int)lhs->col - (int)rhs->col;
 }
 
-static void PrintCursor(CXCursor Cursor,
-                        CommentXMLValidationData *ValidationData) {
+static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
   CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
   if (clang_isInvalid(Cursor.kind)) {
     CXString ks = clang_getCursorKindSpelling(Cursor.kind);
@@ -768,6 +760,8 @@
       printf(" (static)");
     if (clang_CXXMethod_isVirtual(Cursor))
       printf(" (virtual)");
+    if (clang_CXXMethod_isConst(Cursor))
+      printf(" (const)");
     if (clang_CXXMethod_isPureVirtual(Cursor))
       printf(" (pure)");
     if (clang_Cursor_isVariadic(Cursor))
@@ -866,7 +860,7 @@
         PrintRange(RefNameRange, "RefName");
     }
 
-    PrintCursorComments(Cursor, ValidationData);
+    PrintCursorComments(Cursor, CommentSchemaFile);
 
     {
       unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
@@ -983,7 +977,6 @@
         PrintExtent(out, start_line, start_column, end_line, end_column);
         fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
       }
-      break;
     }
     clang_disposeString(insertion_text);
   }
@@ -1036,7 +1029,7 @@
 typedef struct {
   CXTranslationUnit TU;
   enum CXCursorKind *Filter;
-  CommentXMLValidationData ValidationData;
+  const char *CommentSchemaFile;
 } VisitorData;
 
 
@@ -1050,7 +1043,7 @@
     clang_getSpellingLocation(Loc, 0, &line, &column, 0);
     printf("// %s: %s:%d:%d: ", FileCheckPrefix,
            GetCursorSource(Cursor), line, column);
-    PrintCursor(Cursor, &Data->ValidationData);
+    PrintCursor(Cursor, Data->CommentSchemaFile);
     PrintCursorExtent(Cursor);
     if (clang_isDeclaration(Cursor.kind)) {
       enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
@@ -1120,7 +1113,7 @@
       } else if (Ref.kind != CXCursor_FunctionDecl) {
         printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
                curLine, curColumn);
-        PrintCursor(Ref, &Data->ValidationData);
+        PrintCursor(Ref, Data->CommentSchemaFile);
         printf("\n");
       }
     }
@@ -1293,6 +1286,13 @@
     }
     /* Print if this is a non-POD type. */
     printf(" [isPOD=%d]", clang_isPODType(T));
+    /* Print the pointee type. */
+    {
+      CXType PT = clang_getPointeeType(T);
+      if (PT.kind != CXType_Invalid) {
+        PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
+      }
+    }
 
     printf("\n");
   }
@@ -1324,18 +1324,25 @@
   }
   /* Print the record field offset if applicable. */
   {
-    const char *FieldName = clang_getCString(clang_getCursorSpelling(cursor));
+    CXString FieldSpelling = clang_getCursorSpelling(cursor);
+    const char *FieldName = clang_getCString(FieldSpelling);
     /* recurse to get the root anonymous record parent */
     CXCursor Parent, Root;
-    if (clang_getCursorKind(cursor) == CXCursor_FieldDecl ) {
-      const char *RootParentName;
+    if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
+      CXString RootParentSpelling;
+      const char *RootParentName = 0;
       Parent = p;
       do {
+        if (RootParentName != 0)
+          clang_disposeString(RootParentSpelling);
+
         Root = Parent;
-        RootParentName = clang_getCString(clang_getCursorSpelling(Root));
+        RootParentSpelling = clang_getCursorSpelling(Root);
+        RootParentName = clang_getCString(RootParentSpelling);
         Parent = clang_getCursorSemanticParent(Root);
-      } while ( clang_getCursorType(Parent).kind == CXType_Record &&
-                !strcmp(RootParentName, "") );
+      } while (clang_getCursorType(Parent).kind == CXType_Record &&
+               !strcmp(RootParentName, ""));
+      clang_disposeString(RootParentSpelling);
       /* if RootParentName is "", record is anonymous. */
       {
         long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Root),
@@ -1343,6 +1350,7 @@
         printf(" [offsetof=%lld]", Offset);
       }
     }
+    clang_disposeString(FieldSpelling);
   }
   /* Print if its a bitfield */
   {
@@ -1412,11 +1420,7 @@
 
     Data.TU = TU;
     Data.Filter = ck;
-    Data.ValidationData.CommentSchemaFile = CommentSchemaFile;
-#ifdef CLANG_HAVE_LIBXML
-    Data.ValidationData.RNGParser = NULL;
-    Data.ValidationData.Schema = NULL;
-#endif
+    Data.CommentSchemaFile = CommentSchemaFile;
     clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
   }
 
@@ -1783,7 +1787,8 @@
   return 0;
 }
 
-void print_completion_string(CXCompletionString completion_string, FILE *file) {
+static void print_completion_string(CXCompletionString completion_string,
+                                    FILE *file) {
   int I, N;
 
   N = clang_getNumCompletionChunks(completion_string);
@@ -1817,9 +1822,8 @@
 
 }
 
-void print_completion_result(CXCompletionResult *completion_result,
-                             CXClientData client_data) {
-  FILE *file = (FILE *)client_data;
+static void print_completion_result(CXCompletionResult *completion_result,
+                                    FILE *file) {
   CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
   unsigned annotationCount;
   enum CXCursorKind ParentKind;
@@ -2226,7 +2230,8 @@
         }
         clang_disposeString(Spelling);
         if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
-          printf(" Selector index=%d",clang_Cursor_getObjCSelectorIndex(Cursor));
+          printf(" Selector index=%d",
+                 clang_Cursor_getObjCSelectorIndex(Cursor));
         if (clang_Cursor_isDynamicCall(Cursor))
           printf(" Dynamic-call");
         if (Cursor.kind == CXCursor_ObjCMessageExpr) {
@@ -2246,9 +2251,9 @@
             astFilename = clang_getFileName(astFile);
             name = clang_Module_getFullName(mod);
             numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
-            printf(" ModuleName=%s (%s) Headers(%d):",
+            printf(" ModuleName=%s (%s) system=%d Headers(%d):",
                    clang_getCString(name), clang_getCString(astFilename),
-                   numHeaders);
+                   clang_Module_isSystem(mod), numHeaders);
             clang_disposeString(name);
             clang_disposeString(astFilename);
             for (i = 0; i < numHeaders; ++i) {
@@ -2526,6 +2531,11 @@
   p->filenames[p->num_files++] = strdup(file);
 }
 
+typedef struct IndexDataStringList_ {
+  struct IndexDataStringList_ *next;
+  char data[1]; /* Dynamically sized. */
+} IndexDataStringList;
+
 typedef struct {
   const char *check_prefix;
   int first_check_printed;
@@ -2533,8 +2543,20 @@
   int abort;
   const char *main_filename;
   ImportedASTFilesData *importedASTs;
+  IndexDataStringList *strings;
+  CXTranslationUnit TU;
 } IndexData;
 
+static void free_client_data(IndexData *index_data) {
+  IndexDataStringList *node = index_data->strings;
+  while (node) {
+    IndexDataStringList *next = node->next;
+    free(node);
+    node = next;
+  }
+  index_data->strings = NULL;
+}
+
 static void printCheck(IndexData *data) {
   if (data->check_prefix) {
     if (data->first_check_printed) {
@@ -2595,8 +2617,11 @@
   }
 }
 
-static CXIdxClientContainer makeClientContainer(const CXIdxEntityInfo *info,
+static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
+                                                const CXIdxEntityInfo *info,
                                                 CXIdxLoc loc) {
+  IndexData *index_data;
+  IndexDataStringList *node;
   const char *name;
   char *newStr;
   CXIdxClientFile file;
@@ -2607,10 +2632,18 @@
     name = "<anon-tag>";
 
   clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
-  /* FIXME: free these.*/
-  newStr = (char *)malloc(strlen(name) +
-                          digitCount(line) + digitCount(column) + 3);
+
+  node =
+      (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
+                                    digitCount(line) + digitCount(column) + 2);
+  newStr = node->data;
   sprintf(newStr, "%s:%d:%d", name, line, column);
+
+  /* Remember string so it can be freed later. */
+  index_data = (IndexData *)client_data;
+  node->next = index_data->strings;
+  index_data->strings = node;
+
   return (CXIdxClientContainer)newStr;
 }
 
@@ -2781,6 +2814,7 @@
 static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
                                             const CXIdxIncludedFileInfo *info) {
   IndexData *index_data;
+  CXModule Mod;
   index_data = (IndexData *)client_data;
   printCheck(index_data);
 
@@ -2789,8 +2823,18 @@
   printf(" | name: \"%s\"", info->filename);
   printf(" | hash loc: ");
   printCXIndexLoc(info->hashLoc, client_data);
-  printf(" | isImport: %d | isAngled: %d | isModule: %d\n",
+  printf(" | isImport: %d | isAngled: %d | isModule: %d",
          info->isImport, info->isAngled, info->isModuleImport);
+  
+  Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
+  if (Mod) {
+    CXString str = clang_Module_getFullName(Mod);
+    const char *cstr = clang_getCString(str);
+    printf(" | module: %s", cstr);
+    clang_disposeString(str);
+  }
+
+  printf("\n");
 
   return (CXIdxClientFile)info->file;
 }
@@ -2824,8 +2868,8 @@
   return (CXIdxClientFile)info->file;
 }
 
-static CXIdxClientContainer index_startedTranslationUnit(CXClientData client_data,
-                                                   void *reserved) {
+static CXIdxClientContainer
+index_startedTranslationUnit(CXClientData client_data, void *reserved) {
   IndexData *index_data;
   index_data = (IndexData *)client_data;
   printCheck(index_data);
@@ -2926,13 +2970,15 @@
   }
 
   if (info->declAsContainer)
-    clang_index_setClientContainer(info->declAsContainer,
-                              makeClientContainer(info->entityInfo, info->loc));
+    clang_index_setClientContainer(
+        info->declAsContainer,
+        makeClientContainer(client_data, info->entityInfo, info->loc));
 }
 
 static void index_indexEntityReference(CXClientData client_data,
                                        const CXIdxEntityRefInfo *info) {
-  printEntityInfo("[indexEntityReference]", client_data, info->referencedEntity);
+  printEntityInfo("[indexEntityReference]", client_data,
+                  info->referencedEntity);
   printf(" | cursor: ");
   PrintCursor(info->cursor, NULL);
   printf(" | loc: ");
@@ -2997,6 +3043,8 @@
   index_data.abort = 0;
   index_data.main_filename = "";
   index_data.importedASTs = importedASTs;
+  index_data.strings = NULL;
+  index_data.TU = NULL;
 
   index_opts = getIndexOptions();
   result = clang_indexSourceFile(idxAction, &index_data,
@@ -3009,6 +3057,7 @@
   if (index_data.fail_for_error)
     result = -1;
 
+  free_client_data(&index_data);
   return result;
 }
 
@@ -3031,6 +3080,8 @@
   index_data.abort = 0;
   index_data.main_filename = "";
   index_data.importedASTs = importedASTs;
+  index_data.strings = NULL;
+  index_data.TU = TU;
 
   index_opts = getIndexOptions();
   result = clang_indexTranslationUnit(idxAction, &index_data,
@@ -3040,6 +3091,7 @@
     result = -1;
 
   clang_disposeTranslationUnit(TU);
+  free_client_data(&index_data);
   return result;
 }
 
@@ -3736,7 +3788,6 @@
 static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
   switch (severity) {
     case CXDiagnostic_Note: return "note";
-    case CXDiagnostic_Remark: return "remark";
     case CXDiagnostic_Error: return "error";
     case CXDiagnostic_Fatal: return "fatal";
     case CXDiagnostic_Ignored: return "ignored";
@@ -3857,6 +3908,7 @@
     clang_disposeString(FileName);
     clang_disposeString(DiagSpelling);
     clang_disposeString(DiagOption);
+    clang_disposeString(DiagCat);
   }  
 }
 
diff --git a/tools/clang-check/ClangCheck.cpp b/tools/clang-check/ClangCheck.cpp
index 4fc970c..cc8d43c 100644
--- a/tools/clang-check/ClangCheck.cpp
+++ b/tools/clang-check/ClangCheck.cpp
@@ -215,7 +215,7 @@
         Analyze ? "--analyze" : "-fsyntax-only", InsertAdjuster::BEGIN));
 
   clang_check::ClangCheckActionFactory CheckFactory;
-  FrontendActionFactory *FrontendFactory;
+  std::unique_ptr<FrontendActionFactory> FrontendFactory;
 
   // Choose the correct factory based on the selected mode.
   if (Analyze)
@@ -225,5 +225,5 @@
   else
     FrontendFactory = newFrontendActionFactory(&CheckFactory);
 
-  return Tool.run(FrontendFactory);
+  return Tool.run(FrontendFactory.get());
 }
diff --git a/tools/clang-format/ClangFormat.cpp b/tools/clang-format/ClangFormat.cpp
index 6f94461..189a611 100644
--- a/tools/clang-format/ClangFormat.cpp
+++ b/tools/clang-format/ClangFormat.cpp
@@ -68,7 +68,8 @@
               cl::desc("The name of the predefined style used as a\n"
                        "fallback in case clang-format is invoked with\n"
                        "-style=file, but can not find the .clang-format\n"
-                       "file to use."),
+                       "file to use.\n"
+                       "Use -fallback-style=none to skip formatting."),
               cl::init("LLVM"), cl::cat(ClangFormatCategory));
 
 static cl::opt<std::string>
@@ -246,8 +247,8 @@
         return true;
     } else {
       if (Cursor.getNumOccurrences() != 0)
-        outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
-                                          Replaces, Cursor) << " }\n";
+        outs() << "{ \"Cursor\": "
+               << tooling::shiftedCodePosition(Replaces, Cursor) << " }\n";
       Rewrite.getEditBuffer(ID).write(outs());
     }
   }
diff --git a/tools/clang-format/clang-format-diff.py b/tools/clang-format/clang-format-diff.py
index 376257b..d6d0d44 100755
--- a/tools/clang-format/clang-format-diff.py
+++ b/tools/clang-format/clang-format-diff.py
@@ -15,9 +15,10 @@
 
 This script reads input from a unified diff and reformats all the changed
 lines. This is useful to reformat all the lines touched by a specific patch.
-Example usage for git users:
+Example usage for git/svn users:
 
   git diff -U0 HEAD^ | clang-format-diff.py -p1 -i
+  svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
 
 """
 
diff --git a/tools/clang-format/clang-format.py b/tools/clang-format/clang-format.py
index 0c0da6e..16a1879 100644
--- a/tools/clang-format/clang-format.py
+++ b/tools/clang-format/clang-format.py
@@ -38,9 +38,14 @@
   text = '\n'.join(buf)
 
   # Determine range to format.
-  cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
   lines = '%s:%s' % (vim.current.range.start + 1, vim.current.range.end + 1)
 
+  # Determine the cursor position.
+  cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
+  if cursor < 0:
+    print 'Couldn\'t determine cursor position. Is your file empty?'
+    return
+
   # Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format.
   startupinfo = None
   if sys.platform.startswith('win32'):
@@ -59,12 +64,7 @@
 
   # If successful, replace buffer contents.
   if stderr:
-    message = stderr.splitlines()[0]
-    parts = message.split(' ', 2)
-    if len(parts) > 2:
-      message = parts[2]
-    print 'Formatting failed: %s (total %d warnings, %d errors)' % (
-        message, stderr.count('warning:'), stderr.count('error:'))
+    print stderr
 
   if not stdout:
     print ('No output from clang-format (crashed?).\n' +
diff --git a/tools/clang-format/git-clang-format b/tools/clang-format/git-clang-format
index b0737ed..c40b74d 100755
--- a/tools/clang-format/git-clang-format
+++ b/tools/clang-format/git-clang-format
@@ -75,6 +75,9 @@
       'm',  # ObjC
       'mm',  # ObjC++
       'cc', 'cp', 'cpp', 'c++', 'cxx', 'hpp',  # C++
+      # Other languages that clang-format supports
+      'proto', 'protodevel',  # Protocol Buffers
+      'js',  # JavaScript
       ])
 
   p = argparse.ArgumentParser(
diff --git a/tools/diagtool/DiagnosticNames.cpp b/tools/diagtool/DiagnosticNames.cpp
index 155c62d..f5df059 100644
--- a/tools/diagtool/DiagnosticNames.cpp
+++ b/tools/diagtool/DiagnosticNames.cpp
@@ -53,8 +53,8 @@
   DiagnosticRecord Key = {0, DiagID, 0};
 
   const DiagnosticRecord *Result =
-    std::lower_bound(BuiltinDiagnosticsByID,
-                     llvm::array_endof(BuiltinDiagnosticsByID),
+    std::lower_bound(std::begin(BuiltinDiagnosticsByID),
+                     std::end(BuiltinDiagnosticsByID),
                      Key, orderByID);
   assert(Result && "diagnostic not found; table may be out of date");
   return *Result;
diff --git a/tools/driver/Android.mk b/tools/driver/Android.mk
index e7af560..5c54644 100644
--- a/tools/driver/Android.mk
+++ b/tools/driver/Android.mk
@@ -91,7 +91,9 @@
   libLLVMCore \
   libLLVMOption \
   libLLVMSupport \
-  libLLVMTarget
+  libLLVMTarget \
+  libLLVMProfileData \
+  libLLVMObject
 
 LOCAL_LDLIBS += -lm
 ifdef USE_MINGW
diff --git a/tools/driver/CMakeLists.txt b/tools/driver/CMakeLists.txt
index f60162f..67d2115 100644
--- a/tools/driver/CMakeLists.txt
+++ b/tools/driver/CMakeLists.txt
@@ -10,6 +10,7 @@
   MCParser
   ObjCARCOpts
   Option
+  ProfileData
   ScalarOpts
   Support
   TransformUtils
diff --git a/tools/driver/Makefile b/tools/driver/Makefile
index d75b19c..7404496 100644
--- a/tools/driver/Makefile
+++ b/tools/driver/Makefile
@@ -33,7 +33,7 @@
 
 LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader bitwriter codegen \
                    instrumentation ipo irreader linker objcarcopts option \
-                   selectiondag
+                   profiledata selectiondag
 USEDLIBS = clangFrontendTool.a clangFrontend.a clangDriver.a \
            clangSerialization.a clangCodeGen.a clangParse.a clangSema.a
 
diff --git a/tools/driver/cc1as_main.cpp b/tools/driver/cc1as_main.cpp
index 8521c2a..c4456e2 100644
--- a/tools/driver/cc1as_main.cpp
+++ b/tools/driver/cc1as_main.cpp
@@ -34,6 +34,7 @@
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/MC/MCTargetAsmParser.h"
+#include "llvm/MC/MCTargetOptions.h"
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Option/OptTable.h"
@@ -86,6 +87,7 @@
   unsigned SaveTemporaryLabels : 1;
   unsigned GenDwarfForAssembly : 1;
   unsigned CompressDebugSections : 1;
+  unsigned DwarfVersion;
   std::string DwarfDebugFlags;
   std::string DwarfDebugProducer;
   std::string DebugCompilationDir;
@@ -136,6 +138,7 @@
     ShowEncoding = 0;
     RelaxAll = 0;
     NoExecStack = 0;
+    DwarfVersion = 3;
   }
 
   static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
@@ -188,6 +191,12 @@
   Opts.SaveTemporaryLabels = Args->hasArg(OPT_msave_temp_labels);
   Opts.GenDwarfForAssembly = Args->hasArg(OPT_g);
   Opts.CompressDebugSections = Args->hasArg(OPT_compress_debug_sections);
+  if (Args->hasArg(OPT_gdwarf_2))
+    Opts.DwarfVersion = 2;
+  if (Args->hasArg(OPT_gdwarf_3))
+    Opts.DwarfVersion = 3;
+  if (Args->hasArg(OPT_gdwarf_4))
+    Opts.DwarfVersion = 4;
   Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
   Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
   Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
@@ -326,6 +335,7 @@
     Ctx.setCompilationDir(Opts.DebugCompilationDir);
   if (!Opts.MainFileName.empty())
     Ctx.setMainFileName(StringRef(Opts.MainFileName));
+  Ctx.setDwarfVersion(Opts.DwarfVersion);
 
   // Build up the feature string from the target feature list.
   std::string FS;
@@ -353,7 +363,6 @@
       MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
     }
     Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
-                                           /*useCFI*/ true,
                                            /*useDwarfDirectory*/ true,
                                            IP, CE, MAB,
                                            Opts.ShowInst));
@@ -373,8 +382,11 @@
 
   std::unique_ptr<MCAsmParser> Parser(
       createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
+
+  // FIXME: init MCTargetOptions from sanitizer flags here.
+  MCTargetOptions Options;
   std::unique_ptr<MCTargetAsmParser> TAP(
-      TheTarget->createMCAsmParser(*STI, *Parser, *MCII));
+      TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
   if (!TAP) {
     Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
     return false;
diff --git a/tools/driver/driver.cpp b/tools/driver/driver.cpp
index beb271f..fd13555 100644
--- a/tools/driver/driver.cpp
+++ b/tools/driver/driver.cpp
@@ -371,7 +371,7 @@
   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
   ProcessWarningOptions(Diags, *DiagOpts, /*ReportDiags=*/false);
 
-  Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), "a.out", Diags);
+  Driver TheDriver(Path, llvm::sys::getDefaultTargetTriple(), Diags);
 
   // Attempt to find the original path used to invoke the driver, to determine
   // the installed path. We do this manually, because we want to support that
diff --git a/tools/libclang/BuildSystem.cpp b/tools/libclang/BuildSystem.cpp
index 89c6e91..e9423c3 100644
--- a/tools/libclang/BuildSystem.cpp
+++ b/tools/libclang/BuildSystem.cpp
@@ -13,9 +13,9 @@
 
 #include "clang-c/BuildSystem.h"
 #include "CXString.h"
-#include "llvm/ADT/ArrayRef.h"
+#include "clang/Basic/VirtualFileSystem.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/Optional.h"
+#include "llvm/Support/CBindingWrapping.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/TimeValue.h"
 #include "llvm/Support/raw_ostream.h"
@@ -27,13 +27,11 @@
   return llvm::sys::TimeValue::now().toEpochTime();
 }
 
-struct CXVirtualFileOverlayImpl {
-  std::vector<std::pair<std::string, std::string> > Mappings;
-  Optional<bool> IsCaseSensitive;
-};
+DEFINE_SIMPLE_CONVERSION_FUNCTIONS(clang::vfs::YAMLVFSWriter,
+                                   CXVirtualFileOverlay)
 
 CXVirtualFileOverlay clang_VirtualFileOverlay_create(unsigned) {
-  return new CXVirtualFileOverlayImpl();
+  return wrap(new clang::vfs::YAMLVFSWriter());
 }
 
 enum CXErrorCode
@@ -55,7 +53,7 @@
       return CXError_InvalidArguments;
   }
 
-  VFO->Mappings.push_back(std::make_pair(virtualPath, realPath));
+  unwrap(VFO)->addFileMapping(virtualPath, realPath);
   return CXError_Success;
 }
 
@@ -64,125 +62,10 @@
                                             int caseSensitive) {
   if (!VFO)
     return CXError_InvalidArguments;
-
-  VFO->IsCaseSensitive = caseSensitive;
+  unwrap(VFO)->setCaseSensitivity(caseSensitive);
   return CXError_Success;
 }
 
-namespace {
-struct EntryTy {
-  std::string VPath;
-  std::string RPath;
-
-  friend bool operator < (const EntryTy &LHS, const EntryTy &RHS) {
-    return LHS.VPath < RHS.VPath;
-  }
-};
-
-class JSONVFSPrinter {
-  llvm::raw_ostream &OS;
-  CXVirtualFileOverlay VFO;
-
-public:
-  JSONVFSPrinter(llvm::raw_ostream &OS, CXVirtualFileOverlay VFO)
-    : OS(OS), VFO(VFO) {}
-
-  /// Entries must be sorted.
-  void print(ArrayRef<EntryTy> Entries) {
-    OS << "{\n"
-          "  'version': 0,\n";
-    if (VFO->IsCaseSensitive.hasValue()) {
-      OS << "  'case-sensitive': '";
-      if (VFO->IsCaseSensitive.getValue())
-        OS << "true";
-      else
-        OS << "false";
-      OS << "',\n";
-    }
-    OS << "  'roots': [\n";
-    printDirNodes(Entries, "", 4);
-    OS << "  ]\n"
-          "}\n";
-  }
-
-private:
-  ArrayRef<EntryTy> printDirNodes(ArrayRef<EntryTy> Entries,
-                                  StringRef ParentPath,
-                                  unsigned Indent) {
-    while (!Entries.empty()) {
-      const EntryTy &Entry = Entries.front();
-      OS.indent(Indent) << "{\n";
-      Indent += 2;
-      OS.indent(Indent) << "'type': 'directory',\n";
-      OS.indent(Indent) << "'name': \"";
-      StringRef DirName = containedPart(ParentPath,
-                                        path::parent_path(Entry.VPath));
-      OS.write_escaped(DirName) << "\",\n";
-      OS.indent(Indent) << "'contents': [\n";
-      Entries = printContents(Entries, Indent + 2);
-      OS.indent(Indent) << "]\n";
-      Indent -= 2;
-      OS.indent(Indent) << '}';
-      if (Entries.empty()) {
-        OS << '\n';
-        break;
-      }
-      StringRef NextVPath = Entries.front().VPath;
-      if (!containedIn(ParentPath, NextVPath)) {
-        OS << '\n';
-        break;
-      }
-      OS << ",\n";
-    }
-    return Entries;
-  }
-
-  ArrayRef<EntryTy> printContents(ArrayRef<EntryTy> Entries,
-                                  unsigned Indent) {
-    while (!Entries.empty()) {
-      const EntryTy &Entry = Entries.front();
-      Entries = Entries.slice(1);
-      StringRef ParentPath = path::parent_path(Entry.VPath);
-      StringRef VName = path::filename(Entry.VPath);
-      OS.indent(Indent) << "{\n";
-      Indent += 2;
-      OS.indent(Indent) << "'type': 'file',\n";
-      OS.indent(Indent) << "'name': \"";
-      OS.write_escaped(VName) << "\",\n";
-      OS.indent(Indent) << "'external-contents': \"";
-      OS.write_escaped(Entry.RPath) << "\"\n";
-      Indent -= 2;
-      OS.indent(Indent) << '}';
-      if (Entries.empty()) {
-        OS << '\n';
-        break;
-      }
-      StringRef NextVPath = Entries.front().VPath;
-      if (!containedIn(ParentPath, NextVPath)) {
-        OS << '\n';
-        break;
-      }
-      OS << ",\n";
-      if (path::parent_path(NextVPath) != ParentPath) {
-        Entries = printDirNodes(Entries, ParentPath, Indent);
-      }
-    }
-    return Entries;
-  }
-
-  bool containedIn(StringRef Parent, StringRef Path) {
-    return Path.startswith(Parent);
-  }
-
-  StringRef containedPart(StringRef Parent, StringRef Path) {
-    assert(containedIn(Parent, Path));
-    if (Parent.empty())
-      return Path;
-    return Path.slice(Parent.size()+1, StringRef::npos);
-  }
-};
-}
-
 enum CXErrorCode
 clang_VirtualFileOverlay_writeToBuffer(CXVirtualFileOverlay VFO, unsigned,
                                        char **out_buffer_ptr,
@@ -190,24 +73,9 @@
   if (!VFO || !out_buffer_ptr || !out_buffer_size)
     return CXError_InvalidArguments;
 
-  llvm::SmallVector<EntryTy, 16> Entries;
-  for (unsigned i = 0, e = VFO->Mappings.size(); i != e; ++i) {
-    EntryTy Entry;
-    Entry.VPath = VFO->Mappings[i].first;
-    Entry.RPath = VFO->Mappings[i].second;
-    Entries.push_back(Entry);
-  }
-
-  // FIXME: We should add options to determine if the paths are case sensitive
-  // or not. The following assumes that if paths are case-insensitive the caller
-  // did not mix cases in the virtual paths it provided.
-
-  std::sort(Entries.begin(), Entries.end());
-
   llvm::SmallString<256> Buf;
   llvm::raw_svector_ostream OS(Buf);
-  JSONVFSPrinter Printer(OS, VFO);
-  Printer.print(Entries);
+  unwrap(VFO)->write(OS);
 
   StringRef Data = OS.str();
   *out_buffer_ptr = (char*)malloc(Data.size());
@@ -217,7 +85,7 @@
 }
 
 void clang_VirtualFileOverlay_dispose(CXVirtualFileOverlay VFO) {
-  delete VFO;
+  delete unwrap(VFO);
 }
 
 
diff --git a/tools/libclang/CIndex.cpp b/tools/libclang/CIndex.cpp
index 04797a9..bc1174a 100644
--- a/tools/libclang/CIndex.cpp
+++ b/tools/libclang/CIndex.cpp
@@ -15,7 +15,6 @@
 #include "CIndexer.h"
 #include "CIndexDiagnostic.h"
 #include "CLog.h"
-#include "CXComment.h"
 #include "CXCursor.h"
 #include "CXSourceLocation.h"
 #include "CXString.h"
@@ -1936,8 +1935,14 @@
   Visitor->AddStmt(C->getSafelen());
 }
 
+void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
+  Visitor->AddStmt(C->getNumForLoops());
+}
+
 void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) { }
 
+void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) { }
+
 template<typename T>
 void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
   for (const auto *I : Node->varlists())
@@ -1954,6 +1959,10 @@
 void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
   VisitOMPClauseList(C);
 }
+void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
+  VisitOMPClauseList(C);
+  Visitor->AddStmt(C->getStep());
+}
 void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
   VisitOMPClauseList(C);
 }
@@ -3864,6 +3873,12 @@
     return cxstring::createRef("asm label");
   case CXCursor_PackedAttr:
     return cxstring::createRef("attribute(packed)");
+  case CXCursor_PureAttr:
+    return cxstring::createRef("attribute(pure)");
+  case CXCursor_ConstAttr:
+    return cxstring::createRef("attribute(const)");
+  case CXCursor_NoDuplicateAttr:
+    return cxstring::createRef("attribute(noduplicate)");
   case CXCursor_PreprocessingDirective:
     return cxstring::createRef("preprocessing directive");
   case CXCursor_MacroDefinition:
@@ -5683,14 +5698,13 @@
         break;
 
       MacroInfo *MI = 0;
-      if (Tok.is(tok::raw_identifier) &&
-          StringRef(Tok.getRawIdentifierData(), Tok.getLength()) == "define") {
+      if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
         if (lexNext(Lex, Tok, NextIdx, NumTokens))
           break;
 
         if (Tok.is(tok::raw_identifier)) {
-          StringRef Name(Tok.getRawIdentifierData(), Tok.getLength());
-          IdentifierInfo &II = PP.getIdentifierTable().get(Name);
+          IdentifierInfo &II =
+              PP.getIdentifierTable().get(Tok.getRawIdentifier());
           SourceLocation MappedTokLoc =
               CXXUnit->mapLocationToPreamble(Tok.getLocation());
           MI = getMacroInfo(II, MappedTokLoc, TU);
@@ -6029,8 +6043,10 @@
       HadAvailAttr = true;
       if (always_deprecated)
         *always_deprecated = 1;
-      if (deprecated_message)
+      if (deprecated_message) {
+        clang_disposeString(*deprecated_message);
         *deprecated_message = cxstring::createDup(Deprecated->getMessage());
+      }
       continue;
     }
     
@@ -6039,6 +6055,7 @@
       if (always_unavailable)
         *always_unavailable = 1;
       if (unavailable_message) {
+        clang_disposeString(*unavailable_message);
         *unavailable_message = cxstring::createDup(Unavailable->getMessage());
       }
       continue;
@@ -6305,17 +6322,6 @@
   return cxstring::createNull();
 }
 
-CXComment clang_Cursor_getParsedComment(CXCursor C) {
-  if (!clang_isDeclaration(C.kind))
-    return cxcomment::createCXComment(NULL, NULL);
-
-  const Decl *D = getCursorDecl(C);
-  const ASTContext &Context = getCursorContext(C);
-  const comments::FullComment *FC = Context.getCommentForDecl(D, /*PP=*/ NULL);
-
-  return cxcomment::createCXComment(FC, getCursorTU(C));
-}
-
 CXModule clang_Cursor_getModule(CXCursor C) {
   if (C.kind == CXCursor_ModuleImportDecl) {
     if (const ImportDecl *ImportD =
@@ -6326,6 +6332,26 @@
   return 0;
 }
 
+CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
+  if (isNotUsableTU(TU)) {
+    LOG_BAD_TU(TU);
+    return nullptr;
+  }
+  if (!File)
+    return nullptr;
+  FileEntry *FE = static_cast<FileEntry *>(File);
+  
+  ASTUnit &Unit = *cxtu::getASTUnit(TU);
+  HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
+  ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
+  
+  if (Module *Mod = Header.getModule()) {
+    if (Header.getRole() != ModuleMap::ExcludedHeader)
+      return Mod;
+  }
+  return nullptr;
+}
+
 CXFile clang_Module_getASTFile(CXModule CXMod) {
   if (!CXMod)
     return 0;
@@ -6354,6 +6380,13 @@
   return cxstring::createDup(Mod->getFullModuleName());
 }
 
+int clang_Module_isSystem(CXModule CXMod) {
+  if (!CXMod)
+    return 0;
+  Module *Mod = static_cast<Module*>(CXMod);
+  return Mod->IsSystem;
+}
+
 unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
                                             CXModule CXMod) {
   if (isNotUsableTU(TU)) {
@@ -6403,6 +6436,16 @@
   return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
 }
 
+unsigned clang_CXXMethod_isConst(CXCursor C) {
+  if (!clang_isDeclaration(C.kind))
+    return 0;
+
+  const Decl *D = cxcursor::getCursorDecl(C);
+  const CXXMethodDecl *Method =
+      D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : 0;
+  return (Method && (Method->getTypeQualifiers() & Qualifiers::Const)) ? 1 : 0;
+}
+
 unsigned clang_CXXMethod_isStatic(CXCursor C) {
   if (!clang_isDeclaration(C.kind))
     return 0;
@@ -6706,7 +6749,7 @@
   for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), 
                                   DEnd = Unit->stored_diag_end();
        D != DEnd; ++D) {
-    CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOpts());
+    CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
     CXString Msg = clang_formatDiagnostic(&Diag,
                                 clang_defaultDiagnosticDisplayOptions());
     fprintf(stderr, "%s\n", clang_getCString(Msg));
@@ -6779,8 +6822,7 @@
   if (!PPRec)
     return 0;
 
-  StringRef Name(Tok.getRawIdentifierData(), Tok.getLength());
-  IdentifierInfo &II = PP.getIdentifierTable().get(Name);
+  IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
   if (!II.hadMacroDefinition())
     return 0;
 
diff --git a/tools/libclang/CIndexCodeCompletion.cpp b/tools/libclang/CIndexCodeCompletion.cpp
index 5912945..dbf54a1 100644
--- a/tools/libclang/CIndexCodeCompletion.cpp
+++ b/tools/libclang/CIndexCodeCompletion.cpp
@@ -249,12 +249,15 @@
 /// AllocatedCXCodeCompleteResults outlives the CXTranslationUnit, so we can
 /// not rely on the StringPool in the TU.
 struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
-  AllocatedCXCodeCompleteResults(const FileSystemOptions& FileSystemOpts);
+  AllocatedCXCodeCompleteResults(IntrusiveRefCntPtr<FileManager> FileMgr);
   ~AllocatedCXCodeCompleteResults();
   
   /// \brief Diagnostics produced while performing code completion.
   SmallVector<StoredDiagnostic, 8> Diagnostics;
 
+  /// \brief Allocated API-exposed wrappters for Diagnostics.
+  SmallVector<CXStoredDiagnostic *, 8> DiagnosticsWrappers;
+
   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
   
   /// \brief Diag object
@@ -263,8 +266,6 @@
   /// \brief Language options used to adjust source locations.
   LangOptions LangOpts;
 
-  FileSystemOptions FileSystemOpts;
-
   /// \brief File manager, used for diagnostics.
   IntrusiveRefCntPtr<FileManager> FileMgr;
 
@@ -318,26 +319,22 @@
 static std::atomic<unsigned> CodeCompletionResultObjects;
   
 AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
-                                      const FileSystemOptions& FileSystemOpts)
-  : CXCodeCompleteResults(),
-    DiagOpts(new DiagnosticOptions),
-    Diag(new DiagnosticsEngine(
-                   IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
-                   &*DiagOpts)),
-    FileSystemOpts(FileSystemOpts),
-    FileMgr(new FileManager(FileSystemOpts)),
-    SourceMgr(new SourceManager(*Diag, *FileMgr)),
-    CodeCompletionAllocator(new clang::GlobalCodeCompletionAllocator),
-    Contexts(CXCompletionContext_Unknown),
-    ContainerKind(CXCursor_InvalidCode),
-    ContainerIsIncomplete(1)
-{ 
+    IntrusiveRefCntPtr<FileManager> FileMgr)
+    : CXCodeCompleteResults(),
+      DiagOpts(new DiagnosticOptions),
+      Diag(new DiagnosticsEngine(
+          IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts)),
+      FileMgr(FileMgr), SourceMgr(new SourceManager(*Diag, *FileMgr)),
+      CodeCompletionAllocator(new clang::GlobalCodeCompletionAllocator),
+      Contexts(CXCompletionContext_Unknown),
+      ContainerKind(CXCursor_InvalidCode), ContainerIsIncomplete(1) {
   if (getenv("LIBCLANG_OBJTRACKING"))
     fprintf(stderr, "+++ %u completion results\n",
             ++CodeCompletionResultObjects);
 }
   
 AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
+  llvm::DeleteContainerPointers(DiagnosticsWrappers);
   delete [] Results;
 
   for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
@@ -709,8 +706,8 @@
   }
 
   // Parse the resulting source file to find code-completion results.
-  AllocatedCXCodeCompleteResults *Results = 
-        new AllocatedCXCodeCompleteResults(AST->getFileSystemOpts());
+  AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults(
+      &AST->getFileManager());
   Results->Results = 0;
   Results->NumResults = 0;
   
@@ -729,7 +726,9 @@
                     *Results->Diag, Results->LangOpts, *Results->SourceMgr,
                     *Results->FileMgr, Results->Diagnostics,
                     Results->TemporaryBuffers);
-  
+
+  Results->DiagnosticsWrappers.resize(Results->Diagnostics.size());
+
   // Keep a reference to the allocator used for cached global completions, so
   // that we can be sure that the memory used by our code completion strings
   // doesn't get freed due to subsequent reparses (while the code completion
@@ -876,7 +875,11 @@
   if (!Results || Index >= Results->Diagnostics.size())
     return 0;
 
-  return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
+  CXStoredDiagnostic *Diag = Results->DiagnosticsWrappers[Index];
+  if (!Diag)
+    Results->DiagnosticsWrappers[Index] = Diag =
+        new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
+  return Diag;
 }
 
 unsigned long long
diff --git a/tools/libclang/CIndexDiagnostic.cpp b/tools/libclang/CIndexDiagnostic.cpp
index cf9dc6f..8a57d7d 100644
--- a/tools/libclang/CIndexDiagnostic.cpp
+++ b/tools/libclang/CIndexDiagnostic.cpp
@@ -308,7 +308,6 @@
   switch (Severity) {
   case CXDiagnostic_Ignored: llvm_unreachable("impossible");
   case CXDiagnostic_Note: Out << "note: "; break;
-  case CXDiagnostic_Remark: Out << "remark: "; break;
   case CXDiagnostic_Warning: Out << "warning: "; break;
   case CXDiagnostic_Error: Out << "error: "; break;
   case CXDiagnostic_Fatal: Out << "fatal error: "; break;
diff --git a/tools/libclang/CXComment.cpp b/tools/libclang/CXComment.cpp
index 2c4f269..8fb7c0a 100644
--- a/tools/libclang/CXComment.cpp
+++ b/tools/libclang/CXComment.cpp
@@ -12,6 +12,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang-c/Index.h"
+#include "clang-c/Documentation.h"
 #include "CXComment.h"
 #include "CXCursor.h"
 #include "CXString.h"
@@ -28,6 +29,19 @@
 
 extern "C" {
 
+CXComment clang_Cursor_getParsedComment(CXCursor C) {
+  using namespace clang::cxcursor;
+
+  if (!clang_isDeclaration(C.kind))
+    return createCXComment(NULL, NULL);
+
+  const Decl *D = getCursorDecl(C);
+  const ASTContext &Context = getCursorContext(C);
+  const FullComment *FC = Context.getCommentForDecl(D, /*PP=*/NULL);
+
+  return createCXComment(FC, getCursorTU(C));
+}
+
 enum CXCommentKind clang_Comment_getKind(CXComment CXC) {
   const Comment *C = getASTNode(CXC);
   if (!C)
diff --git a/tools/libclang/CXComment.h b/tools/libclang/CXComment.h
index 1e2561d..606ee26 100644
--- a/tools/libclang/CXComment.h
+++ b/tools/libclang/CXComment.h
@@ -16,6 +16,7 @@
 
 #include "CXTranslationUnit.h"
 #include "clang-c/Index.h"
+#include "clang-c/Documentation.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Comment.h"
 #include "clang/Frontend/ASTUnit.h"
diff --git a/tools/libclang/CXCursor.cpp b/tools/libclang/CXCursor.cpp
index d682986..fb4ce66 100644
--- a/tools/libclang/CXCursor.cpp
+++ b/tools/libclang/CXCursor.cpp
@@ -50,6 +50,9 @@
     case attr::Annotate: return CXCursor_AnnotateAttr;
     case attr::AsmLabel: return CXCursor_AsmLabelAttr;
     case attr::Packed: return CXCursor_PackedAttr;
+    case attr::Pure: return CXCursor_PureAttr;
+    case attr::Const: return CXCursor_ConstAttr;
+    case attr::NoDuplicate: return CXCursor_NoDuplicateAttr;
   }
 
   return CXCursor_UnexposedAttr;
diff --git a/tools/libclang/CXLoadedDiagnostic.cpp b/tools/libclang/CXLoadedDiagnostic.cpp
index 679c528..8385f24 100644
--- a/tools/libclang/CXLoadedDiagnostic.cpp
+++ b/tools/libclang/CXLoadedDiagnostic.cpp
@@ -79,8 +79,9 @@
   CASE(Warning)
   CASE(Error)
   CASE(Fatal)
-  CASE(Remark)
 #undef CASE
+  // The 'Remark' level isn't represented in the stable API.
+  case serialized_diags::Remark: return CXDiagnostic_Warning;
   }
   
   llvm_unreachable("Invalid diagnostic level");
diff --git a/tools/libclang/CXStoredDiagnostic.cpp b/tools/libclang/CXStoredDiagnostic.cpp
index 45ce39b..faaf746 100644
--- a/tools/libclang/CXStoredDiagnostic.cpp
+++ b/tools/libclang/CXStoredDiagnostic.cpp
@@ -31,7 +31,8 @@
   switch (Diag.getLevel()) {
     case DiagnosticsEngine::Ignored: return CXDiagnostic_Ignored;
     case DiagnosticsEngine::Note:    return CXDiagnostic_Note;
-    case DiagnosticsEngine::Remark:  return CXDiagnostic_Remark;
+    case DiagnosticsEngine::Remark:
+    // The 'Remark' level isn't represented in the stable API.
     case DiagnosticsEngine::Warning: return CXDiagnostic_Warning;
     case DiagnosticsEngine::Error:   return CXDiagnostic_Error;
     case DiagnosticsEngine::Fatal:   return CXDiagnostic_Fatal;
diff --git a/tools/libclang/IndexBody.cpp b/tools/libclang/IndexBody.cpp
index 6cc8062..fbec3d7 100644
--- a/tools/libclang/IndexBody.cpp
+++ b/tools/libclang/IndexBody.cpp
@@ -149,13 +149,13 @@
     return true;
   }
 
-  bool TraverseLambdaCapture(LambdaExpr::Capture C) {
-    if (C.capturesThis())
+  bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C) {
+    if (C->capturesThis())
       return true;
 
-    if (C.capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols())
-      IndexCtx.handleReference(C.getCapturedVar(), C.getLocation(),
-                               Parent, ParentDC);
+    if (C->capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols())
+      IndexCtx.handleReference(C->getCapturedVar(), C->getLocation(), Parent,
+                               ParentDC);
 
     // FIXME: Lambda init-captures.
     return true;
diff --git a/tools/libclang/Indexing.cpp b/tools/libclang/Indexing.cpp
index 55e6e79..47ba97b 100644
--- a/tools/libclang/Indexing.cpp
+++ b/tools/libclang/Indexing.cpp
@@ -610,6 +610,11 @@
   ASTUnit *Unit = ASTUnit::create(CInvok.getPtr(), Diags,
                                   CaptureDiagnostics,
                                   /*UserFilesAreVolatile=*/true);
+  if (!Unit) {
+    ITUI->result = CXError_InvalidArguments;
+    return;
+  }
+
   std::unique_ptr<CXTUOwner> CXTU(
       new CXTUOwner(MakeCXTranslationUnit(CXXIdx, Unit)));
 
diff --git a/tools/libclang/libclang.exports b/tools/libclang/libclang.exports
index 37b6159..48eec25 100644
--- a/tools/libclang/libclang.exports
+++ b/tools/libclang/libclang.exports
@@ -2,6 +2,7 @@
 clang_CXCursorSet_insert
 clang_CXIndex_getGlobalOptions
 clang_CXIndex_setGlobalOptions
+clang_CXXMethod_isConst
 clang_CXXMethod_isPureVirtual
 clang_CXXMethod_isStatic
 clang_CXXMethod_isVirtual
@@ -29,6 +30,7 @@
 clang_Module_getFullName
 clang_Module_getNumTopLevelHeaders
 clang_Module_getTopLevelHeader
+clang_Module_isSystem
 clang_IndexAction_create
 clang_IndexAction_dispose
 clang_Range_isNull
@@ -193,6 +195,7 @@
 clang_getInstantiationLocation
 clang_getLocation
 clang_getLocationForOffset
+clang_getModuleForFile
 clang_getNullCursor
 clang_getNullLocation
 clang_getNullRange
diff --git a/tools/scan-build/ccc-analyzer b/tools/scan-build/ccc-analyzer
index b5445e6..087f0f0 100755
--- a/tools/scan-build/ccc-analyzer
+++ b/tools/scan-build/ccc-analyzer
@@ -71,10 +71,10 @@
 # Remove any stale files at exit.
 END {
   if (defined $ResultFile && -z $ResultFile) {
-    `rm -f $ResultFile`;
+    unlink($ResultFile);
   }
   if (defined $CleanupFile) {
-    `rm -f $CleanupFile`;
+    unlink($CleanupFile);
   }
 }
 
@@ -127,7 +127,7 @@
   close OUT;
   `uname -a >> $PPFile.info.txt 2>&1`;
   `$Compiler -v >> $PPFile.info.txt 2>&1`;
-  system 'mv',$ofile,"$PPFile.stderr.txt";
+  rename($ofile, "$PPFile.stderr.txt");
   return (basename $PPFile);
 }
 
@@ -353,6 +353,7 @@
   '-m32' => 0,
   '-m64' => 0,
   '-stdlib' => 0, # This is really a 1 argument, but always has '='
+  '--sysroot' => 1,
   '-target' => 1,
   '-v' => 0,
   '-mmacosx-version-min' => 0, # This is really a 1 argument, but always has '='
diff --git a/tools/scan-build/scan-build b/tools/scan-build/scan-build
index 31dbfb4..7502a42 100755
--- a/tools/scan-build/scan-build
+++ b/tools/scan-build/scan-build
@@ -18,6 +18,8 @@
 use Digest::MD5;
 use File::Basename;
 use File::Find;
+use File::Copy qw(copy);
+use File::Path qw( rmtree mkpath );
 use Term::ANSIColor;
 use Term::ANSIColor qw(:constants);
 use Cwd qw/ getcwd abs_path /;
@@ -204,7 +206,7 @@
   else {
     $NewDir = "$Dir/$DateString-$RunNumber";
   }
-  system 'mkdir','-p',$NewDir;
+  mkpath($NewDir);
   return $NewDir;
 }
 
@@ -293,7 +295,7 @@
 
   close (ROUT);
   close (RIN);
-  system("mv", "$fname.tmp", $fname);
+  rename("$fname.tmp", $fname)
 }
 
 ##----------------------------------------------------------------------------##
@@ -352,14 +354,14 @@
 
   if (defined $AlreadyScanned{$digest}) {
     # Redundant file.  Remove it.
-    system ("rm", "-f", "$Dir/$FName");
+    unlink("$Dir/$FName");
     return;
   }
 
   $AlreadyScanned{$digest} = 1;
 
   # At this point the report file is not world readable.  Make it happen.
-  system ("chmod", "644", "$Dir/$FName");
+  chmod(0644, "$Dir/$FName");
 
   # Scan the report file for tags.
   open(IN, "$Dir/$FName") or DieDiag("Cannot open '$Dir/$FName'\n");
@@ -424,7 +426,7 @@
   DieDiag("Cannot find 'sorttable.js'.\n")
     if (! -r $JS);
 
-  system ("cp", $JS, "$Dir");
+  copy($JS, "$Dir");
 
   DieDiag("Could not copy 'sorttable.js' to '$Dir'.\n")
     if (! -r "$Dir/sorttable.js");
@@ -434,7 +436,7 @@
   DieDiag("Cannot find 'scanview.css'.\n")
     if (! -r $CSS);
 
-  system ("cp", $CSS, "$Dir");
+  copy($CSS, "$Dir");
 
   DieDiag("Could not copy 'scanview.css' to '$Dir'.\n")
     if (! -r $CSS);
@@ -523,7 +525,7 @@
   if (scalar(@filesFound) == 0 and ! -e "$Dir/failures") {
     if (! $KeepEmpty) {
       Diag("Removing directory '$Dir' because it contains no reports.\n");
-      system ("rm", "-fR", $Dir);
+      rmtree($Dir) or die "Cannot rmtree '$Dir' : $!";
     }
     Diag("No bugs found.\n");
     return 0;
@@ -844,14 +846,18 @@
   CopyFiles($Dir);
 
   # Make sure $Dir and $BaseDir are world readable/executable.
-  system("chmod", "755", $Dir);
-  if (defined $BaseDir) { system("chmod", "755", $BaseDir); }
+  chmod(0755, $Dir);
+  if (defined $BaseDir) { chmod(0755, $BaseDir); }
 
   # Print statistics
   print CalcStats(\@Stats) if $AnalyzerStats;
 
   my $Num = scalar(@Index);
-  Diag("$Num bugs found.\n");
+  if ($Num == 1) {
+    Diag("$Num bug found.\n");
+  } else {
+    Diag("$Num bugs found.\n");
+  }
   if ($Num > 0 && -r "$Dir/index.html") {
     Diag("Run 'scan-view $Dir' to examine bug reports.\n");
   }
@@ -1584,7 +1590,7 @@
     }
   }
   else {
-    $Clang = Cwd::realpath($AnalyzerDiscoveryMethod);
+    $Clang = $AnalyzerDiscoveryMethod;
 	if (!defined $Clang or not -x $Clang) {
    	  DieDiag("Cannot find an executable clang at '$AnalyzerDiscoveryMethod'\n");
 	}
diff --git a/tools/scan-build/set-xcode-analyzer b/tools/scan-build/set-xcode-analyzer
index 5ac5c18..8e67482 100755
--- a/tools/scan-build/set-xcode-analyzer
+++ b/tools/scan-build/set-xcode-analyzer
@@ -100,7 +100,7 @@
   if (xcode_path.find(".app/") != -1):
     # Cut off the 'Developer' dir, as the xcspec lies in another part
     # of the Xcode.app subtree.
-    xcode_path = os.path.dirname(xcode_path)
+    xcode_path = xcode_path.rsplit('/Developer', 1)[0]
 
   foundSpec = False
   for x in FindClangSpecs(xcode_path):