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::opt<std::string>
28     CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Optional);
29 
30 static cl::opt<std::string>
31     InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
32                   cl::init("-"), cl::value_desc("filename"));
33 
34 static cl::list<std::string> CheckPrefixes(
35     "check-prefix",
36     cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
37 static cl::alias CheckPrefixesAlias(
38     "check-prefixes", cl::aliasopt(CheckPrefixes), cl::CommaSeparated,
39     cl::NotHidden,
40     cl::desc(
41         "Alias for -check-prefix permitting multiple comma separated values"));
42 
43 static cl::opt<bool> NoCanonicalizeWhiteSpace(
44     "strict-whitespace",
45     cl::desc("Do not treat all horizontal whitespace as equivalent"));
46 
47 static cl::list<std::string> ImplicitCheckNot(
48     "implicit-check-not",
49     cl::desc("Add an implicit negative check with this pattern to every\n"
50              "positive check. This can be used to ensure that no instances of\n"
51              "this pattern occur which are not matched by a positive pattern"),
52     cl::value_desc("pattern"));
53 
54 static cl::list<std::string>
55     GlobalDefines("D", cl::AlwaysPrefix,
56                   cl::desc("Define a variable to be used in capture patterns."),
57                   cl::value_desc("VAR=VALUE"));
58 
59 static cl::opt<bool> AllowEmptyInput(
60     "allow-empty", cl::init(false),
61     cl::desc("Allow the input file to be empty. This is useful when making\n"
62              "checks that some error message does not occur, for example."));
63 
64 static cl::opt<bool> MatchFullLines(
65     "match-full-lines", cl::init(false),
66     cl::desc("Require all positive matches to cover an entire input line.\n"
67              "Allows leading and trailing whitespace if --strict-whitespace\n"
68              "is not also passed."));
69 
70 static cl::opt<bool> EnableVarScope(
71     "enable-var-scope", cl::init(false),
72     cl::desc("Enables scope for regex variables. Variables with names that\n"
73              "do not start with '$' will be reset at the beginning of\n"
74              "each CHECK-LABEL block."));
75 
76 static cl::opt<bool> AllowDeprecatedDagOverlap(
77     "allow-deprecated-dag-overlap", cl::init(false),
78     cl::desc("Enable overlapping among matches in a group of consecutive\n"
79              "CHECK-DAG directives.  This option is deprecated and is only\n"
80              "provided for convenience as old tests are migrated to the new\n"
81              "non-overlapping CHECK-DAG implementation.\n"));
82 
83 static cl::opt<bool> Verbose(
84     "v", cl::init(false),
85     cl::desc("Print directive pattern matches, or add them to the input dump\n"
86              "if enabled.\n"));
87 
88 static cl::opt<bool> VerboseVerbose(
89     "vv", cl::init(false),
90     cl::desc("Print information helpful in diagnosing internal FileCheck\n"
91              "issues, or add it to the input dump if enabled.  Implies\n"
92              "-v.\n"));
93 static const char * DumpInputEnv = "FILECHECK_DUMP_INPUT_ON_FAILURE";
94 
95 static cl::opt<bool> DumpInputOnFailure(
96     "dump-input-on-failure",
97     cl::init(std::getenv(DumpInputEnv) && *std::getenv(DumpInputEnv)),
98     cl::desc("Dump original input to stderr before failing.\n"
99              "The value can be also controlled using\n"
100              "FILECHECK_DUMP_INPUT_ON_FAILURE environment variable.\n"
101              "This option is deprecated in favor of -dump-input=fail.\n"));
102 
103 enum DumpInputValue {
104   DumpInputDefault,
105   DumpInputHelp,
106   DumpInputNever,
107   DumpInputFail,
108   DumpInputAlways
109 };
110 
111 static cl::opt<DumpInputValue> DumpInput(
112     "dump-input", cl::init(DumpInputDefault),
113     cl::desc("Dump input to stderr, adding annotations representing\n"
114              " currently enabled diagnostics\n"),
115     cl::value_desc("mode"),
116     cl::values(clEnumValN(DumpInputHelp, "help",
117                           "Explain dump format and quit"),
118                clEnumValN(DumpInputNever, "never", "Never dump input"),
119                clEnumValN(DumpInputFail, "fail", "Dump input on failure"),
120                clEnumValN(DumpInputAlways, "always", "Always dump input")));
121 
122 typedef cl::list<std::string>::const_iterator prefix_iterator;
123 
124 
125 
126 
127 
128 
129 
130 static void DumpCommandLine(int argc, char **argv) {
131   errs() << "FileCheck command line: ";
132   for (int I = 0; I < argc; I++)
133     errs() << " " << argv[I];
134   errs() << "\n";
135 }
136 
137 struct MarkerStyle {
138   /// The starting char (before tildes) for marking the line.
139   char Lead;
140   /// What color to use for this annotation.
141   raw_ostream::Colors Color;
142   /// A note to follow the marker, or empty string if none.
143   std::string Note;
144   MarkerStyle() {}
145   MarkerStyle(char Lead, raw_ostream::Colors Color,
146               const std::string &Note = "")
147       : Lead(Lead), Color(Color), Note(Note) {}
148 };
149 
150 static MarkerStyle GetMarker(FileCheckDiag::MatchType MatchTy) {
151   switch (MatchTy) {
152   case FileCheckDiag::MatchFoundAndExpected:
153     return MarkerStyle('^', raw_ostream::GREEN);
154   case FileCheckDiag::MatchFoundButExcluded:
155     return MarkerStyle('!', raw_ostream::RED, "error: no match expected");
156   case FileCheckDiag::MatchFoundButWrongLine:
157     return MarkerStyle('!', raw_ostream::RED, "error: match on wrong line");
158   case FileCheckDiag::MatchFoundButDiscarded:
159     return MarkerStyle('!', raw_ostream::CYAN,
160                        "discard: overlaps earlier match");
161   case FileCheckDiag::MatchNoneAndExcluded:
162     return MarkerStyle('X', raw_ostream::GREEN);
163   case FileCheckDiag::MatchNoneButExpected:
164     return MarkerStyle('X', raw_ostream::RED, "error: no match found");
165   case FileCheckDiag::MatchFuzzy:
166     return MarkerStyle('?', raw_ostream::MAGENTA, "possible intended match");
167   }
168   llvm_unreachable_internal("unexpected match type");
169 }
170 
171 static void DumpInputAnnotationHelp(raw_ostream &OS) {
172   OS << "The following description was requested by -dump-input=help to\n"
173      << "explain the input annotations printed by -dump-input=always and\n"
174      << "-dump-input=fail:\n\n";
175 
176   // Labels for input lines.
177   OS << "  - ";
178   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "L:";
179   OS << "     labels line number L of the input file\n";
180 
181   // Labels for annotation lines.
182   OS << "  - ";
183   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L";
184   OS << "    labels the only match result for a pattern of type T from "
185      << "line L of\n"
186      << "           the check file\n";
187   OS << "  - ";
188   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L'N";
189   OS << "  labels the Nth match result for a pattern of type T from line "
190      << "L of\n"
191      << "           the check file\n";
192 
193   // Markers on annotation lines.
194   OS << "  - ";
195   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "^~~";
196   OS << "    marks good match (reported if -v)\n"
197      << "  - ";
198   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "!~~";
199   OS << "    marks bad match, such as:\n"
200      << "           - CHECK-NEXT on same line as previous match (error)\n"
201      << "           - CHECK-NOT found (error)\n"
202      << "           - CHECK-DAG overlapping match (discarded, reported if "
203      << "-vv)\n"
204      << "  - ";
205   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "X~~";
206   OS << "    marks search range when no match is found, such as:\n"
207      << "           - CHECK-NEXT not found (error)\n"
208      << "           - CHECK-NOT not found (success, reported if -vv)\n"
209      << "           - CHECK-DAG not found after discarded matches (error)\n"
210      << "  - ";
211   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "?";
212   OS << "      marks fuzzy match when no match is found\n";
213 
214   // Colors.
215   OS << "  - colors ";
216   WithColor(OS, raw_ostream::GREEN, true) << "success";
217   OS << ", ";
218   WithColor(OS, raw_ostream::RED, true) << "error";
219   OS << ", ";
220   WithColor(OS, raw_ostream::MAGENTA, true) << "fuzzy match";
221   OS << ", ";
222   WithColor(OS, raw_ostream::CYAN, true, false) << "discarded match";
223   OS << ", ";
224   WithColor(OS, raw_ostream::CYAN, true, true) << "unmatched input";
225   OS << "\n\n"
226      << "If you are not seeing color above or in input dumps, try: -color\n";
227 }
228 
229 /// An annotation for a single input line.
230 struct InputAnnotation {
231   /// The check file line (one-origin indexing) where the directive that
232   /// produced this annotation is located.
233   unsigned CheckLine;
234   /// The index of the match result for this check.
235   unsigned CheckDiagIndex;
236   /// The label for this annotation.
237   std::string Label;
238   /// What input line (one-origin indexing) this annotation marks.  This might
239   /// be different from the starting line of the original diagnostic if this is
240   /// a non-initial fragment of a diagnostic that has been broken across
241   /// multiple lines.
242   unsigned InputLine;
243   /// The column range (one-origin indexing, open end) in which to to mark the
244   /// input line.  If InputEndCol is UINT_MAX, treat it as the last column
245   /// before the newline.
246   unsigned InputStartCol, InputEndCol;
247   /// The marker to use.
248   MarkerStyle Marker;
249   /// Whether this annotation represents a good match for an expected pattern.
250   bool FoundAndExpectedMatch;
251 };
252 
253 /// Get an abbreviation for the check type.
254 std::string GetCheckTypeAbbreviation(Check::FileCheckType Ty) {
255   switch (Ty) {
256   case Check::CheckPlain:
257     if (Ty.getCount() > 1)
258       return "count";
259     return "check";
260   case Check::CheckNext:
261     return "next";
262   case Check::CheckSame:
263     return "same";
264   case Check::CheckNot:
265     return "not";
266   case Check::CheckDAG:
267     return "dag";
268   case Check::CheckLabel:
269     return "label";
270   case Check::CheckEmpty:
271     return "empty";
272   case Check::CheckEOF:
273     return "eof";
274   case Check::CheckBadNot:
275     return "bad-not";
276   case Check::CheckBadCount:
277     return "bad-count";
278   case Check::CheckNone:
279     llvm_unreachable("invalid FileCheckType");
280   }
281   llvm_unreachable("unknown FileCheckType");
282 }
283 
284 static void BuildInputAnnotations(const std::vector<FileCheckDiag> &Diags,
285                                   std::vector<InputAnnotation> &Annotations,
286                                   unsigned &LabelWidth) {
287   // How many diagnostics has the current check seen so far?
288   unsigned CheckDiagCount = 0;
289   // What's the widest label?
290   LabelWidth = 0;
291   for (auto DiagItr = Diags.begin(), DiagEnd = Diags.end(); DiagItr != DiagEnd;
292        ++DiagItr) {
293     InputAnnotation A;
294 
295     // Build label, which uniquely identifies this check result.
296     A.CheckLine = DiagItr->CheckLine;
297     llvm::raw_string_ostream Label(A.Label);
298     Label << GetCheckTypeAbbreviation(DiagItr->CheckTy) << ":"
299           << DiagItr->CheckLine;
300     A.CheckDiagIndex = UINT_MAX;
301     auto DiagNext = std::next(DiagItr);
302     if (DiagNext != DiagEnd && DiagItr->CheckTy == DiagNext->CheckTy &&
303         DiagItr->CheckLine == DiagNext->CheckLine)
304       A.CheckDiagIndex = CheckDiagCount++;
305     else if (CheckDiagCount) {
306       A.CheckDiagIndex = CheckDiagCount;
307       CheckDiagCount = 0;
308     }
309     if (A.CheckDiagIndex != UINT_MAX)
310       Label << "'" << A.CheckDiagIndex;
311     else
312       A.CheckDiagIndex = 0;
313     Label.flush();
314     LabelWidth = std::max((std::string::size_type)LabelWidth, A.Label.size());
315 
316     MarkerStyle Marker = GetMarker(DiagItr->MatchTy);
317     A.Marker = Marker;
318     A.FoundAndExpectedMatch =
319         DiagItr->MatchTy == FileCheckDiag::MatchFoundAndExpected;
320 
321     // Compute the mark location, and break annotation into multiple
322     // annotations if it spans multiple lines.
323     A.InputLine = DiagItr->InputStartLine;
324     A.InputStartCol = DiagItr->InputStartCol;
325     if (DiagItr->InputStartLine == DiagItr->InputEndLine) {
326       // Sometimes ranges are empty in order to indicate a specific point, but
327       // that would mean nothing would be marked, so adjust the range to
328       // include the following character.
329       A.InputEndCol =
330           std::max(DiagItr->InputStartCol + 1, DiagItr->InputEndCol);
331       Annotations.push_back(A);
332     } else {
333       assert(DiagItr->InputStartLine < DiagItr->InputEndLine &&
334              "expected input range not to be inverted");
335       A.InputEndCol = UINT_MAX;
336       A.Marker.Note = "";
337       Annotations.push_back(A);
338       for (unsigned L = DiagItr->InputStartLine + 1, E = DiagItr->InputEndLine;
339            L <= E; ++L) {
340         // If a range ends before the first column on a line, then it has no
341         // characters on that line, so there's nothing to render.
342         if (DiagItr->InputEndCol == 1 && L == E) {
343           Annotations.back().Marker.Note = Marker.Note;
344           break;
345         }
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 = Marker;
352         B.Marker.Lead = '~';
353         B.InputStartCol = 1;
354         if (L != E) {
355           B.InputEndCol = UINT_MAX;
356           B.Marker.Note = "";
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