1ee3c74fbSChris Lattner //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2ee3c74fbSChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ee3c74fbSChris Lattner //
7ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
8ee3c74fbSChris Lattner //
9ee3c74fbSChris Lattner // FileCheck does a line-by line check of a file that validates whether it
10ee3c74fbSChris Lattner // contains the expected content.  This is useful for regression tests etc.
11ee3c74fbSChris Lattner //
12b5ecceffSJames Henderson // This program exits with an exit status of 2 on error, exit status of 0 if
13ee3c74fbSChris Lattner // the file matched the expected contents, and exit status of 1 if it did not
14ee3c74fbSChris Lattner // contain the expected contents.
15ee3c74fbSChris Lattner //
16ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
17ee3c74fbSChris Lattner 
18ee3c74fbSChris Lattner #include "llvm/Support/CommandLine.h"
19197194b6SRui Ueyama #include "llvm/Support/InitLLVM.h"
203e66509fSJoel E. Denny #include "llvm/Support/Process.h"
213c5d267eSJoel E. Denny #include "llvm/Support/WithColor.h"
22ee3c74fbSChris Lattner #include "llvm/Support/raw_ostream.h"
23ffa9d2e4SAditya Nandakumar #include "llvm/Support/FileCheck.h"
24010982f7SRainer Orth #include <cmath>
25ee3c74fbSChris Lattner using namespace llvm;
26ee3c74fbSChris Lattner 
27dbb757f4SJoel E. Denny static cl::extrahelp FileCheckOptsEnv(
28dbb757f4SJoel E. Denny     "\nOptions are parsed from the environment variable FILECHECK_OPTS and\n"
29dbb757f4SJoel E. Denny     "from the command line.\n");
30dbb757f4SJoel E. Denny 
31ee3c74fbSChris Lattner static cl::opt<std::string>
323c5d267eSJoel E. Denny     CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Optional);
33ee3c74fbSChris Lattner 
34ee3c74fbSChris Lattner static cl::opt<std::string>
35ee3c74fbSChris Lattner     InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
36ee3c74fbSChris Lattner                   cl::init("-"), cl::value_desc("filename"));
37ee3c74fbSChris Lattner 
38e8f2fb20SChandler Carruth static cl::list<std::string> CheckPrefixes(
39e8f2fb20SChandler Carruth     "check-prefix",
40ee3c74fbSChris Lattner     cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
41fd557cb0SDaniel Sanders static cl::alias CheckPrefixesAlias(
42fd557cb0SDaniel Sanders     "check-prefixes", cl::aliasopt(CheckPrefixes), cl::CommaSeparated,
43fd557cb0SDaniel Sanders     cl::NotHidden,
44fd557cb0SDaniel Sanders     cl::desc(
45fd557cb0SDaniel Sanders         "Alias for -check-prefix permitting multiple comma separated values"));
46ee3c74fbSChris Lattner 
47e8f2fb20SChandler Carruth static cl::opt<bool> NoCanonicalizeWhiteSpace(
48e8f2fb20SChandler Carruth     "strict-whitespace",
492c3e5cdfSChris Lattner     cl::desc("Do not treat all horizontal whitespace as equivalent"));
502c3e5cdfSChris Lattner 
515b5b2fd2SKai Nacke static cl::opt<bool> IgnoreCase(
525b5b2fd2SKai Nacke     "ignore-case",
535b5b2fd2SKai Nacke     cl::desc("Use case-insensitive matching"));
545b5b2fd2SKai Nacke 
5556ccdbbdSAlexander Kornienko static cl::list<std::string> ImplicitCheckNot(
5656ccdbbdSAlexander Kornienko     "implicit-check-not",
5756ccdbbdSAlexander Kornienko     cl::desc("Add an implicit negative check with this pattern to every\n"
5856ccdbbdSAlexander Kornienko              "positive check. This can be used to ensure that no instances of\n"
5956ccdbbdSAlexander Kornienko              "this pattern occur which are not matched by a positive pattern"),
6056ccdbbdSAlexander Kornienko     cl::value_desc("pattern"));
6156ccdbbdSAlexander Kornienko 
62a5e233bfSThomas Preud'homme static cl::list<std::string>
63a5e233bfSThomas Preud'homme     GlobalDefines("D", cl::AlwaysPrefix,
6446e1fd61SAlexander Richardson                   cl::desc("Define a variable to be used in capture patterns."),
6546e1fd61SAlexander Richardson                   cl::value_desc("VAR=VALUE"));
6646e1fd61SAlexander Richardson 
671b9f936fSJustin Bogner static cl::opt<bool> AllowEmptyInput(
681b9f936fSJustin Bogner     "allow-empty", cl::init(false),
691b9f936fSJustin Bogner     cl::desc("Allow the input file to be empty. This is useful when making\n"
701b9f936fSJustin Bogner              "checks that some error message does not occur, for example."));
711b9f936fSJustin Bogner 
7285913ccaSJames Y Knight static cl::opt<bool> MatchFullLines(
7385913ccaSJames Y Knight     "match-full-lines", cl::init(false),
7485913ccaSJames Y Knight     cl::desc("Require all positive matches to cover an entire input line.\n"
7585913ccaSJames Y Knight              "Allows leading and trailing whitespace if --strict-whitespace\n"
7685913ccaSJames Y Knight              "is not also passed."));
7785913ccaSJames Y Knight 
78f55e72a5SArtem Belevich static cl::opt<bool> EnableVarScope(
79f55e72a5SArtem Belevich     "enable-var-scope", cl::init(false),
80f55e72a5SArtem Belevich     cl::desc("Enables scope for regex variables. Variables with names that\n"
81f55e72a5SArtem Belevich              "do not start with '$' will be reset at the beginning of\n"
82f55e72a5SArtem Belevich              "each CHECK-LABEL block."));
83f55e72a5SArtem Belevich 
84bcf5b441SJoel E. Denny static cl::opt<bool> AllowDeprecatedDagOverlap(
85bcf5b441SJoel E. Denny     "allow-deprecated-dag-overlap", cl::init(false),
86bcf5b441SJoel E. Denny     cl::desc("Enable overlapping among matches in a group of consecutive\n"
87bcf5b441SJoel E. Denny              "CHECK-DAG directives.  This option is deprecated and is only\n"
88bcf5b441SJoel E. Denny              "provided for convenience as old tests are migrated to the new\n"
89bcf5b441SJoel E. Denny              "non-overlapping CHECK-DAG implementation.\n"));
90bcf5b441SJoel E. Denny 
91352695c3SJoel E. Denny static cl::opt<bool> Verbose(
92352695c3SJoel E. Denny     "v", cl::init(false),
93352695c3SJoel E. Denny     cl::desc("Print directive pattern matches, or add them to the input dump\n"
94352695c3SJoel E. Denny              "if enabled.\n"));
95dc5ba317SJoel E. Denny 
96dc5ba317SJoel E. Denny static cl::opt<bool> VerboseVerbose(
97dc5ba317SJoel E. Denny     "vv", cl::init(false),
98dc5ba317SJoel E. Denny     cl::desc("Print information helpful in diagnosing internal FileCheck\n"
99352695c3SJoel E. Denny              "issues, or add it to the input dump if enabled.  Implies\n"
100352695c3SJoel E. Denny              "-v.\n"));
101346dfbe2SGeorge Karpenkov static const char * DumpInputEnv = "FILECHECK_DUMP_INPUT_ON_FAILURE";
102346dfbe2SGeorge Karpenkov 
103346dfbe2SGeorge Karpenkov static cl::opt<bool> DumpInputOnFailure(
104ffc722a3SMichal Gorny     "dump-input-on-failure",
105ffc722a3SMichal Gorny     cl::init(std::getenv(DumpInputEnv) && *std::getenv(DumpInputEnv)),
106346dfbe2SGeorge Karpenkov     cl::desc("Dump original input to stderr before failing.\n"
107346dfbe2SGeorge Karpenkov              "The value can be also controlled using\n"
1083c5d267eSJoel E. Denny              "FILECHECK_DUMP_INPUT_ON_FAILURE environment variable.\n"
1093c5d267eSJoel E. Denny              "This option is deprecated in favor of -dump-input=fail.\n"));
1103c5d267eSJoel E. Denny 
111fdde18a7SJoel E. Denny // The order of DumpInputValue members affects their precedence, as documented
112fdde18a7SJoel E. Denny // for -dump-input below.
1133c5d267eSJoel E. Denny enum DumpInputValue {
1143c5d267eSJoel E. Denny   DumpInputDefault,
1153c5d267eSJoel E. Denny   DumpInputNever,
1163c5d267eSJoel E. Denny   DumpInputFail,
117fdde18a7SJoel E. Denny   DumpInputAlways,
118fdde18a7SJoel E. Denny   DumpInputHelp
1193c5d267eSJoel E. Denny };
1203c5d267eSJoel E. Denny 
121fdde18a7SJoel E. Denny static cl::list<DumpInputValue> DumpInputs(
122fdde18a7SJoel E. Denny     "dump-input",
1233c5d267eSJoel E. Denny     cl::desc("Dump input to stderr, adding annotations representing\n"
124fdde18a7SJoel E. Denny              "currently enabled diagnostics.  When there are multiple\n"
125fdde18a7SJoel E. Denny              "occurrences of this option, the <value> that appears earliest\n"
126fdde18a7SJoel E. Denny              "in the list below has precedence.\n"),
1273c5d267eSJoel E. Denny     cl::value_desc("mode"),
1283c5d267eSJoel E. Denny     cl::values(clEnumValN(DumpInputHelp, "help",
1293c5d267eSJoel E. Denny                           "Explain dump format and quit"),
130fdde18a7SJoel E. Denny                clEnumValN(DumpInputAlways, "always", "Always dump input"),
1313c5d267eSJoel E. Denny                clEnumValN(DumpInputFail, "fail", "Dump input on failure"),
132fdde18a7SJoel E. Denny                clEnumValN(DumpInputNever, "never", "Never dump input")));
133dc5ba317SJoel E. Denny 
13413df4626SMatt Arsenault typedef cl::list<std::string>::const_iterator prefix_iterator;
13513df4626SMatt Arsenault 
13613df4626SMatt Arsenault 
13713df4626SMatt Arsenault 
138726774cbSChandler Carruth 
139726774cbSChandler Carruth 
140726774cbSChandler Carruth 
141c2735158SRui Ueyama 
1422bd4f8b6SXinliang David Li static void DumpCommandLine(int argc, char **argv) {
1432bd4f8b6SXinliang David Li   errs() << "FileCheck command line: ";
1442bd4f8b6SXinliang David Li   for (int I = 0; I < argc; I++)
1452bd4f8b6SXinliang David Li     errs() << " " << argv[I];
1462bd4f8b6SXinliang David Li   errs() << "\n";
1472bd4f8b6SXinliang David Li }
1482bd4f8b6SXinliang David Li 
1493c5d267eSJoel E. Denny struct MarkerStyle {
1503c5d267eSJoel E. Denny   /// The starting char (before tildes) for marking the line.
1513c5d267eSJoel E. Denny   char Lead;
1523c5d267eSJoel E. Denny   /// What color to use for this annotation.
1534d41c332SRui Ueyama   raw_ostream::Colors Color;
1543c5d267eSJoel E. Denny   /// A note to follow the marker, or empty string if none.
1553c5d267eSJoel E. Denny   std::string Note;
1563c5d267eSJoel E. Denny   MarkerStyle() {}
1574d41c332SRui Ueyama   MarkerStyle(char Lead, raw_ostream::Colors Color,
1584d41c332SRui Ueyama               const std::string &Note = "")
1593c5d267eSJoel E. Denny       : Lead(Lead), Color(Color), Note(Note) {}
1603c5d267eSJoel E. Denny };
1613c5d267eSJoel E. Denny 
1623c5d267eSJoel E. Denny static MarkerStyle GetMarker(FileCheckDiag::MatchType MatchTy) {
1633c5d267eSJoel E. Denny   switch (MatchTy) {
164e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundAndExpected:
1657df86967SJoel E. Denny     return MarkerStyle('^', raw_ostream::GREEN);
166e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundButExcluded:
1670e7e3fa0SJoel E. Denny     return MarkerStyle('!', raw_ostream::RED, "error: no match expected");
168e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundButWrongLine:
169cadfcef4SJoel E. Denny     return MarkerStyle('!', raw_ostream::RED, "error: match on wrong line");
170e2afb614SJoel E. Denny   case FileCheckDiag::MatchFoundButDiscarded:
171f7c1c4d8SJoel E. Denny     return MarkerStyle('!', raw_ostream::CYAN,
172f7c1c4d8SJoel E. Denny                        "discard: overlaps earlier match");
17396f0e84cSJoel E. Denny   case FileCheckDiag::MatchNoneAndExcluded:
17496f0e84cSJoel E. Denny     return MarkerStyle('X', raw_ostream::GREEN);
1753c5d267eSJoel E. Denny   case FileCheckDiag::MatchNoneButExpected:
1763c5d267eSJoel E. Denny     return MarkerStyle('X', raw_ostream::RED, "error: no match found");
1772c007c80SJoel E. Denny   case FileCheckDiag::MatchFuzzy:
1782c007c80SJoel E. Denny     return MarkerStyle('?', raw_ostream::MAGENTA, "possible intended match");
1793c5d267eSJoel E. Denny   }
1803c5d267eSJoel E. Denny   llvm_unreachable_internal("unexpected match type");
1813c5d267eSJoel E. Denny }
1823c5d267eSJoel E. Denny 
1833c5d267eSJoel E. Denny static void DumpInputAnnotationHelp(raw_ostream &OS) {
1843c5d267eSJoel E. Denny   OS << "The following description was requested by -dump-input=help to\n"
1853c5d267eSJoel E. Denny      << "explain the input annotations printed by -dump-input=always and\n"
1863c5d267eSJoel E. Denny      << "-dump-input=fail:\n\n";
1873c5d267eSJoel E. Denny 
1883c5d267eSJoel E. Denny   // Labels for input lines.
1893c5d267eSJoel E. Denny   OS << "  - ";
1903c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "L:";
1913c5d267eSJoel E. Denny   OS << "     labels line number L of the input file\n";
1923c5d267eSJoel E. Denny 
1933c5d267eSJoel E. Denny   // Labels for annotation lines.
1943c5d267eSJoel E. Denny   OS << "  - ";
1953c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L";
196*b5a24610SJoel E. Denny   OS << "    labels the only match result for either (1) a pattern of type T"
197*b5a24610SJoel E. Denny      << " from\n"
198*b5a24610SJoel E. Denny      << "           line L of the check file if L is an integer or (2) the"
199*b5a24610SJoel E. Denny      << " I-th implicit\n"
200*b5a24610SJoel E. Denny      << "           pattern if L is \"imp\" followed by an integer "
201*b5a24610SJoel E. Denny      << "I (index origin one)\n";
2022c007c80SJoel E. Denny   OS << "  - ";
2032c007c80SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L'N";
204*b5a24610SJoel E. Denny   OS << "  labels the Nth match result for such a pattern\n";
2053c5d267eSJoel E. Denny 
2063c5d267eSJoel E. Denny   // Markers on annotation lines.
2073c5d267eSJoel E. Denny   OS << "  - ";
2087df86967SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "^~~";
2097df86967SJoel E. Denny   OS << "    marks good match (reported if -v)\n"
2107df86967SJoel E. Denny      << "  - ";
211cadfcef4SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "!~~";
212cadfcef4SJoel E. Denny   OS << "    marks bad match, such as:\n"
213cadfcef4SJoel E. Denny      << "           - CHECK-NEXT on same line as previous match (error)\n"
2140e7e3fa0SJoel E. Denny      << "           - CHECK-NOT found (error)\n"
215f7c1c4d8SJoel E. Denny      << "           - CHECK-DAG overlapping match (discarded, reported if "
216f7c1c4d8SJoel E. Denny      << "-vv)\n"
217cadfcef4SJoel E. Denny      << "  - ";
2183c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "X~~";
219cadfcef4SJoel E. Denny   OS << "    marks search range when no match is found, such as:\n"
220cadfcef4SJoel E. Denny      << "           - CHECK-NEXT not found (error)\n"
22196f0e84cSJoel E. Denny      << "           - CHECK-NOT not found (success, reported if -vv)\n"
222f7c1c4d8SJoel E. Denny      << "           - CHECK-DAG not found after discarded matches (error)\n"
2232c007c80SJoel E. Denny      << "  - ";
2242c007c80SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "?";
2252c007c80SJoel E. Denny   OS << "      marks fuzzy match when no match is found\n";
2263c5d267eSJoel E. Denny 
2273c5d267eSJoel E. Denny   // Colors.
2283c5d267eSJoel E. Denny   OS << "  - colors ";
2297df86967SJoel E. Denny   WithColor(OS, raw_ostream::GREEN, true) << "success";
2307df86967SJoel E. Denny   OS << ", ";
2313c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::RED, true) << "error";
2322c007c80SJoel E. Denny   OS << ", ";
2332c007c80SJoel E. Denny   WithColor(OS, raw_ostream::MAGENTA, true) << "fuzzy match";
2347df86967SJoel E. Denny   OS << ", ";
235f7c1c4d8SJoel E. Denny   WithColor(OS, raw_ostream::CYAN, true, false) << "discarded match";
236f7c1c4d8SJoel E. Denny   OS << ", ";
2377df86967SJoel E. Denny   WithColor(OS, raw_ostream::CYAN, true, true) << "unmatched input";
2383c5d267eSJoel E. Denny   OS << "\n\n"
2393c5d267eSJoel E. Denny      << "If you are not seeing color above or in input dumps, try: -color\n";
2403c5d267eSJoel E. Denny }
2413c5d267eSJoel E. Denny 
2423c5d267eSJoel E. Denny /// An annotation for a single input line.
2433c5d267eSJoel E. Denny struct InputAnnotation {
2443c5d267eSJoel E. Denny   /// The check file line (one-origin indexing) where the directive that
2453c5d267eSJoel E. Denny   /// produced this annotation is located.
2463c5d267eSJoel E. Denny   unsigned CheckLine;
2472c007c80SJoel E. Denny   /// The index of the match result for this check.
2482c007c80SJoel E. Denny   unsigned CheckDiagIndex;
2493c5d267eSJoel E. Denny   /// The label for this annotation.
2503c5d267eSJoel E. Denny   std::string Label;
2513c5d267eSJoel E. Denny   /// What input line (one-origin indexing) this annotation marks.  This might
2523c5d267eSJoel E. Denny   /// be different from the starting line of the original diagnostic if this is
2533c5d267eSJoel E. Denny   /// a non-initial fragment of a diagnostic that has been broken across
2543c5d267eSJoel E. Denny   /// multiple lines.
2553c5d267eSJoel E. Denny   unsigned InputLine;
2563c5d267eSJoel E. Denny   /// The column range (one-origin indexing, open end) in which to to mark the
2573c5d267eSJoel E. Denny   /// input line.  If InputEndCol is UINT_MAX, treat it as the last column
2583c5d267eSJoel E. Denny   /// before the newline.
2593c5d267eSJoel E. Denny   unsigned InputStartCol, InputEndCol;
2603c5d267eSJoel E. Denny   /// The marker to use.
2613c5d267eSJoel E. Denny   MarkerStyle Marker;
262e2afb614SJoel E. Denny   /// Whether this annotation represents a good match for an expected pattern.
263e2afb614SJoel E. Denny   bool FoundAndExpectedMatch;
2643c5d267eSJoel E. Denny };
2653c5d267eSJoel E. Denny 
2663c5d267eSJoel E. Denny /// Get an abbreviation for the check type.
2673c5d267eSJoel E. Denny std::string GetCheckTypeAbbreviation(Check::FileCheckType Ty) {
2683c5d267eSJoel E. Denny   switch (Ty) {
2693c5d267eSJoel E. Denny   case Check::CheckPlain:
2703c5d267eSJoel E. Denny     if (Ty.getCount() > 1)
2713c5d267eSJoel E. Denny       return "count";
2723c5d267eSJoel E. Denny     return "check";
2733c5d267eSJoel E. Denny   case Check::CheckNext:
2743c5d267eSJoel E. Denny     return "next";
2753c5d267eSJoel E. Denny   case Check::CheckSame:
2763c5d267eSJoel E. Denny     return "same";
2773c5d267eSJoel E. Denny   case Check::CheckNot:
2783c5d267eSJoel E. Denny     return "not";
2793c5d267eSJoel E. Denny   case Check::CheckDAG:
2803c5d267eSJoel E. Denny     return "dag";
2813c5d267eSJoel E. Denny   case Check::CheckLabel:
2823c5d267eSJoel E. Denny     return "label";
2833c5d267eSJoel E. Denny   case Check::CheckEmpty:
2843c5d267eSJoel E. Denny     return "empty";
2853c5d267eSJoel E. Denny   case Check::CheckEOF:
2863c5d267eSJoel E. Denny     return "eof";
2873c5d267eSJoel E. Denny   case Check::CheckBadNot:
2883c5d267eSJoel E. Denny     return "bad-not";
2893c5d267eSJoel E. Denny   case Check::CheckBadCount:
2903c5d267eSJoel E. Denny     return "bad-count";
2913c5d267eSJoel E. Denny   case Check::CheckNone:
2923c5d267eSJoel E. Denny     llvm_unreachable("invalid FileCheckType");
2933c5d267eSJoel E. Denny   }
2943c5d267eSJoel E. Denny   llvm_unreachable("unknown FileCheckType");
2953c5d267eSJoel E. Denny }
2963c5d267eSJoel E. Denny 
297*b5a24610SJoel E. Denny static void
298*b5a24610SJoel E. Denny BuildInputAnnotations(const SourceMgr &SM, unsigned CheckFileBufferID,
299*b5a24610SJoel E. Denny                       const std::pair<unsigned, unsigned> &ImpPatBufferIDRange,
300*b5a24610SJoel E. Denny                       const std::vector<FileCheckDiag> &Diags,
3013c5d267eSJoel E. Denny                       std::vector<InputAnnotation> &Annotations,
3023c5d267eSJoel E. Denny                       unsigned &LabelWidth) {
3032c007c80SJoel E. Denny   // How many diagnostics has the current check seen so far?
3042c007c80SJoel E. Denny   unsigned CheckDiagCount = 0;
3053c5d267eSJoel E. Denny   // What's the widest label?
3063c5d267eSJoel E. Denny   LabelWidth = 0;
3073c5d267eSJoel E. Denny   for (auto DiagItr = Diags.begin(), DiagEnd = Diags.end(); DiagItr != DiagEnd;
3083c5d267eSJoel E. Denny        ++DiagItr) {
3093c5d267eSJoel E. Denny     InputAnnotation A;
3103c5d267eSJoel E. Denny 
3113c5d267eSJoel E. Denny     // Build label, which uniquely identifies this check result.
312*b5a24610SJoel E. Denny     unsigned CheckBufferID = SM.FindBufferContainingLoc(DiagItr->CheckLoc);
313*b5a24610SJoel E. Denny     auto CheckLineAndCol =
314*b5a24610SJoel E. Denny         SM.getLineAndColumn(DiagItr->CheckLoc, CheckBufferID);
315*b5a24610SJoel E. Denny     A.CheckLine = CheckLineAndCol.first;
3163c5d267eSJoel E. Denny     llvm::raw_string_ostream Label(A.Label);
317*b5a24610SJoel E. Denny     Label << GetCheckTypeAbbreviation(DiagItr->CheckTy) << ":";
318*b5a24610SJoel E. Denny     if (CheckBufferID == CheckFileBufferID)
319*b5a24610SJoel E. Denny       Label << CheckLineAndCol.first;
320*b5a24610SJoel E. Denny     else if (ImpPatBufferIDRange.first <= CheckBufferID &&
321*b5a24610SJoel E. Denny              CheckBufferID < ImpPatBufferIDRange.second)
322*b5a24610SJoel E. Denny       Label << "imp" << (CheckBufferID - ImpPatBufferIDRange.first + 1);
323*b5a24610SJoel E. Denny     else
324*b5a24610SJoel E. Denny       llvm_unreachable("expected diagnostic's check location to be either in "
325*b5a24610SJoel E. Denny                        "the check file or for an implicit pattern");
3262c007c80SJoel E. Denny     A.CheckDiagIndex = UINT_MAX;
3272c007c80SJoel E. Denny     auto DiagNext = std::next(DiagItr);
3282c007c80SJoel E. Denny     if (DiagNext != DiagEnd && DiagItr->CheckTy == DiagNext->CheckTy &&
329*b5a24610SJoel E. Denny         DiagItr->CheckLoc == DiagNext->CheckLoc)
3302c007c80SJoel E. Denny       A.CheckDiagIndex = CheckDiagCount++;
3312c007c80SJoel E. Denny     else if (CheckDiagCount) {
3322c007c80SJoel E. Denny       A.CheckDiagIndex = CheckDiagCount;
3332c007c80SJoel E. Denny       CheckDiagCount = 0;
3342c007c80SJoel E. Denny     }
3352c007c80SJoel E. Denny     if (A.CheckDiagIndex != UINT_MAX)
3362c007c80SJoel E. Denny       Label << "'" << A.CheckDiagIndex;
3372c007c80SJoel E. Denny     else
3382c007c80SJoel E. Denny       A.CheckDiagIndex = 0;
3393c5d267eSJoel E. Denny     Label.flush();
3403c5d267eSJoel E. Denny     LabelWidth = std::max((std::string::size_type)LabelWidth, A.Label.size());
3413c5d267eSJoel E. Denny 
342608f2bfdSJoel E. Denny     A.Marker = GetMarker(DiagItr->MatchTy);
343e2afb614SJoel E. Denny     A.FoundAndExpectedMatch =
344e2afb614SJoel E. Denny         DiagItr->MatchTy == FileCheckDiag::MatchFoundAndExpected;
3453c5d267eSJoel E. Denny 
3463c5d267eSJoel E. Denny     // Compute the mark location, and break annotation into multiple
3473c5d267eSJoel E. Denny     // annotations if it spans multiple lines.
3483c5d267eSJoel E. Denny     A.InputLine = DiagItr->InputStartLine;
3493c5d267eSJoel E. Denny     A.InputStartCol = DiagItr->InputStartCol;
3503c5d267eSJoel E. Denny     if (DiagItr->InputStartLine == DiagItr->InputEndLine) {
3513c5d267eSJoel E. Denny       // Sometimes ranges are empty in order to indicate a specific point, but
3523c5d267eSJoel E. Denny       // that would mean nothing would be marked, so adjust the range to
3533c5d267eSJoel E. Denny       // include the following character.
3543c5d267eSJoel E. Denny       A.InputEndCol =
3553c5d267eSJoel E. Denny           std::max(DiagItr->InputStartCol + 1, DiagItr->InputEndCol);
3563c5d267eSJoel E. Denny       Annotations.push_back(A);
3573c5d267eSJoel E. Denny     } else {
3583c5d267eSJoel E. Denny       assert(DiagItr->InputStartLine < DiagItr->InputEndLine &&
3593c5d267eSJoel E. Denny              "expected input range not to be inverted");
3603c5d267eSJoel E. Denny       A.InputEndCol = UINT_MAX;
3613c5d267eSJoel E. Denny       Annotations.push_back(A);
3623c5d267eSJoel E. Denny       for (unsigned L = DiagItr->InputStartLine + 1, E = DiagItr->InputEndLine;
3633c5d267eSJoel E. Denny            L <= E; ++L) {
3643c5d267eSJoel E. Denny         // If a range ends before the first column on a line, then it has no
3653c5d267eSJoel E. Denny         // characters on that line, so there's nothing to render.
366608f2bfdSJoel E. Denny         if (DiagItr->InputEndCol == 1 && L == E)
3673c5d267eSJoel E. Denny           break;
3683c5d267eSJoel E. Denny         InputAnnotation B;
3693c5d267eSJoel E. Denny         B.CheckLine = A.CheckLine;
3702c007c80SJoel E. Denny         B.CheckDiagIndex = A.CheckDiagIndex;
3713c5d267eSJoel E. Denny         B.Label = A.Label;
3723c5d267eSJoel E. Denny         B.InputLine = L;
373608f2bfdSJoel E. Denny         B.Marker = A.Marker;
3743c5d267eSJoel E. Denny         B.Marker.Lead = '~';
3753c5d267eSJoel E. Denny         B.Marker.Note = "";
376608f2bfdSJoel E. Denny         B.InputStartCol = 1;
377608f2bfdSJoel E. Denny         if (L != E)
378608f2bfdSJoel E. Denny           B.InputEndCol = UINT_MAX;
379608f2bfdSJoel E. Denny         else
3803c5d267eSJoel E. Denny           B.InputEndCol = DiagItr->InputEndCol;
381e2afb614SJoel E. Denny         B.FoundAndExpectedMatch = A.FoundAndExpectedMatch;
3823c5d267eSJoel E. Denny         Annotations.push_back(B);
3833c5d267eSJoel E. Denny       }
3843c5d267eSJoel E. Denny     }
3853c5d267eSJoel E. Denny   }
3863c5d267eSJoel E. Denny }
3873c5d267eSJoel E. Denny 
3887df86967SJoel E. Denny static void DumpAnnotatedInput(raw_ostream &OS, const FileCheckRequest &Req,
3897df86967SJoel E. Denny                                StringRef InputFileText,
3907df86967SJoel E. Denny                                std::vector<InputAnnotation> &Annotations,
3917df86967SJoel E. Denny                                unsigned LabelWidth) {
3923c5d267eSJoel E. Denny   OS << "Full input was:\n<<<<<<\n";
3933c5d267eSJoel E. Denny 
3943c5d267eSJoel E. Denny   // Sort annotations.
3953c5d267eSJoel E. Denny   //
3963c5d267eSJoel E. Denny   // First, sort in the order of input lines to make it easier to find relevant
3973c5d267eSJoel E. Denny   // annotations while iterating input lines in the implementation below.
3983c5d267eSJoel E. Denny   // FileCheck diagnostics are not always reported and recorded in the order of
3993c5d267eSJoel E. Denny   // input lines due to, for example, CHECK-DAG and CHECK-NOT.
4003c5d267eSJoel E. Denny   //
4013c5d267eSJoel E. Denny   // Second, for annotations for the same input line, sort in the order of the
4023c5d267eSJoel E. Denny   // FileCheck directive's line in the check file (where there's at most one
4032c007c80SJoel E. Denny   // directive per line) and then by the index of the match result for that
4042c007c80SJoel E. Denny   // directive.  The rationale of this choice is that, for any input line, this
4052c007c80SJoel E. Denny   // sort establishes a total order of annotations that, with respect to match
4062c007c80SJoel E. Denny   // results, is consistent across multiple lines, thus making match results
4072c007c80SJoel E. Denny   // easier to track from one line to the next when they span multiple lines.
4083c5d267eSJoel E. Denny   std::sort(Annotations.begin(), Annotations.end(),
4093c5d267eSJoel E. Denny             [](const InputAnnotation &A, const InputAnnotation &B) {
4103c5d267eSJoel E. Denny               if (A.InputLine != B.InputLine)
4113c5d267eSJoel E. Denny                 return A.InputLine < B.InputLine;
4122c007c80SJoel E. Denny               if (A.CheckLine != B.CheckLine)
4133c5d267eSJoel E. Denny                 return A.CheckLine < B.CheckLine;
4147df86967SJoel E. Denny               // FIXME: Sometimes CHECK-LABEL reports its match twice with
4157df86967SJoel E. Denny               // other diagnostics in between, and then diag index incrementing
4167df86967SJoel E. Denny               // fails to work properly, and then this assert fails.  We should
4177df86967SJoel E. Denny               // suppress one of those diagnostics or do a better job of
4187df86967SJoel E. Denny               // computing this index.  For now, we just produce a redundant
4197df86967SJoel E. Denny               // CHECK-LABEL annotation.
4207df86967SJoel E. Denny               // assert(A.CheckDiagIndex != B.CheckDiagIndex &&
4217df86967SJoel E. Denny               //        "expected diagnostic indices to be unique within a "
4227df86967SJoel E. Denny               //        " check line");
4232c007c80SJoel E. Denny               return A.CheckDiagIndex < B.CheckDiagIndex;
4243c5d267eSJoel E. Denny             });
4253c5d267eSJoel E. Denny 
4263c5d267eSJoel E. Denny   // Compute the width of the label column.
4273c5d267eSJoel E. Denny   const unsigned char *InputFilePtr = InputFileText.bytes_begin(),
4283c5d267eSJoel E. Denny                       *InputFileEnd = InputFileText.bytes_end();
4293c5d267eSJoel E. Denny   unsigned LineCount = InputFileText.count('\n');
4303c5d267eSJoel E. Denny   if (InputFileEnd[-1] != '\n')
4313c5d267eSJoel E. Denny     ++LineCount;
432010982f7SRainer Orth   unsigned LineNoWidth = std::log10(LineCount) + 1;
4333c5d267eSJoel E. Denny   // +3 below adds spaces (1) to the left of the (right-aligned) line numbers
4343c5d267eSJoel E. Denny   // on input lines and (2) to the right of the (left-aligned) labels on
4353c5d267eSJoel E. Denny   // annotation lines so that input lines and annotation lines are more
4363c5d267eSJoel E. Denny   // visually distinct.  For example, the spaces on the annotation lines ensure
4373c5d267eSJoel E. Denny   // that input line numbers and check directive line numbers never align
4383c5d267eSJoel E. Denny   // horizontally.  Those line numbers might not even be for the same file.
4393c5d267eSJoel E. Denny   // One space would be enough to achieve that, but more makes it even easier
4403c5d267eSJoel E. Denny   // to see.
4413c5d267eSJoel E. Denny   LabelWidth = std::max(LabelWidth, LineNoWidth) + 3;
4423c5d267eSJoel E. Denny 
4433c5d267eSJoel E. Denny   // Print annotated input lines.
4443c5d267eSJoel E. Denny   auto AnnotationItr = Annotations.begin(), AnnotationEnd = Annotations.end();
4453c5d267eSJoel E. Denny   for (unsigned Line = 1;
4463c5d267eSJoel E. Denny        InputFilePtr != InputFileEnd || AnnotationItr != AnnotationEnd;
4473c5d267eSJoel E. Denny        ++Line) {
4483c5d267eSJoel E. Denny     const unsigned char *InputFileLine = InputFilePtr;
4493c5d267eSJoel E. Denny 
4503c5d267eSJoel E. Denny     // Print right-aligned line number.
4513c5d267eSJoel E. Denny     WithColor(OS, raw_ostream::BLACK, true)
4523c5d267eSJoel E. Denny         << format_decimal(Line, LabelWidth) << ": ";
4533c5d267eSJoel E. Denny 
454e2afb614SJoel E. Denny     // For the case where -v and colors are enabled, find the annotations for
455e2afb614SJoel E. Denny     // good matches for expected patterns in order to highlight everything
456e2afb614SJoel E. Denny     // else in the line.  There are no such annotations if -v is disabled.
457e2afb614SJoel E. Denny     std::vector<InputAnnotation> FoundAndExpectedMatches;
4587df86967SJoel E. Denny     if (Req.Verbose && WithColor(OS).colorsEnabled()) {
4597df86967SJoel E. Denny       for (auto I = AnnotationItr; I != AnnotationEnd && I->InputLine == Line;
4607df86967SJoel E. Denny            ++I) {
461e2afb614SJoel E. Denny         if (I->FoundAndExpectedMatch)
462e2afb614SJoel E. Denny           FoundAndExpectedMatches.push_back(*I);
4637df86967SJoel E. Denny       }
4647df86967SJoel E. Denny     }
4657df86967SJoel E. Denny 
4667df86967SJoel E. Denny     // Print numbered line with highlighting where there are no matches for
4677df86967SJoel E. Denny     // expected patterns.
4683c5d267eSJoel E. Denny     bool Newline = false;
4697df86967SJoel E. Denny     {
4707df86967SJoel E. Denny       WithColor COS(OS);
4717df86967SJoel E. Denny       bool InMatch = false;
4727df86967SJoel E. Denny       if (Req.Verbose)
4737df86967SJoel E. Denny         COS.changeColor(raw_ostream::CYAN, true, true);
4747df86967SJoel E. Denny       for (unsigned Col = 1; InputFilePtr != InputFileEnd && !Newline; ++Col) {
4757df86967SJoel E. Denny         bool WasInMatch = InMatch;
4767df86967SJoel E. Denny         InMatch = false;
477e2afb614SJoel E. Denny         for (auto M : FoundAndExpectedMatches) {
4787df86967SJoel E. Denny           if (M.InputStartCol <= Col && Col < M.InputEndCol) {
4797df86967SJoel E. Denny             InMatch = true;
4807df86967SJoel E. Denny             break;
4817df86967SJoel E. Denny           }
4827df86967SJoel E. Denny         }
4837df86967SJoel E. Denny         if (!WasInMatch && InMatch)
4847df86967SJoel E. Denny           COS.resetColor();
4857df86967SJoel E. Denny         else if (WasInMatch && !InMatch)
4867df86967SJoel E. Denny           COS.changeColor(raw_ostream::CYAN, true, true);
4873c5d267eSJoel E. Denny         if (*InputFilePtr == '\n')
4883c5d267eSJoel E. Denny           Newline = true;
4893c5d267eSJoel E. Denny         else
4907df86967SJoel E. Denny           COS << *InputFilePtr;
4913c5d267eSJoel E. Denny         ++InputFilePtr;
4923c5d267eSJoel E. Denny       }
4937df86967SJoel E. Denny     }
4943c5d267eSJoel E. Denny     OS << '\n';
4953c5d267eSJoel E. Denny     unsigned InputLineWidth = InputFilePtr - InputFileLine - Newline;
4963c5d267eSJoel E. Denny 
4973c5d267eSJoel E. Denny     // Print any annotations.
4983c5d267eSJoel E. Denny     while (AnnotationItr != AnnotationEnd &&
4993c5d267eSJoel E. Denny            AnnotationItr->InputLine == Line) {
5003c5d267eSJoel E. Denny       WithColor COS(OS, AnnotationItr->Marker.Color, true);
5013c5d267eSJoel E. Denny       // The two spaces below are where the ": " appears on input lines.
5023c5d267eSJoel E. Denny       COS << left_justify(AnnotationItr->Label, LabelWidth) << "  ";
5033c5d267eSJoel E. Denny       unsigned Col;
5043c5d267eSJoel E. Denny       for (Col = 1; Col < AnnotationItr->InputStartCol; ++Col)
5053c5d267eSJoel E. Denny         COS << ' ';
5063c5d267eSJoel E. Denny       COS << AnnotationItr->Marker.Lead;
5073c5d267eSJoel E. Denny       // If InputEndCol=UINT_MAX, stop at InputLineWidth.
5083c5d267eSJoel E. Denny       for (++Col; Col < AnnotationItr->InputEndCol && Col <= InputLineWidth;
5093c5d267eSJoel E. Denny            ++Col)
5103c5d267eSJoel E. Denny         COS << '~';
5113c5d267eSJoel E. Denny       const std::string &Note = AnnotationItr->Marker.Note;
5123c5d267eSJoel E. Denny       if (!Note.empty()) {
5133c5d267eSJoel E. Denny         // Put the note at the end of the input line.  If we were to instead
5143c5d267eSJoel E. Denny         // put the note right after the marker, subsequent annotations for the
5153c5d267eSJoel E. Denny         // same input line might appear to mark this note instead of the input
5163c5d267eSJoel E. Denny         // line.
5173c5d267eSJoel E. Denny         for (; Col <= InputLineWidth; ++Col)
5183c5d267eSJoel E. Denny           COS << ' ';
5193c5d267eSJoel E. Denny         COS << ' ' << Note;
5203c5d267eSJoel E. Denny       }
5213c5d267eSJoel E. Denny       COS << '\n';
5223c5d267eSJoel E. Denny       ++AnnotationItr;
5233c5d267eSJoel E. Denny     }
5243c5d267eSJoel E. Denny   }
5253c5d267eSJoel E. Denny 
5263c5d267eSJoel E. Denny   OS << ">>>>>>\n";
5273c5d267eSJoel E. Denny }
5283c5d267eSJoel E. Denny 
529ee3c74fbSChris Lattner int main(int argc, char **argv) {
5303e66509fSJoel E. Denny   // Enable use of ANSI color codes because FileCheck is using them to
5313e66509fSJoel E. Denny   // highlight text.
5323e66509fSJoel E. Denny   llvm::sys::Process::UseANSIEscapeCodes(true);
5333e66509fSJoel E. Denny 
534197194b6SRui Ueyama   InitLLVM X(argc, argv);
53524994d77SJoel E. Denny   cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr,
53624994d77SJoel E. Denny                               "FILECHECK_OPTS");
537fdde18a7SJoel E. Denny   DumpInputValue DumpInput =
538fdde18a7SJoel E. Denny       DumpInputs.empty()
539fdde18a7SJoel E. Denny           ? DumpInputDefault
540fdde18a7SJoel E. Denny           : *std::max_element(DumpInputs.begin(), DumpInputs.end());
5413c5d267eSJoel E. Denny   if (DumpInput == DumpInputHelp) {
5423c5d267eSJoel E. Denny     DumpInputAnnotationHelp(outs());
5433c5d267eSJoel E. Denny     return 0;
5443c5d267eSJoel E. Denny   }
5453c5d267eSJoel E. Denny   if (CheckFilename.empty()) {
5463c5d267eSJoel E. Denny     errs() << "<check-file> not specified\n";
5473c5d267eSJoel E. Denny     return 2;
5483c5d267eSJoel E. Denny   }
549ee3c74fbSChris Lattner 
550ffa9d2e4SAditya Nandakumar   FileCheckRequest Req;
551ffa9d2e4SAditya Nandakumar   for (auto Prefix : CheckPrefixes)
552ffa9d2e4SAditya Nandakumar     Req.CheckPrefixes.push_back(Prefix);
553ffa9d2e4SAditya Nandakumar 
554ffa9d2e4SAditya Nandakumar   for (auto CheckNot : ImplicitCheckNot)
555ffa9d2e4SAditya Nandakumar     Req.ImplicitCheckNot.push_back(CheckNot);
556ffa9d2e4SAditya Nandakumar 
557a5e233bfSThomas Preud'homme   bool GlobalDefineError = false;
558a5e233bfSThomas Preud'homme   for (auto G : GlobalDefines) {
559a5e233bfSThomas Preud'homme     size_t EqIdx = G.find('=');
560a5e233bfSThomas Preud'homme     if (EqIdx == std::string::npos) {
561a5e233bfSThomas Preud'homme       errs() << "Missing equal sign in command-line definition '-D" << G
562a5e233bfSThomas Preud'homme              << "'\n";
563a5e233bfSThomas Preud'homme       GlobalDefineError = true;
564a5e233bfSThomas Preud'homme       continue;
565a5e233bfSThomas Preud'homme     }
566a5e233bfSThomas Preud'homme     if (EqIdx == 0) {
5671a944d27SThomas Preud'homme       errs() << "Missing variable name in command-line definition '-D" << G
5681a944d27SThomas Preud'homme              << "'\n";
569a5e233bfSThomas Preud'homme       GlobalDefineError = true;
570a5e233bfSThomas Preud'homme       continue;
571a5e233bfSThomas Preud'homme     }
572ffa9d2e4SAditya Nandakumar     Req.GlobalDefines.push_back(G);
573a5e233bfSThomas Preud'homme   }
574a5e233bfSThomas Preud'homme   if (GlobalDefineError)
575a5e233bfSThomas Preud'homme     return 2;
576ffa9d2e4SAditya Nandakumar 
577ffa9d2e4SAditya Nandakumar   Req.AllowEmptyInput = AllowEmptyInput;
578ffa9d2e4SAditya Nandakumar   Req.EnableVarScope = EnableVarScope;
579ffa9d2e4SAditya Nandakumar   Req.AllowDeprecatedDagOverlap = AllowDeprecatedDagOverlap;
580ffa9d2e4SAditya Nandakumar   Req.Verbose = Verbose;
581ffa9d2e4SAditya Nandakumar   Req.VerboseVerbose = VerboseVerbose;
582ffa9d2e4SAditya Nandakumar   Req.NoCanonicalizeWhiteSpace = NoCanonicalizeWhiteSpace;
583ffa9d2e4SAditya Nandakumar   Req.MatchFullLines = MatchFullLines;
5845b5b2fd2SKai Nacke   Req.IgnoreCase = IgnoreCase;
585ffa9d2e4SAditya Nandakumar 
586ffa9d2e4SAditya Nandakumar   if (VerboseVerbose)
587ffa9d2e4SAditya Nandakumar     Req.Verbose = true;
588ffa9d2e4SAditya Nandakumar 
589ffa9d2e4SAditya Nandakumar   FileCheck FC(Req);
590ffa9d2e4SAditya Nandakumar   if (!FC.ValidateCheckPrefixes()) {
59113df4626SMatt Arsenault     errs() << "Supplied check-prefix is invalid! Prefixes must be unique and "
59213df4626SMatt Arsenault               "start with a letter and contain only alphanumeric characters, "
59313df4626SMatt Arsenault               "hyphens and underscores\n";
594c2735158SRui Ueyama     return 2;
595c2735158SRui Ueyama   }
596c2735158SRui Ueyama 
597ffa9d2e4SAditya Nandakumar   Regex PrefixRE = FC.buildCheckPrefixRegex();
598726774cbSChandler Carruth   std::string REError;
599726774cbSChandler Carruth   if (!PrefixRE.isValid(REError)) {
600726774cbSChandler Carruth     errs() << "Unable to combine check-prefix strings into a prefix regular "
601726774cbSChandler Carruth               "expression! This is likely a bug in FileCheck's verification of "
602726774cbSChandler Carruth               "the check-prefix strings. Regular expression parsing failed "
603726774cbSChandler Carruth               "with the following error: "
604726774cbSChandler Carruth            << REError << "\n";
605726774cbSChandler Carruth     return 2;
606726774cbSChandler Carruth   }
60713df4626SMatt Arsenault 
608ee3c74fbSChris Lattner   SourceMgr SM;
609ee3c74fbSChris Lattner 
610ee3c74fbSChris Lattner   // Read the expected strings from the check file.
61120247900SChandler Carruth   ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr =
61220247900SChandler Carruth       MemoryBuffer::getFileOrSTDIN(CheckFilename);
61320247900SChandler Carruth   if (std::error_code EC = CheckFileOrErr.getError()) {
61420247900SChandler Carruth     errs() << "Could not open check file '" << CheckFilename
61520247900SChandler Carruth            << "': " << EC.message() << '\n';
61620247900SChandler Carruth     return 2;
61720247900SChandler Carruth   }
61820247900SChandler Carruth   MemoryBuffer &CheckFile = *CheckFileOrErr.get();
61920247900SChandler Carruth 
62020247900SChandler Carruth   SmallString<4096> CheckFileBuffer;
621ffa9d2e4SAditya Nandakumar   StringRef CheckFileText = FC.CanonicalizeFile(CheckFile, CheckFileBuffer);
62220247900SChandler Carruth 
623*b5a24610SJoel E. Denny   unsigned CheckFileBufferID =
62420247900SChandler Carruth       SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
62520247900SChandler Carruth                                 CheckFileText, CheckFile.getBufferIdentifier()),
62620247900SChandler Carruth                             SMLoc());
62720247900SChandler Carruth 
628*b5a24610SJoel E. Denny   std::pair<unsigned, unsigned> ImpPatBufferIDRange;
629*b5a24610SJoel E. Denny   if (FC.readCheckFile(SM, CheckFileText, PrefixRE, &ImpPatBufferIDRange))
630ee3c74fbSChris Lattner     return 2;
631ee3c74fbSChris Lattner 
632ee3c74fbSChris Lattner   // Open the file to check and add it to SourceMgr.
63320247900SChandler Carruth   ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr =
634adf21f2aSRafael Espindola       MemoryBuffer::getFileOrSTDIN(InputFilename);
6356e01cd67SDavid Bozier   if (InputFilename == "-")
6366e01cd67SDavid Bozier     InputFilename = "<stdin>"; // Overwrite for improved diagnostic messages
63720247900SChandler Carruth   if (std::error_code EC = InputFileOrErr.getError()) {
638adf21f2aSRafael Espindola     errs() << "Could not open input file '" << InputFilename
639adf21f2aSRafael Espindola            << "': " << EC.message() << '\n';
6408e1c6477SEli Bendersky     return 2;
641ee3c74fbSChris Lattner   }
64220247900SChandler Carruth   MemoryBuffer &InputFile = *InputFileOrErr.get();
6432c3e5cdfSChris Lattner 
64420247900SChandler Carruth   if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) {
645b692bed7SChris Lattner     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
6462bd4f8b6SXinliang David Li     DumpCommandLine(argc, argv);
6478e1c6477SEli Bendersky     return 2;
648b692bed7SChris Lattner   }
649b692bed7SChris Lattner 
65020247900SChandler Carruth   SmallString<4096> InputFileBuffer;
651ffa9d2e4SAditya Nandakumar   StringRef InputFileText = FC.CanonicalizeFile(InputFile, InputFileBuffer);
6522c3e5cdfSChris Lattner 
653e8f2fb20SChandler Carruth   SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
654e8f2fb20SChandler Carruth                             InputFileText, InputFile.getBufferIdentifier()),
655e8f2fb20SChandler Carruth                         SMLoc());
656ee3c74fbSChris Lattner 
6573c5d267eSJoel E. Denny   if (DumpInput == DumpInputDefault)
6583c5d267eSJoel E. Denny     DumpInput = DumpInputOnFailure ? DumpInputFail : DumpInputNever;
6593c5d267eSJoel E. Denny 
6603c5d267eSJoel E. Denny   std::vector<FileCheckDiag> Diags;
66102ada9bdSThomas Preud'homme   int ExitCode = FC.checkInput(SM, InputFileText,
6623c5d267eSJoel E. Denny                                DumpInput == DumpInputNever ? nullptr : &Diags)
6633c5d267eSJoel E. Denny                      ? EXIT_SUCCESS
6643c5d267eSJoel E. Denny                      : 1;
6653c5d267eSJoel E. Denny   if (DumpInput == DumpInputAlways ||
6663c5d267eSJoel E. Denny       (ExitCode == 1 && DumpInput == DumpInputFail)) {
6673c5d267eSJoel E. Denny     errs() << "\n"
6683c5d267eSJoel E. Denny            << "Input file: "
6696e01cd67SDavid Bozier            << InputFilename
6703c5d267eSJoel E. Denny            << "\n"
6713c5d267eSJoel E. Denny            << "Check file: " << CheckFilename << "\n"
6723c5d267eSJoel E. Denny            << "\n"
6733c5d267eSJoel E. Denny            << "-dump-input=help describes the format of the following dump.\n"
6743c5d267eSJoel E. Denny            << "\n";
6753c5d267eSJoel E. Denny     std::vector<InputAnnotation> Annotations;
6763c5d267eSJoel E. Denny     unsigned LabelWidth;
677*b5a24610SJoel E. Denny     BuildInputAnnotations(SM, CheckFileBufferID, ImpPatBufferIDRange, Diags,
678*b5a24610SJoel E. Denny                           Annotations, LabelWidth);
6797df86967SJoel E. Denny     DumpAnnotatedInput(errs(), Req, InputFileText, Annotations, LabelWidth);
6803c5d267eSJoel E. Denny   }
681346dfbe2SGeorge Karpenkov 
682346dfbe2SGeorge Karpenkov   return ExitCode;
683ee3c74fbSChris Lattner }
684