xref: /llvm-project/llvm/utils/FileCheck/FileCheck.cpp (revision dbb757f462054ff9e06a46ce72135843e42f960b)
1 //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // FileCheck does a line-by line check of a file that validates whether it
10 // contains the expected content.  This is useful for regression tests etc.
11 //
12 // This program exits with an exit status of 2 on error, exit status of 0 if
13 // the file matched the expected contents, and exit status of 1 if it did not
14 // contain the expected contents.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/InitLLVM.h"
20 #include "llvm/Support/Process.h"
21 #include "llvm/Support/WithColor.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/FileCheck.h"
24 #include <cmath>
25 using namespace llvm;
26 
27 static cl::extrahelp FileCheckOptsEnv(
28     "\nOptions are parsed from the environment variable FILECHECK_OPTS and\n"
29     "from the command line.\n");
30 
31 static cl::opt<std::string>
32     CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Optional);
33 
34 static cl::opt<std::string>
35     InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
36                   cl::init("-"), cl::value_desc("filename"));
37 
38 static cl::list<std::string> CheckPrefixes(
39     "check-prefix",
40     cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
41 static cl::alias CheckPrefixesAlias(
42     "check-prefixes", cl::aliasopt(CheckPrefixes), cl::CommaSeparated,
43     cl::NotHidden,
44     cl::desc(
45         "Alias for -check-prefix permitting multiple comma separated values"));
46 
47 static cl::opt<bool> NoCanonicalizeWhiteSpace(
48     "strict-whitespace",
49     cl::desc("Do not treat all horizontal whitespace as equivalent"));
50 
51 static cl::list<std::string> ImplicitCheckNot(
52     "implicit-check-not",
53     cl::desc("Add an implicit negative check with this pattern to every\n"
54              "positive check. This can be used to ensure that no instances of\n"
55              "this pattern occur which are not matched by a positive pattern"),
56     cl::value_desc("pattern"));
57 
58 static cl::list<std::string>
59     GlobalDefines("D", cl::AlwaysPrefix,
60                   cl::desc("Define a variable to be used in capture patterns."),
61                   cl::value_desc("VAR=VALUE"));
62 
63 static cl::opt<bool> AllowEmptyInput(
64     "allow-empty", cl::init(false),
65     cl::desc("Allow the input file to be empty. This is useful when making\n"
66              "checks that some error message does not occur, for example."));
67 
68 static cl::opt<bool> MatchFullLines(
69     "match-full-lines", cl::init(false),
70     cl::desc("Require all positive matches to cover an entire input line.\n"
71              "Allows leading and trailing whitespace if --strict-whitespace\n"
72              "is not also passed."));
73 
74 static cl::opt<bool> EnableVarScope(
75     "enable-var-scope", cl::init(false),
76     cl::desc("Enables scope for regex variables. Variables with names that\n"
77              "do not start with '$' will be reset at the beginning of\n"
78              "each CHECK-LABEL block."));
79 
80 static cl::opt<bool> AllowDeprecatedDagOverlap(
81     "allow-deprecated-dag-overlap", cl::init(false),
82     cl::desc("Enable overlapping among matches in a group of consecutive\n"
83              "CHECK-DAG directives.  This option is deprecated and is only\n"
84              "provided for convenience as old tests are migrated to the new\n"
85              "non-overlapping CHECK-DAG implementation.\n"));
86 
87 static cl::opt<bool> Verbose(
88     "v", cl::init(false),
89     cl::desc("Print directive pattern matches, or add them to the input dump\n"
90              "if enabled.\n"));
91 
92 static cl::opt<bool> VerboseVerbose(
93     "vv", cl::init(false),
94     cl::desc("Print information helpful in diagnosing internal FileCheck\n"
95              "issues, or add it to the input dump if enabled.  Implies\n"
96              "-v.\n"));
97 static const char * DumpInputEnv = "FILECHECK_DUMP_INPUT_ON_FAILURE";
98 
99 static cl::opt<bool> DumpInputOnFailure(
100     "dump-input-on-failure",
101     cl::init(std::getenv(DumpInputEnv) && *std::getenv(DumpInputEnv)),
102     cl::desc("Dump original input to stderr before failing.\n"
103              "The value can be also controlled using\n"
104              "FILECHECK_DUMP_INPUT_ON_FAILURE environment variable.\n"
105              "This option is deprecated in favor of -dump-input=fail.\n"));
106 
107 enum DumpInputValue {
108   DumpInputDefault,
109   DumpInputHelp,
110   DumpInputNever,
111   DumpInputFail,
112   DumpInputAlways
113 };
114 
115 static cl::opt<DumpInputValue> DumpInput(
116     "dump-input", cl::init(DumpInputDefault),
117     cl::desc("Dump input to stderr, adding annotations representing\n"
118              " currently enabled diagnostics\n"),
119     cl::value_desc("mode"),
120     cl::values(clEnumValN(DumpInputHelp, "help",
121                           "Explain dump format and quit"),
122                clEnumValN(DumpInputNever, "never", "Never dump input"),
123                clEnumValN(DumpInputFail, "fail", "Dump input on failure"),
124                clEnumValN(DumpInputAlways, "always", "Always dump input")));
125 
126 typedef cl::list<std::string>::const_iterator prefix_iterator;
127 
128 
129 
130 
131 
132 
133 
134 static void DumpCommandLine(int argc, char **argv) {
135   errs() << "FileCheck command line: ";
136   for (int I = 0; I < argc; I++)
137     errs() << " " << argv[I];
138   errs() << "\n";
139 }
140 
141 struct MarkerStyle {
142   /// The starting char (before tildes) for marking the line.
143   char Lead;
144   /// What color to use for this annotation.
145   raw_ostream::Colors Color;
146   /// A note to follow the marker, or empty string if none.
147   std::string Note;
148   MarkerStyle() {}
149   MarkerStyle(char Lead, raw_ostream::Colors Color,
150               const std::string &Note = "")
151       : Lead(Lead), Color(Color), Note(Note) {}
152 };
153 
154 static MarkerStyle GetMarker(FileCheckDiag::MatchType MatchTy) {
155   switch (MatchTy) {
156   case FileCheckDiag::MatchFoundAndExpected:
157     return MarkerStyle('^', raw_ostream::GREEN);
158   case FileCheckDiag::MatchFoundButExcluded:
159     return MarkerStyle('!', raw_ostream::RED, "error: no match expected");
160   case FileCheckDiag::MatchFoundButWrongLine:
161     return MarkerStyle('!', raw_ostream::RED, "error: match on wrong line");
162   case FileCheckDiag::MatchFoundButDiscarded:
163     return MarkerStyle('!', raw_ostream::CYAN,
164                        "discard: overlaps earlier match");
165   case FileCheckDiag::MatchNoneAndExcluded:
166     return MarkerStyle('X', raw_ostream::GREEN);
167   case FileCheckDiag::MatchNoneButExpected:
168     return MarkerStyle('X', raw_ostream::RED, "error: no match found");
169   case FileCheckDiag::MatchFuzzy:
170     return MarkerStyle('?', raw_ostream::MAGENTA, "possible intended match");
171   }
172   llvm_unreachable_internal("unexpected match type");
173 }
174 
175 static void DumpInputAnnotationHelp(raw_ostream &OS) {
176   OS << "The following description was requested by -dump-input=help to\n"
177      << "explain the input annotations printed by -dump-input=always and\n"
178      << "-dump-input=fail:\n\n";
179 
180   // Labels for input lines.
181   OS << "  - ";
182   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "L:";
183   OS << "     labels line number L of the input file\n";
184 
185   // Labels for annotation lines.
186   OS << "  - ";
187   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L";
188   OS << "    labels the only match result for a pattern of type T from "
189      << "line L of\n"
190      << "           the check file\n";
191   OS << "  - ";
192   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L'N";
193   OS << "  labels the Nth match result for a pattern of type T from line "
194      << "L of\n"
195      << "           the check file\n";
196 
197   // Markers on annotation lines.
198   OS << "  - ";
199   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "^~~";
200   OS << "    marks good match (reported if -v)\n"
201      << "  - ";
202   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "!~~";
203   OS << "    marks bad match, such as:\n"
204      << "           - CHECK-NEXT on same line as previous match (error)\n"
205      << "           - CHECK-NOT found (error)\n"
206      << "           - CHECK-DAG overlapping match (discarded, reported if "
207      << "-vv)\n"
208      << "  - ";
209   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "X~~";
210   OS << "    marks search range when no match is found, such as:\n"
211      << "           - CHECK-NEXT not found (error)\n"
212      << "           - CHECK-NOT not found (success, reported if -vv)\n"
213      << "           - CHECK-DAG not found after discarded matches (error)\n"
214      << "  - ";
215   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "?";
216   OS << "      marks fuzzy match when no match is found\n";
217 
218   // Colors.
219   OS << "  - colors ";
220   WithColor(OS, raw_ostream::GREEN, true) << "success";
221   OS << ", ";
222   WithColor(OS, raw_ostream::RED, true) << "error";
223   OS << ", ";
224   WithColor(OS, raw_ostream::MAGENTA, true) << "fuzzy match";
225   OS << ", ";
226   WithColor(OS, raw_ostream::CYAN, true, false) << "discarded match";
227   OS << ", ";
228   WithColor(OS, raw_ostream::CYAN, true, true) << "unmatched input";
229   OS << "\n\n"
230      << "If you are not seeing color above or in input dumps, try: -color\n";
231 }
232 
233 /// An annotation for a single input line.
234 struct InputAnnotation {
235   /// The check file line (one-origin indexing) where the directive that
236   /// produced this annotation is located.
237   unsigned CheckLine;
238   /// The index of the match result for this check.
239   unsigned CheckDiagIndex;
240   /// The label for this annotation.
241   std::string Label;
242   /// What input line (one-origin indexing) this annotation marks.  This might
243   /// be different from the starting line of the original diagnostic if this is
244   /// a non-initial fragment of a diagnostic that has been broken across
245   /// multiple lines.
246   unsigned InputLine;
247   /// The column range (one-origin indexing, open end) in which to to mark the
248   /// input line.  If InputEndCol is UINT_MAX, treat it as the last column
249   /// before the newline.
250   unsigned InputStartCol, InputEndCol;
251   /// The marker to use.
252   MarkerStyle Marker;
253   /// Whether this annotation represents a good match for an expected pattern.
254   bool FoundAndExpectedMatch;
255 };
256 
257 /// Get an abbreviation for the check type.
258 std::string GetCheckTypeAbbreviation(Check::FileCheckType Ty) {
259   switch (Ty) {
260   case Check::CheckPlain:
261     if (Ty.getCount() > 1)
262       return "count";
263     return "check";
264   case Check::CheckNext:
265     return "next";
266   case Check::CheckSame:
267     return "same";
268   case Check::CheckNot:
269     return "not";
270   case Check::CheckDAG:
271     return "dag";
272   case Check::CheckLabel:
273     return "label";
274   case Check::CheckEmpty:
275     return "empty";
276   case Check::CheckEOF:
277     return "eof";
278   case Check::CheckBadNot:
279     return "bad-not";
280   case Check::CheckBadCount:
281     return "bad-count";
282   case Check::CheckNone:
283     llvm_unreachable("invalid FileCheckType");
284   }
285   llvm_unreachable("unknown FileCheckType");
286 }
287 
288 static void BuildInputAnnotations(const std::vector<FileCheckDiag> &Diags,
289                                   std::vector<InputAnnotation> &Annotations,
290                                   unsigned &LabelWidth) {
291   // How many diagnostics has the current check seen so far?
292   unsigned CheckDiagCount = 0;
293   // What's the widest label?
294   LabelWidth = 0;
295   for (auto DiagItr = Diags.begin(), DiagEnd = Diags.end(); DiagItr != DiagEnd;
296        ++DiagItr) {
297     InputAnnotation A;
298 
299     // Build label, which uniquely identifies this check result.
300     A.CheckLine = DiagItr->CheckLine;
301     llvm::raw_string_ostream Label(A.Label);
302     Label << GetCheckTypeAbbreviation(DiagItr->CheckTy) << ":"
303           << DiagItr->CheckLine;
304     A.CheckDiagIndex = UINT_MAX;
305     auto DiagNext = std::next(DiagItr);
306     if (DiagNext != DiagEnd && DiagItr->CheckTy == DiagNext->CheckTy &&
307         DiagItr->CheckLine == DiagNext->CheckLine)
308       A.CheckDiagIndex = CheckDiagCount++;
309     else if (CheckDiagCount) {
310       A.CheckDiagIndex = CheckDiagCount;
311       CheckDiagCount = 0;
312     }
313     if (A.CheckDiagIndex != UINT_MAX)
314       Label << "'" << A.CheckDiagIndex;
315     else
316       A.CheckDiagIndex = 0;
317     Label.flush();
318     LabelWidth = std::max((std::string::size_type)LabelWidth, A.Label.size());
319 
320     A.Marker = GetMarker(DiagItr->MatchTy);
321     A.FoundAndExpectedMatch =
322         DiagItr->MatchTy == FileCheckDiag::MatchFoundAndExpected;
323 
324     // Compute the mark location, and break annotation into multiple
325     // annotations if it spans multiple lines.
326     A.InputLine = DiagItr->InputStartLine;
327     A.InputStartCol = DiagItr->InputStartCol;
328     if (DiagItr->InputStartLine == DiagItr->InputEndLine) {
329       // Sometimes ranges are empty in order to indicate a specific point, but
330       // that would mean nothing would be marked, so adjust the range to
331       // include the following character.
332       A.InputEndCol =
333           std::max(DiagItr->InputStartCol + 1, DiagItr->InputEndCol);
334       Annotations.push_back(A);
335     } else {
336       assert(DiagItr->InputStartLine < DiagItr->InputEndLine &&
337              "expected input range not to be inverted");
338       A.InputEndCol = UINT_MAX;
339       Annotations.push_back(A);
340       for (unsigned L = DiagItr->InputStartLine + 1, E = DiagItr->InputEndLine;
341            L <= E; ++L) {
342         // If a range ends before the first column on a line, then it has no
343         // characters on that line, so there's nothing to render.
344         if (DiagItr->InputEndCol == 1 && L == E)
345           break;
346         InputAnnotation B;
347         B.CheckLine = A.CheckLine;
348         B.CheckDiagIndex = A.CheckDiagIndex;
349         B.Label = A.Label;
350         B.InputLine = L;
351         B.Marker = A.Marker;
352         B.Marker.Lead = '~';
353         B.Marker.Note = "";
354         B.InputStartCol = 1;
355         if (L != E)
356           B.InputEndCol = UINT_MAX;
357         else
358           B.InputEndCol = DiagItr->InputEndCol;
359         B.FoundAndExpectedMatch = A.FoundAndExpectedMatch;
360         Annotations.push_back(B);
361       }
362     }
363   }
364 }
365 
366 static void DumpAnnotatedInput(raw_ostream &OS, const FileCheckRequest &Req,
367                                StringRef InputFileText,
368                                std::vector<InputAnnotation> &Annotations,
369                                unsigned LabelWidth) {
370   OS << "Full input was:\n<<<<<<\n";
371 
372   // Sort annotations.
373   //
374   // First, sort in the order of input lines to make it easier to find relevant
375   // annotations while iterating input lines in the implementation below.
376   // FileCheck diagnostics are not always reported and recorded in the order of
377   // input lines due to, for example, CHECK-DAG and CHECK-NOT.
378   //
379   // Second, for annotations for the same input line, sort in the order of the
380   // FileCheck directive's line in the check file (where there's at most one
381   // directive per line) and then by the index of the match result for that
382   // directive.  The rationale of this choice is that, for any input line, this
383   // sort establishes a total order of annotations that, with respect to match
384   // results, is consistent across multiple lines, thus making match results
385   // easier to track from one line to the next when they span multiple lines.
386   std::sort(Annotations.begin(), Annotations.end(),
387             [](const InputAnnotation &A, const InputAnnotation &B) {
388               if (A.InputLine != B.InputLine)
389                 return A.InputLine < B.InputLine;
390               if (A.CheckLine != B.CheckLine)
391                 return A.CheckLine < B.CheckLine;
392               // FIXME: Sometimes CHECK-LABEL reports its match twice with
393               // other diagnostics in between, and then diag index incrementing
394               // fails to work properly, and then this assert fails.  We should
395               // suppress one of those diagnostics or do a better job of
396               // computing this index.  For now, we just produce a redundant
397               // CHECK-LABEL annotation.
398               // assert(A.CheckDiagIndex != B.CheckDiagIndex &&
399               //        "expected diagnostic indices to be unique within a "
400               //        " check line");
401               return A.CheckDiagIndex < B.CheckDiagIndex;
402             });
403 
404   // Compute the width of the label column.
405   const unsigned char *InputFilePtr = InputFileText.bytes_begin(),
406                       *InputFileEnd = InputFileText.bytes_end();
407   unsigned LineCount = InputFileText.count('\n');
408   if (InputFileEnd[-1] != '\n')
409     ++LineCount;
410   unsigned LineNoWidth = std::log10(LineCount) + 1;
411   // +3 below adds spaces (1) to the left of the (right-aligned) line numbers
412   // on input lines and (2) to the right of the (left-aligned) labels on
413   // annotation lines so that input lines and annotation lines are more
414   // visually distinct.  For example, the spaces on the annotation lines ensure
415   // that input line numbers and check directive line numbers never align
416   // horizontally.  Those line numbers might not even be for the same file.
417   // One space would be enough to achieve that, but more makes it even easier
418   // to see.
419   LabelWidth = std::max(LabelWidth, LineNoWidth) + 3;
420 
421   // Print annotated input lines.
422   auto AnnotationItr = Annotations.begin(), AnnotationEnd = Annotations.end();
423   for (unsigned Line = 1;
424        InputFilePtr != InputFileEnd || AnnotationItr != AnnotationEnd;
425        ++Line) {
426     const unsigned char *InputFileLine = InputFilePtr;
427 
428     // Print right-aligned line number.
429     WithColor(OS, raw_ostream::BLACK, true)
430         << format_decimal(Line, LabelWidth) << ": ";
431 
432     // For the case where -v and colors are enabled, find the annotations for
433     // good matches for expected patterns in order to highlight everything
434     // else in the line.  There are no such annotations if -v is disabled.
435     std::vector<InputAnnotation> FoundAndExpectedMatches;
436     if (Req.Verbose && WithColor(OS).colorsEnabled()) {
437       for (auto I = AnnotationItr; I != AnnotationEnd && I->InputLine == Line;
438            ++I) {
439         if (I->FoundAndExpectedMatch)
440           FoundAndExpectedMatches.push_back(*I);
441       }
442     }
443 
444     // Print numbered line with highlighting where there are no matches for
445     // expected patterns.
446     bool Newline = false;
447     {
448       WithColor COS(OS);
449       bool InMatch = false;
450       if (Req.Verbose)
451         COS.changeColor(raw_ostream::CYAN, true, true);
452       for (unsigned Col = 1; InputFilePtr != InputFileEnd && !Newline; ++Col) {
453         bool WasInMatch = InMatch;
454         InMatch = false;
455         for (auto M : FoundAndExpectedMatches) {
456           if (M.InputStartCol <= Col && Col < M.InputEndCol) {
457             InMatch = true;
458             break;
459           }
460         }
461         if (!WasInMatch && InMatch)
462           COS.resetColor();
463         else if (WasInMatch && !InMatch)
464           COS.changeColor(raw_ostream::CYAN, true, true);
465         if (*InputFilePtr == '\n')
466           Newline = true;
467         else
468           COS << *InputFilePtr;
469         ++InputFilePtr;
470       }
471     }
472     OS << '\n';
473     unsigned InputLineWidth = InputFilePtr - InputFileLine - Newline;
474 
475     // Print any annotations.
476     while (AnnotationItr != AnnotationEnd &&
477            AnnotationItr->InputLine == Line) {
478       WithColor COS(OS, AnnotationItr->Marker.Color, true);
479       // The two spaces below are where the ": " appears on input lines.
480       COS << left_justify(AnnotationItr->Label, LabelWidth) << "  ";
481       unsigned Col;
482       for (Col = 1; Col < AnnotationItr->InputStartCol; ++Col)
483         COS << ' ';
484       COS << AnnotationItr->Marker.Lead;
485       // If InputEndCol=UINT_MAX, stop at InputLineWidth.
486       for (++Col; Col < AnnotationItr->InputEndCol && Col <= InputLineWidth;
487            ++Col)
488         COS << '~';
489       const std::string &Note = AnnotationItr->Marker.Note;
490       if (!Note.empty()) {
491         // Put the note at the end of the input line.  If we were to instead
492         // put the note right after the marker, subsequent annotations for the
493         // same input line might appear to mark this note instead of the input
494         // line.
495         for (; Col <= InputLineWidth; ++Col)
496           COS << ' ';
497         COS << ' ' << Note;
498       }
499       COS << '\n';
500       ++AnnotationItr;
501     }
502   }
503 
504   OS << ">>>>>>\n";
505 }
506 
507 int main(int argc, char **argv) {
508   // Enable use of ANSI color codes because FileCheck is using them to
509   // highlight text.
510   llvm::sys::Process::UseANSIEscapeCodes(true);
511 
512   InitLLVM X(argc, argv);
513   cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr,
514                               "FILECHECK_OPTS");
515   if (DumpInput == DumpInputHelp) {
516     DumpInputAnnotationHelp(outs());
517     return 0;
518   }
519   if (CheckFilename.empty()) {
520     errs() << "<check-file> not specified\n";
521     return 2;
522   }
523 
524   FileCheckRequest Req;
525   for (auto Prefix : CheckPrefixes)
526     Req.CheckPrefixes.push_back(Prefix);
527 
528   for (auto CheckNot : ImplicitCheckNot)
529     Req.ImplicitCheckNot.push_back(CheckNot);
530 
531   bool GlobalDefineError = false;
532   for (auto G : GlobalDefines) {
533     size_t EqIdx = G.find('=');
534     if (EqIdx == std::string::npos) {
535       errs() << "Missing equal sign in command-line definition '-D" << G
536              << "'\n";
537       GlobalDefineError = true;
538       continue;
539     }
540     if (EqIdx == 0) {
541       errs() << "Missing variable name in command-line definition '-D" << G
542              << "'\n";
543       GlobalDefineError = true;
544       continue;
545     }
546     Req.GlobalDefines.push_back(G);
547   }
548   if (GlobalDefineError)
549     return 2;
550 
551   Req.AllowEmptyInput = AllowEmptyInput;
552   Req.EnableVarScope = EnableVarScope;
553   Req.AllowDeprecatedDagOverlap = AllowDeprecatedDagOverlap;
554   Req.Verbose = Verbose;
555   Req.VerboseVerbose = VerboseVerbose;
556   Req.NoCanonicalizeWhiteSpace = NoCanonicalizeWhiteSpace;
557   Req.MatchFullLines = MatchFullLines;
558 
559   if (VerboseVerbose)
560     Req.Verbose = true;
561 
562   FileCheck FC(Req);
563   if (!FC.ValidateCheckPrefixes()) {
564     errs() << "Supplied check-prefix is invalid! Prefixes must be unique and "
565               "start with a letter and contain only alphanumeric characters, "
566               "hyphens and underscores\n";
567     return 2;
568   }
569 
570   Regex PrefixRE = FC.buildCheckPrefixRegex();
571   std::string REError;
572   if (!PrefixRE.isValid(REError)) {
573     errs() << "Unable to combine check-prefix strings into a prefix regular "
574               "expression! This is likely a bug in FileCheck's verification of "
575               "the check-prefix strings. Regular expression parsing failed "
576               "with the following error: "
577            << REError << "\n";
578     return 2;
579   }
580 
581   SourceMgr SM;
582 
583   // Read the expected strings from the check file.
584   ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr =
585       MemoryBuffer::getFileOrSTDIN(CheckFilename);
586   if (std::error_code EC = CheckFileOrErr.getError()) {
587     errs() << "Could not open check file '" << CheckFilename
588            << "': " << EC.message() << '\n';
589     return 2;
590   }
591   MemoryBuffer &CheckFile = *CheckFileOrErr.get();
592 
593   SmallString<4096> CheckFileBuffer;
594   StringRef CheckFileText = FC.CanonicalizeFile(CheckFile, CheckFileBuffer);
595 
596   SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
597                             CheckFileText, CheckFile.getBufferIdentifier()),
598                         SMLoc());
599 
600   std::vector<FileCheckString> CheckStrings;
601   if (FC.ReadCheckFile(SM, CheckFileText, PrefixRE, CheckStrings))
602     return 2;
603 
604   // Open the file to check and add it to SourceMgr.
605   ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr =
606       MemoryBuffer::getFileOrSTDIN(InputFilename);
607   if (std::error_code EC = InputFileOrErr.getError()) {
608     errs() << "Could not open input file '" << InputFilename
609            << "': " << EC.message() << '\n';
610     return 2;
611   }
612   MemoryBuffer &InputFile = *InputFileOrErr.get();
613 
614   if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) {
615     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
616     DumpCommandLine(argc, argv);
617     return 2;
618   }
619 
620   SmallString<4096> InputFileBuffer;
621   StringRef InputFileText = FC.CanonicalizeFile(InputFile, InputFileBuffer);
622 
623   SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
624                             InputFileText, InputFile.getBufferIdentifier()),
625                         SMLoc());
626 
627   if (DumpInput == DumpInputDefault)
628     DumpInput = DumpInputOnFailure ? DumpInputFail : DumpInputNever;
629 
630   std::vector<FileCheckDiag> Diags;
631   int ExitCode = FC.CheckInput(SM, InputFileText, CheckStrings,
632                                DumpInput == DumpInputNever ? nullptr : &Diags)
633                      ? EXIT_SUCCESS
634                      : 1;
635   if (DumpInput == DumpInputAlways ||
636       (ExitCode == 1 && DumpInput == DumpInputFail)) {
637     errs() << "\n"
638            << "Input file: "
639            << (InputFilename == "-" ? "<stdin>" : InputFilename.getValue())
640            << "\n"
641            << "Check file: " << CheckFilename << "\n"
642            << "\n"
643            << "-dump-input=help describes the format of the following dump.\n"
644            << "\n";
645     std::vector<InputAnnotation> Annotations;
646     unsigned LabelWidth;
647     BuildInputAnnotations(Diags, Annotations, LabelWidth);
648     DumpAnnotatedInput(errs(), Req, InputFileText, Annotations, LabelWidth);
649   }
650 
651   return ExitCode;
652 }
653