LLVM  10.0.0svn
FileCheck.cpp
Go to the documentation of this file.
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 file implements most of the API that will be used by the FileCheck utility
13 // as well as various unittests.
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Support/FileCheck.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/ADT/Twine.h"
20 #include <cstdint>
21 #include <list>
22 #include <tuple>
23 #include <utility>
24 
25 using namespace llvm;
26 
28  if (Value)
29  return true;
30 
31  return ExpressionAST != nullptr;
32 }
33 
34 void FileCheckNumericVariable::setValue(uint64_t NewValue) {
35  if (ExpressionAST != nullptr) {
36  // Caller is expected to call setValue only if substitution was successful.
37  assert(NewValue == cantFail(ExpressionAST->eval(),
38  "Failed to evaluate associated expression when "
39  "sanity checking value") &&
40  "Value being set to different from variable evaluation");
41  }
42  Value = NewValue;
43  // Clear pointer to AST to ensure it is not used after the numeric
44  // substitution defining this variable is processed since it's the
45  // substitution that owns the pointer.
46  ExpressionAST = nullptr;
47 }
48 
50  Optional<uint64_t> Value = NumericVariable->getValue();
51  if (Value)
52  return *Value;
53 
54  FileCheckExpressionAST *ExpressionAST = NumericVariable->getExpressionAST();
55  if (!ExpressionAST)
56  return make_error<FileCheckUndefVarError>(Name);
57 
58  return ExpressionAST->eval();
59 }
60 
62  Expected<uint64_t> LeftOp = LeftOperand->eval();
63  Expected<uint64_t> RightOp = RightOperand->eval();
64 
65  // Bubble up any error (e.g. undefined variables) in the recursive
66  // evaluation.
67  if (!LeftOp || !RightOp) {
68  Error Err = Error::success();
69  if (!LeftOp)
70  Err = joinErrors(std::move(Err), LeftOp.takeError());
71  if (!RightOp)
72  Err = joinErrors(std::move(Err), RightOp.takeError());
73  return std::move(Err);
74  }
75 
76  return EvalBinop(*LeftOp, *RightOp);
77 }
78 
80  Expected<uint64_t> EvaluatedValue = ExpressionAST->eval();
81  if (!EvaluatedValue)
82  return EvaluatedValue.takeError();
83  return utostr(*EvaluatedValue);
84 }
85 
87  // Look up the value and escape it so that we can put it into the regex.
88  Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
89  if (!VarVal)
90  return VarVal.takeError();
91  return Regex::escape(*VarVal);
92 }
93 
95  return C == '_' || isalpha(C);
96 }
97 
100  if (Str.empty())
101  return FileCheckErrorDiagnostic::get(SM, Str, "empty variable name");
102 
103  bool ParsedOneChar = false;
104  unsigned I = 0;
105  bool IsPseudo = Str[0] == '@';
106 
107  // Global vars start with '$'.
108  if (Str[0] == '$' || IsPseudo)
109  ++I;
110 
111  for (unsigned E = Str.size(); I != E; ++I) {
112  if (!ParsedOneChar && !isValidVarNameStart(Str[I]))
113  return FileCheckErrorDiagnostic::get(SM, Str, "invalid variable name");
114 
115  // Variable names are composed of alphanumeric characters and underscores.
116  if (Str[I] != '_' && !isalnum(Str[I]))
117  break;
118  ParsedOneChar = true;
119  }
120 
121  StringRef Name = Str.take_front(I);
122  Str = Str.substr(I);
123  return VariableProperties {Name, IsPseudo};
124 }
125 
126 // StringRef holding all characters considered as horizontal whitespaces by
127 // FileCheck input canonicalization.
129 
130 // Parsing helper function that strips the first character in S and returns it.
131 static char popFront(StringRef &S) {
132  char C = S.front();
133  S = S.drop_front();
134  return C;
135 }
136 
140 
142 FileCheckPattern::parseNumericVariableDefinition(
144  Optional<size_t> LineNumber, FileCheckExpressionAST *ExpressionAST,
145  const SourceMgr &SM) {
146  Expected<VariableProperties> ParseVarResult = parseVariable(Expr, SM);
147  if (!ParseVarResult)
148  return ParseVarResult.takeError();
149  StringRef Name = ParseVarResult->Name;
150 
151  if (ParseVarResult->IsPseudo)
153  SM, Name, "definition of pseudo numeric variable unsupported");
154 
155  // Detect collisions between string and numeric variables when the latter
156  // is created later than the former.
157  if (Context->DefinedVariableTable.find(Name) !=
158  Context->DefinedVariableTable.end())
160  SM, Name, "string variable with name '" + Name + "' already exists");
161 
162  Expr = Expr.ltrim(SpaceChars);
163  if (!Expr.empty())
165  SM, Expr, "unexpected characters after numeric variable name");
166 
167  FileCheckNumericVariable *DefinedNumericVariable;
168  auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
169  if (VarTableIter != Context->GlobalNumericVariableTable.end())
170  DefinedNumericVariable = VarTableIter->second;
171  else
172  DefinedNumericVariable =
173  Context->makeNumericVariable(Name, LineNumber, ExpressionAST);
174 
175  return DefinedNumericVariable;
176 }
177 
179 FileCheckPattern::parseNumericVariableUse(StringRef Name, bool IsPseudo,
180  Optional<size_t> LineNumber,
181  FileCheckPatternContext *Context,
182  const SourceMgr &SM) {
183  if (IsPseudo && !Name.equals("@LINE"))
185  SM, Name, "invalid pseudo numeric variable '" + Name + "'");
186 
187  // Numeric variable definitions and uses are parsed in the order in which
188  // they appear in the CHECK patterns. For each definition, the pointer to the
189  // class instance of the corresponding numeric variable definition is stored
190  // in GlobalNumericVariableTable in parsePattern. Therefore, if the pointer
191  // we get below is null, it means no such variable was defined before. When
192  // that happens, we create a dummy variable so that parsing can continue. All
193  // uses of undefined variables, whether string or numeric, are then diagnosed
194  // in printSubstitutions() after failing to match.
195  auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
196  FileCheckNumericVariable *NumericVariable;
197  if (VarTableIter != Context->GlobalNumericVariableTable.end())
198  NumericVariable = VarTableIter->second;
199  else {
200  NumericVariable = Context->makeNumericVariable(Name);
201  Context->GlobalNumericVariableTable[Name] = NumericVariable;
202  }
203 
204  Optional<size_t> DefLineNumber = NumericVariable->getDefLineNumber();
205  if (DefLineNumber && LineNumber && *DefLineNumber == *LineNumber &&
206  !NumericVariable->isValueKnownAtMatchTime())
208  SM, Name,
209  "numeric variable '" + Name +
210  "' defined from input on the same line as used");
211 
212  return std::make_unique<FileCheckNumericVariableUse>(Name, NumericVariable);
213 }
214 
216 FileCheckPattern::parseNumericOperand(StringRef &Expr, AllowedOperand AO,
217  Optional<size_t> LineNumber,
218  FileCheckPatternContext *Context,
219  const SourceMgr &SM) {
220  if (AO == AllowedOperand::LineVar || AO == AllowedOperand::Any) {
221  // Try to parse as a numeric variable use.
223  parseVariable(Expr, SM);
224  if (ParseVarResult)
225  return parseNumericVariableUse(ParseVarResult->Name,
226  ParseVarResult->IsPseudo, LineNumber,
227  Context, SM);
228  if (AO == AllowedOperand::LineVar)
229  return ParseVarResult.takeError();
230  // Ignore the error and retry parsing as a literal.
231  consumeError(ParseVarResult.takeError());
232  }
233 
234  // Otherwise, parse it as a literal.
235  uint64_t LiteralValue;
236  if (!Expr.consumeInteger(/*Radix=*/10, LiteralValue))
237  return std::make_unique<FileCheckExpressionLiteral>(LiteralValue);
238 
239  return FileCheckErrorDiagnostic::get(SM, Expr,
240  "invalid operand format '" + Expr + "'");
241 }
242 
243 static uint64_t add(uint64_t LeftOp, uint64_t RightOp) {
244  return LeftOp + RightOp;
245 }
246 
247 static uint64_t sub(uint64_t LeftOp, uint64_t RightOp) {
248  return LeftOp - RightOp;
249 }
250 
251 Expected<std::unique_ptr<FileCheckExpressionAST>> FileCheckPattern::parseBinop(
252  StringRef &Expr, std::unique_ptr<FileCheckExpressionAST> LeftOp,
253  bool IsLegacyLineExpr, Optional<size_t> LineNumber,
254  FileCheckPatternContext *Context, const SourceMgr &SM) {
255  Expr = Expr.ltrim(SpaceChars);
256  if (Expr.empty())
257  return std::move(LeftOp);
258 
259  // Check if this is a supported operation and select a function to perform
260  // it.
261  SMLoc OpLoc = SMLoc::getFromPointer(Expr.data());
262  char Operator = popFront(Expr);
263  binop_eval_t EvalBinop;
264  switch (Operator) {
265  case '+':
266  EvalBinop = add;
267  break;
268  case '-':
269  EvalBinop = sub;
270  break;
271  default:
273  SM, OpLoc, Twine("unsupported operation '") + Twine(Operator) + "'");
274  }
275 
276  // Parse right operand.
277  Expr = Expr.ltrim(SpaceChars);
278  if (Expr.empty())
279  return FileCheckErrorDiagnostic::get(SM, Expr,
280  "missing operand in expression");
281  // The second operand in a legacy @LINE expression is always a literal.
282  AllowedOperand AO =
283  IsLegacyLineExpr ? AllowedOperand::Literal : AllowedOperand::Any;
285  parseNumericOperand(Expr, AO, LineNumber, Context, SM);
286  if (!RightOpResult)
287  return RightOpResult;
288 
289  Expr = Expr.ltrim(SpaceChars);
290  return std::make_unique<FileCheckASTBinop>(EvalBinop, std::move(LeftOp),
291  std::move(*RightOpResult));
292 }
293 
296  StringRef Expr,
297  Optional<FileCheckNumericVariable *> &DefinedNumericVariable,
298  bool IsLegacyLineExpr, Optional<size_t> LineNumber,
299  FileCheckPatternContext *Context, const SourceMgr &SM) {
300  std::unique_ptr<FileCheckExpressionAST> ExpressionAST = nullptr;
301  StringRef DefExpr = StringRef();
302  DefinedNumericVariable = None;
303  // Save variable definition expression if any.
304  size_t DefEnd = Expr.find(':');
305  if (DefEnd != StringRef::npos) {
306  DefExpr = Expr.substr(0, DefEnd);
307  Expr = Expr.substr(DefEnd + 1);
308  }
309 
310  // Parse the expression itself.
311  Expr = Expr.ltrim(SpaceChars);
312  if (!Expr.empty()) {
313  // The first operand in a legacy @LINE expression is always the @LINE
314  // pseudo variable.
315  AllowedOperand AO =
316  IsLegacyLineExpr ? AllowedOperand::LineVar : AllowedOperand::Any;
318  parseNumericOperand(Expr, AO, LineNumber, Context, SM);
319  while (ParseResult && !Expr.empty()) {
320  ParseResult = parseBinop(Expr, std::move(*ParseResult), IsLegacyLineExpr,
321  LineNumber, Context, SM);
322  // Legacy @LINE expressions only allow 2 operands.
323  if (ParseResult && IsLegacyLineExpr && !Expr.empty())
325  SM, Expr,
326  "unexpected characters at end of expression '" + Expr + "'");
327  }
328  if (!ParseResult)
329  return ParseResult;
330  ExpressionAST = std::move(*ParseResult);
331  }
332 
333  // Parse the numeric variable definition.
334  if (DefEnd != StringRef::npos) {
335  DefExpr = DefExpr.ltrim(SpaceChars);
337  parseNumericVariableDefinition(DefExpr, Context, LineNumber,
338  ExpressionAST.get(), SM);
339 
340  if (!ParseResult)
341  return ParseResult.takeError();
342  DefinedNumericVariable = *ParseResult;
343  }
344 
345  return std::move(ExpressionAST);
346 }
347 
349  SourceMgr &SM,
350  const FileCheckRequest &Req) {
351  bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
352 
353  PatternLoc = SMLoc::getFromPointer(PatternStr.data());
354 
355  if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
356  // Ignore trailing whitespace.
357  while (!PatternStr.empty() &&
358  (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
359  PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
360 
361  // Check that there is something on the line.
362  if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
363  SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
364  "found empty check string with prefix '" + Prefix + ":'");
365  return true;
366  }
367 
368  if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
369  SM.PrintMessage(
370  PatternLoc, SourceMgr::DK_Error,
371  "found non-empty check string for empty check with prefix '" + Prefix +
372  ":'");
373  return true;
374  }
375 
376  if (CheckTy == Check::CheckEmpty) {
377  RegExStr = "(\n$)";
378  return false;
379  }
380 
381  // Check to see if this is a fixed string, or if it has regex pieces.
382  if (!MatchFullLinesHere &&
383  (PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
384  PatternStr.find("[[") == StringRef::npos))) {
385  FixedStr = PatternStr;
386  return false;
387  }
388 
389  if (MatchFullLinesHere) {
390  RegExStr += '^';
391  if (!Req.NoCanonicalizeWhiteSpace)
392  RegExStr += " *";
393  }
394 
395  // Paren value #0 is for the fully matched string. Any new parenthesized
396  // values add from there.
397  unsigned CurParen = 1;
398 
399  // Otherwise, there is at least one regex piece. Build up the regex pattern
400  // by escaping scary characters in fixed strings, building up one big regex.
401  while (!PatternStr.empty()) {
402  // RegEx matches.
403  if (PatternStr.startswith("{{")) {
404  // This is the start of a regex match. Scan for the }}.
405  size_t End = PatternStr.find("}}");
406  if (End == StringRef::npos) {
407  SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
409  "found start of regex string with no end '}}'");
410  return true;
411  }
412 
413  // Enclose {{}} patterns in parens just like [[]] even though we're not
414  // capturing the result for any purpose. This is required in case the
415  // expression contains an alternation like: CHECK: abc{{x|z}}def. We
416  // want this to turn into: "abc(x|z)def" not "abcx|zdef".
417  RegExStr += '(';
418  ++CurParen;
419 
420  if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
421  return true;
422  RegExStr += ')';
423 
424  PatternStr = PatternStr.substr(End + 2);
425  continue;
426  }
427 
428  // String and numeric substitution blocks. Pattern substitution blocks come
429  // in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
430  // other regex) and assigns it to the string variable 'foo'. The latter
431  // substitutes foo's value. Numeric substitution blocks recognize the same
432  // form as string ones, but start with a '#' sign after the double
433  // brackets. They also accept a combined form which sets a numeric variable
434  // to the evaluation of an expression. Both string and numeric variable
435  // names must satisfy the regular expression "[a-zA-Z_][0-9a-zA-Z_]*" to be
436  // valid, as this helps catch some common errors.
437  if (PatternStr.startswith("[[")) {
438  StringRef UnparsedPatternStr = PatternStr.substr(2);
439  // Find the closing bracket pair ending the match. End is going to be an
440  // offset relative to the beginning of the match string.
441  size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
442  StringRef MatchStr = UnparsedPatternStr.substr(0, End);
443  bool IsNumBlock = MatchStr.consume_front("#");
444 
445  if (End == StringRef::npos) {
446  SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
448  "Invalid substitution block, no ]] found");
449  return true;
450  }
451  // Strip the substitution block we are parsing. End points to the start
452  // of the "]]" closing the expression so account for it in computing the
453  // index of the first unparsed character.
454  PatternStr = UnparsedPatternStr.substr(End + 2);
455 
456  bool IsDefinition = false;
457  bool SubstNeeded = false;
458  // Whether the substitution block is a legacy use of @LINE with string
459  // substitution block syntax.
460  bool IsLegacyLineExpr = false;
461  StringRef DefName;
462  StringRef SubstStr;
463  StringRef MatchRegexp;
464  size_t SubstInsertIdx = RegExStr.size();
465 
466  // Parse string variable or legacy @LINE expression.
467  if (!IsNumBlock) {
468  size_t VarEndIdx = MatchStr.find(":");
469  size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
470  if (SpacePos != StringRef::npos) {
471  SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
472  SourceMgr::DK_Error, "unexpected whitespace");
473  return true;
474  }
475 
476  // Get the name (e.g. "foo") and verify it is well formed.
477  StringRef OrigMatchStr = MatchStr;
479  parseVariable(MatchStr, SM);
480  if (!ParseVarResult) {
481  logAllUnhandledErrors(ParseVarResult.takeError(), errs());
482  return true;
483  }
484  StringRef Name = ParseVarResult->Name;
485  bool IsPseudo = ParseVarResult->IsPseudo;
486 
487  IsDefinition = (VarEndIdx != StringRef::npos);
488  SubstNeeded = !IsDefinition;
489  if (IsDefinition) {
490  if ((IsPseudo || !MatchStr.consume_front(":"))) {
493  "invalid name in string variable definition");
494  return true;
495  }
496 
497  // Detect collisions between string and numeric variables when the
498  // former is created later than the latter.
499  if (Context->GlobalNumericVariableTable.find(Name) !=
500  Context->GlobalNumericVariableTable.end()) {
501  SM.PrintMessage(
503  "numeric variable with name '" + Name + "' already exists");
504  return true;
505  }
506  DefName = Name;
507  MatchRegexp = MatchStr;
508  } else {
509  if (IsPseudo) {
510  MatchStr = OrigMatchStr;
511  IsLegacyLineExpr = IsNumBlock = true;
512  } else
513  SubstStr = Name;
514  }
515  }
516 
517  // Parse numeric substitution block.
518  std::unique_ptr<FileCheckExpressionAST> ExpressionAST;
519  Optional<FileCheckNumericVariable *> DefinedNumericVariable;
520  if (IsNumBlock) {
522  parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable,
523  IsLegacyLineExpr, LineNumber, Context,
524  SM);
525  if (!ParseResult) {
526  logAllUnhandledErrors(ParseResult.takeError(), errs());
527  return true;
528  }
529  ExpressionAST = std::move(*ParseResult);
530  SubstNeeded = ExpressionAST != nullptr;
531  if (DefinedNumericVariable) {
532  IsDefinition = true;
533  DefName = (*DefinedNumericVariable)->getName();
534  }
535  if (SubstNeeded)
536  SubstStr = MatchStr;
537  else
538  MatchRegexp = "[0-9]+";
539  }
540 
541  // Handle variable definition: [[<def>:(...)]] and [[#(...)<def>:(...)]].
542  if (IsDefinition) {
543  RegExStr += '(';
544  ++SubstInsertIdx;
545 
546  if (IsNumBlock) {
547  FileCheckNumericVariableMatch NumericVariableDefinition = {
548  *DefinedNumericVariable, CurParen};
549  NumericVariableDefs[DefName] = NumericVariableDefinition;
550  // This store is done here rather than in match() to allow
551  // parseNumericVariableUse() to get the pointer to the class instance
552  // of the right variable definition corresponding to a given numeric
553  // variable use.
554  Context->GlobalNumericVariableTable[DefName] =
555  *DefinedNumericVariable;
556  } else {
557  VariableDefs[DefName] = CurParen;
558  // Mark string variable as defined to detect collisions between
559  // string and numeric variables in parseNumericVariableUse() and
560  // defineCmdlineVariables() when the latter is created later than the
561  // former. We cannot reuse GlobalVariableTable for this by populating
562  // it with an empty string since we would then lose the ability to
563  // detect the use of an undefined variable in match().
564  Context->DefinedVariableTable[DefName] = true;
565  }
566 
567  ++CurParen;
568  }
569 
570  if (!MatchRegexp.empty() && AddRegExToRegEx(MatchRegexp, CurParen, SM))
571  return true;
572 
573  if (IsDefinition)
574  RegExStr += ')';
575 
576  // Handle substitutions: [[foo]] and [[#<foo expr>]].
577  if (SubstNeeded) {
578  // Handle substitution of string variables that were defined earlier on
579  // the same line by emitting a backreference. Expressions do not
580  // support substituting a numeric variable defined on the same line.
581  if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
582  unsigned CaptureParenGroup = VariableDefs[SubstStr];
583  if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
584  SM.PrintMessage(SMLoc::getFromPointer(SubstStr.data()),
586  "Can't back-reference more than 9 variables");
587  return true;
588  }
589  AddBackrefToRegEx(CaptureParenGroup);
590  } else {
591  // Handle substitution of string variables ([[<var>]]) defined in
592  // previous CHECK patterns, and substitution of expressions.
593  FileCheckSubstitution *Substitution =
594  IsNumBlock
595  ? Context->makeNumericSubstitution(
596  SubstStr, std::move(ExpressionAST), SubstInsertIdx)
597  : Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
598  Substitutions.push_back(Substitution);
599  }
600  }
601  }
602 
603  // Handle fixed string matches.
604  // Find the end, which is the start of the next regex.
605  size_t FixedMatchEnd = PatternStr.find("{{");
606  FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
607  RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
608  PatternStr = PatternStr.substr(FixedMatchEnd);
609  }
610 
611  if (MatchFullLinesHere) {
612  if (!Req.NoCanonicalizeWhiteSpace)
613  RegExStr += " *";
614  RegExStr += '$';
615  }
616 
617  return false;
618 }
619 
620 bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
621  Regex R(RS);
622  std::string Error;
623  if (!R.isValid(Error)) {
625  "invalid regex: " + Error);
626  return true;
627  }
628 
629  RegExStr += RS.str();
630  CurParen += R.getNumMatches();
631  return false;
632 }
633 
634 void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
635  assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
636  std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
637  RegExStr += Backref;
638 }
639 
641  const SourceMgr &SM) const {
642  // If this is the EOF pattern, match it immediately.
643  if (CheckTy == Check::CheckEOF) {
644  MatchLen = 0;
645  return Buffer.size();
646  }
647 
648  // If this is a fixed string pattern, just match it now.
649  if (!FixedStr.empty()) {
650  MatchLen = FixedStr.size();
651  size_t Pos = Buffer.find(FixedStr);
652  if (Pos == StringRef::npos)
653  return make_error<FileCheckNotFoundError>();
654  return Pos;
655  }
656 
657  // Regex match.
658 
659  // If there are substitutions, we need to create a temporary string with the
660  // actual value.
661  StringRef RegExToMatch = RegExStr;
662  std::string TmpStr;
663  if (!Substitutions.empty()) {
664  TmpStr = RegExStr;
665  if (LineNumber)
666  Context->LineVariable->setValue(*LineNumber);
667 
668  size_t InsertOffset = 0;
669  // Substitute all string variables and expressions whose values are only
670  // now known. Use of string variables defined on the same line are handled
671  // by back-references.
672  for (const auto &Substitution : Substitutions) {
673  // Substitute and check for failure (e.g. use of undefined variable).
674  Expected<std::string> Value = Substitution->getResult();
675  if (!Value)
676  return Value.takeError();
677 
678  // Plop it into the regex at the adjusted offset.
679  TmpStr.insert(TmpStr.begin() + Substitution->getIndex() + InsertOffset,
680  Value->begin(), Value->end());
681  InsertOffset += Value->size();
682  }
683 
684  // Match the newly constructed regex.
685  RegExToMatch = TmpStr;
686  }
687 
688  SmallVector<StringRef, 4> MatchInfo;
689  if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
690  return make_error<FileCheckNotFoundError>();
691 
692  // Successful regex match.
693  assert(!MatchInfo.empty() && "Didn't get any match");
694  StringRef FullMatch = MatchInfo[0];
695 
696  // If this defines any string variables, remember their values.
697  for (const auto &VariableDef : VariableDefs) {
698  assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
699  Context->GlobalVariableTable[VariableDef.first] =
700  MatchInfo[VariableDef.second];
701  }
702 
703  // If this defines any numeric variables, remember their values.
704  for (const auto &NumericVariableDef : NumericVariableDefs) {
705  const FileCheckNumericVariableMatch &NumericVariableMatch =
706  NumericVariableDef.getValue();
707  unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
708  assert(CaptureParenGroup < MatchInfo.size() && "Internal paren error");
709  FileCheckNumericVariable *DefinedNumericVariable =
710  NumericVariableMatch.DefinedNumericVariable;
711 
712  StringRef MatchedValue = MatchInfo[CaptureParenGroup];
713  uint64_t Val;
714  if (MatchedValue.getAsInteger(10, Val))
715  return FileCheckErrorDiagnostic::get(SM, MatchedValue,
716  "Unable to represent numeric value");
717  DefinedNumericVariable->setValue(Val);
718  }
719 
720  // Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
721  // the required preceding newline, which is consumed by the pattern in the
722  // case of CHECK-EMPTY but not CHECK-NEXT.
723  size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
724  MatchLen = FullMatch.size() - MatchStartSkip;
725  return FullMatch.data() - Buffer.data() + MatchStartSkip;
726 }
727 
728 unsigned FileCheckPattern::computeMatchDistance(StringRef Buffer) const {
729  // Just compute the number of matching characters. For regular expressions, we
730  // just compare against the regex itself and hope for the best.
731  //
732  // FIXME: One easy improvement here is have the regex lib generate a single
733  // example regular expression which matches, and use that as the example
734  // string.
735  StringRef ExampleString(FixedStr);
736  if (ExampleString.empty())
737  ExampleString = RegExStr;
738 
739  // Only compare up to the first line in the buffer, or the string size.
740  StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
741  BufferPrefix = BufferPrefix.split('\n').first;
742  return BufferPrefix.edit_distance(ExampleString);
743 }
744 
746  SMRange MatchRange) const {
747  // Print what we know about substitutions.
748  if (!Substitutions.empty()) {
749  for (const auto &Substitution : Substitutions) {
750  SmallString<256> Msg;
751  raw_svector_ostream OS(Msg);
752  Expected<std::string> MatchedValue = Substitution->getResult();
753 
754  // Substitution failed or is not known at match time, print the undefined
755  // variables it uses.
756  if (!MatchedValue) {
757  bool UndefSeen = false;
758  handleAllErrors(MatchedValue.takeError(),
759  [](const FileCheckNotFoundError &E) {},
760  // Handled in PrintNoMatch().
761  [](const FileCheckErrorDiagnostic &E) {},
762  [&](const FileCheckUndefVarError &E) {
763  if (!UndefSeen) {
764  OS << "uses undefined variable(s):";
765  UndefSeen = true;
766  }
767  OS << " ";
768  E.log(OS);
769  });
770  } else {
771  // Substitution succeeded. Print substituted value.
772  OS << "with \"";
773  OS.write_escaped(Substitution->getFromString()) << "\" equal to \"";
774  OS.write_escaped(*MatchedValue) << "\"";
775  }
776 
777  if (MatchRange.isValid())
778  SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
779  {MatchRange});
780  else
782  SourceMgr::DK_Note, OS.str());
783  }
784  }
785 }
786 
788  const SourceMgr &SM, SMLoc Loc,
789  Check::FileCheckType CheckTy,
790  StringRef Buffer, size_t Pos, size_t Len,
791  std::vector<FileCheckDiag> *Diags,
792  bool AdjustPrevDiag = false) {
793  SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
794  SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
795  SMRange Range(Start, End);
796  if (Diags) {
797  if (AdjustPrevDiag)
798  Diags->rbegin()->MatchTy = MatchTy;
799  else
800  Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
801  }
802  return Range;
803 }
804 
806  const SourceMgr &SM, StringRef Buffer,
807  std::vector<FileCheckDiag> *Diags) const {
808  // Attempt to find the closest/best fuzzy match. Usually an error happens
809  // because some string in the output didn't exactly match. In these cases, we
810  // would like to show the user a best guess at what "should have" matched, to
811  // save them having to actually check the input manually.
812  size_t NumLinesForward = 0;
813  size_t Best = StringRef::npos;
814  double BestQuality = 0;
815 
816  // Use an arbitrary 4k limit on how far we will search.
817  for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
818  if (Buffer[i] == '\n')
819  ++NumLinesForward;
820 
821  // Patterns have leading whitespace stripped, so skip whitespace when
822  // looking for something which looks like a pattern.
823  if (Buffer[i] == ' ' || Buffer[i] == '\t')
824  continue;
825 
826  // Compute the "quality" of this match as an arbitrary combination of the
827  // match distance and the number of lines skipped to get to this match.
828  unsigned Distance = computeMatchDistance(Buffer.substr(i));
829  double Quality = Distance + (NumLinesForward / 100.);
830 
831  if (Quality < BestQuality || Best == StringRef::npos) {
832  Best = i;
833  BestQuality = Quality;
834  }
835  }
836 
837  // Print the "possible intended match here" line if we found something
838  // reasonable and not equal to what we showed in the "scanning from here"
839  // line.
840  if (Best && Best != StringRef::npos && BestQuality < 50) {
841  SMRange MatchRange =
843  getCheckTy(), Buffer, Best, 0, Diags);
844  SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
845  "possible intended match here");
846 
847  // FIXME: If we wanted to be really friendly we would show why the match
848  // failed, as it can be hard to spot simple one character differences.
849  }
850 }
851 
854  auto VarIter = GlobalVariableTable.find(VarName);
855  if (VarIter == GlobalVariableTable.end())
856  return make_error<FileCheckUndefVarError>(VarName);
857 
858  return VarIter->second;
859 }
860 
861 template <class... Types>
863 FileCheckPatternContext::makeNumericVariable(Types... args) {
864  NumericVariables.push_back(
865  std::make_unique<FileCheckNumericVariable>(args...));
866  return NumericVariables.back().get();
867 }
868 
870 FileCheckPatternContext::makeStringSubstitution(StringRef VarName,
871  size_t InsertIdx) {
872  Substitutions.push_back(
873  std::make_unique<FileCheckStringSubstitution>(this, VarName, InsertIdx));
874  return Substitutions.back().get();
875 }
876 
877 FileCheckSubstitution *FileCheckPatternContext::makeNumericSubstitution(
878  StringRef ExpressionStr,
879  std::unique_ptr<FileCheckExpressionAST> ExpressionAST, size_t InsertIdx) {
880  Substitutions.push_back(std::make_unique<FileCheckNumericSubstitution>(
881  this, ExpressionStr, std::move(ExpressionAST), InsertIdx));
882  return Substitutions.back().get();
883 }
884 
885 size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
886  // Offset keeps track of the current offset within the input Str
887  size_t Offset = 0;
888  // [...] Nesting depth
889  size_t BracketDepth = 0;
890 
891  while (!Str.empty()) {
892  if (Str.startswith("]]") && BracketDepth == 0)
893  return Offset;
894  if (Str[0] == '\\') {
895  // Backslash escapes the next char within regexes, so skip them both.
896  Str = Str.substr(2);
897  Offset += 2;
898  } else {
899  switch (Str[0]) {
900  default:
901  break;
902  case '[':
903  BracketDepth++;
904  break;
905  case ']':
906  if (BracketDepth == 0) {
909  "missing closing \"]\" for regex variable");
910  exit(1);
911  }
912  BracketDepth--;
913  break;
914  }
915  Str = Str.substr(1);
916  Offset++;
917  }
918  }
919 
920  return StringRef::npos;
921 }
922 
924  SmallVectorImpl<char> &OutputBuffer) {
925  OutputBuffer.reserve(MB.getBufferSize());
926 
927  for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
928  Ptr != End; ++Ptr) {
929  // Eliminate trailing dosish \r.
930  if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
931  continue;
932  }
933 
934  // If current char is not a horizontal whitespace or if horizontal
935  // whitespace canonicalization is disabled, dump it to output as is.
936  if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
937  OutputBuffer.push_back(*Ptr);
938  continue;
939  }
940 
941  // Otherwise, add one space and advance over neighboring space.
942  OutputBuffer.push_back(' ');
943  while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
944  ++Ptr;
945  }
946 
947  // Add a null byte and then return all but that byte.
948  OutputBuffer.push_back('\0');
949  return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
950 }
951 
953  const Check::FileCheckType &CheckTy,
954  SMLoc CheckLoc, MatchType MatchTy,
955  SMRange InputRange)
956  : CheckTy(CheckTy), MatchTy(MatchTy) {
957  auto Start = SM.getLineAndColumn(InputRange.Start);
958  auto End = SM.getLineAndColumn(InputRange.End);
959  InputStartLine = Start.first;
960  InputStartCol = Start.second;
961  InputEndLine = End.first;
962  InputEndCol = End.second;
963  Start = SM.getLineAndColumn(CheckLoc);
964  CheckLine = Start.first;
965  CheckCol = Start.second;
966 }
967 
968 static bool IsPartOfWord(char c) {
969  return (isalnum(c) || c == '-' || c == '_');
970 }
971 
973  assert(Count > 0 && "zero and negative counts are not supported");
974  assert((C == 1 || Kind == CheckPlain) &&
975  "count supported only for plain CHECK directives");
976  Count = C;
977  return *this;
978 }
979 
981  switch (Kind) {
982  case Check::CheckNone:
983  return "invalid";
984  case Check::CheckPlain:
985  if (Count > 1)
986  return Prefix.str() + "-COUNT";
987  return Prefix;
988  case Check::CheckNext:
989  return Prefix.str() + "-NEXT";
990  case Check::CheckSame:
991  return Prefix.str() + "-SAME";
992  case Check::CheckNot:
993  return Prefix.str() + "-NOT";
994  case Check::CheckDAG:
995  return Prefix.str() + "-DAG";
996  case Check::CheckLabel:
997  return Prefix.str() + "-LABEL";
998  case Check::CheckEmpty:
999  return Prefix.str() + "-EMPTY";
1000  case Check::CheckEOF:
1001  return "implicit EOF";
1002  case Check::CheckBadNot:
1003  return "bad NOT";
1004  case Check::CheckBadCount:
1005  return "bad COUNT";
1006  }
1007  llvm_unreachable("unknown FileCheckType");
1008 }
1009 
1010 static std::pair<Check::FileCheckType, StringRef>
1012  if (Buffer.size() <= Prefix.size())
1013  return {Check::CheckNone, StringRef()};
1014 
1015  char NextChar = Buffer[Prefix.size()];
1016 
1017  StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
1018  // Verify that the : is present after the prefix.
1019  if (NextChar == ':')
1020  return {Check::CheckPlain, Rest};
1021 
1022  if (NextChar != '-')
1023  return {Check::CheckNone, StringRef()};
1024 
1025  if (Rest.consume_front("COUNT-")) {
1026  int64_t Count;
1027  if (Rest.consumeInteger(10, Count))
1028  // Error happened in parsing integer.
1029  return {Check::CheckBadCount, Rest};
1030  if (Count <= 0 || Count > INT32_MAX)
1031  return {Check::CheckBadCount, Rest};
1032  if (!Rest.consume_front(":"))
1033  return {Check::CheckBadCount, Rest};
1034  return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
1035  }
1036 
1037  if (Rest.consume_front("NEXT:"))
1038  return {Check::CheckNext, Rest};
1039 
1040  if (Rest.consume_front("SAME:"))
1041  return {Check::CheckSame, Rest};
1042 
1043  if (Rest.consume_front("NOT:"))
1044  return {Check::CheckNot, Rest};
1045 
1046  if (Rest.consume_front("DAG:"))
1047  return {Check::CheckDAG, Rest};
1048 
1049  if (Rest.consume_front("LABEL:"))
1050  return {Check::CheckLabel, Rest};
1051 
1052  if (Rest.consume_front("EMPTY:"))
1053  return {Check::CheckEmpty, Rest};
1054 
1055  // You can't combine -NOT with another suffix.
1056  if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
1057  Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
1058  Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
1059  Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
1060  return {Check::CheckBadNot, Rest};
1061 
1062  return {Check::CheckNone, Rest};
1063 }
1064 
1065 // From the given position, find the next character after the word.
1066 static size_t SkipWord(StringRef Str, size_t Loc) {
1067  while (Loc < Str.size() && IsPartOfWord(Str[Loc]))
1068  ++Loc;
1069  return Loc;
1070 }
1071 
1072 /// Searches the buffer for the first prefix in the prefix regular expression.
1073 ///
1074 /// This searches the buffer using the provided regular expression, however it
1075 /// enforces constraints beyond that:
1076 /// 1) The found prefix must not be a suffix of something that looks like
1077 /// a valid prefix.
1078 /// 2) The found prefix must be followed by a valid check type suffix using \c
1079 /// FindCheckType above.
1080 ///
1081 /// \returns a pair of StringRefs into the Buffer, which combines:
1082 /// - the first match of the regular expression to satisfy these two is
1083 /// returned,
1084 /// otherwise an empty StringRef is returned to indicate failure.
1085 /// - buffer rewound to the location right after parsed suffix, for parsing
1086 /// to continue from
1087 ///
1088 /// If this routine returns a valid prefix, it will also shrink \p Buffer to
1089 /// start at the beginning of the returned prefix, increment \p LineNumber for
1090 /// each new line consumed from \p Buffer, and set \p CheckTy to the type of
1091 /// check found by examining the suffix.
1092 ///
1093 /// If no valid prefix is found, the state of Buffer, LineNumber, and CheckTy
1094 /// is unspecified.
1095 static std::pair<StringRef, StringRef>
1097  unsigned &LineNumber, Check::FileCheckType &CheckTy) {
1098  SmallVector<StringRef, 2> Matches;
1099 
1100  while (!Buffer.empty()) {
1101  // Find the first (longest) match using the RE.
1102  if (!PrefixRE.match(Buffer, &Matches))
1103  // No match at all, bail.
1104  return {StringRef(), StringRef()};
1105 
1106  StringRef Prefix = Matches[0];
1107  Matches.clear();
1108 
1109  assert(Prefix.data() >= Buffer.data() &&
1110  Prefix.data() < Buffer.data() + Buffer.size() &&
1111  "Prefix doesn't start inside of buffer!");
1112  size_t Loc = Prefix.data() - Buffer.data();
1113  StringRef Skipped = Buffer.substr(0, Loc);
1114  Buffer = Buffer.drop_front(Loc);
1115  LineNumber += Skipped.count('\n');
1116 
1117  // Check that the matched prefix isn't a suffix of some other check-like
1118  // word.
1119  // FIXME: This is a very ad-hoc check. it would be better handled in some
1120  // other way. Among other things it seems hard to distinguish between
1121  // intentional and unintentional uses of this feature.
1122  if (Skipped.empty() || !IsPartOfWord(Skipped.back())) {
1123  // Now extract the type.
1124  StringRef AfterSuffix;
1125  std::tie(CheckTy, AfterSuffix) = FindCheckType(Buffer, Prefix);
1126 
1127  // If we've found a valid check type for this prefix, we're done.
1128  if (CheckTy != Check::CheckNone)
1129  return {Prefix, AfterSuffix};
1130  }
1131 
1132  // If we didn't successfully find a prefix, we need to skip this invalid
1133  // prefix and continue scanning. We directly skip the prefix that was
1134  // matched and any additional parts of that check-like word.
1135  Buffer = Buffer.drop_front(SkipWord(Buffer, Prefix.size()));
1136  }
1137 
1138  // We ran out of buffer while skipping partial matches so give up.
1139  return {StringRef(), StringRef()};
1140 }
1141 
1143  assert(!LineVariable && "@LINE pseudo numeric variable already created");
1144  StringRef LineName = "@LINE";
1145  LineVariable = makeNumericVariable(LineName);
1146  GlobalNumericVariableTable[LineName] = LineVariable;
1147 }
1148 
1150  std::vector<FileCheckString> &CheckStrings) {
1151  Error DefineError =
1152  PatternContext.defineCmdlineVariables(Req.GlobalDefines, SM);
1153  if (DefineError) {
1154  logAllUnhandledErrors(std::move(DefineError), errs());
1155  return true;
1156  }
1157 
1158  PatternContext.createLineVariable();
1159 
1160  std::vector<FileCheckPattern> ImplicitNegativeChecks;
1161  for (const auto &PatternString : Req.ImplicitCheckNot) {
1162  // Create a buffer with fake command line content in order to display the
1163  // command line option responsible for the specific implicit CHECK-NOT.
1164  std::string Prefix = "-implicit-check-not='";
1165  std::string Suffix = "'";
1166  std::unique_ptr<MemoryBuffer> CmdLine = MemoryBuffer::getMemBufferCopy(
1167  Prefix + PatternString + Suffix, "command line");
1168 
1169  StringRef PatternInBuffer =
1170  CmdLine->getBuffer().substr(Prefix.size(), PatternString.size());
1171  SM.AddNewSourceBuffer(std::move(CmdLine), SMLoc());
1172 
1173  ImplicitNegativeChecks.push_back(
1174  FileCheckPattern(Check::CheckNot, &PatternContext));
1175  ImplicitNegativeChecks.back().parsePattern(PatternInBuffer,
1176  "IMPLICIT-CHECK", SM, Req);
1177  }
1178 
1179  std::vector<FileCheckPattern> DagNotMatches = ImplicitNegativeChecks;
1180 
1181  // LineNumber keeps track of the line on which CheckPrefix instances are
1182  // found.
1183  unsigned LineNumber = 1;
1184 
1185  while (1) {
1187 
1188  // See if a prefix occurs in the memory buffer.
1189  StringRef UsedPrefix;
1190  StringRef AfterSuffix;
1191  std::tie(UsedPrefix, AfterSuffix) =
1192  FindFirstMatchingPrefix(PrefixRE, Buffer, LineNumber, CheckTy);
1193  if (UsedPrefix.empty())
1194  break;
1195  assert(UsedPrefix.data() == Buffer.data() &&
1196  "Failed to move Buffer's start forward, or pointed prefix outside "
1197  "of the buffer!");
1198  assert(AfterSuffix.data() >= Buffer.data() &&
1199  AfterSuffix.data() < Buffer.data() + Buffer.size() &&
1200  "Parsing after suffix doesn't start inside of buffer!");
1201 
1202  // Location to use for error messages.
1203  const char *UsedPrefixStart = UsedPrefix.data();
1204 
1205  // Skip the buffer to the end of parsed suffix (or just prefix, if no good
1206  // suffix was processed).
1207  Buffer = AfterSuffix.empty() ? Buffer.drop_front(UsedPrefix.size())
1208  : AfterSuffix;
1209 
1210  // Complain about useful-looking but unsupported suffixes.
1211  if (CheckTy == Check::CheckBadNot) {
1213  "unsupported -NOT combo on prefix '" + UsedPrefix + "'");
1214  return true;
1215  }
1216 
1217  // Complain about invalid count specification.
1218  if (CheckTy == Check::CheckBadCount) {
1220  "invalid count in -COUNT specification on prefix '" +
1221  UsedPrefix + "'");
1222  return true;
1223  }
1224 
1225  // Okay, we found the prefix, yay. Remember the rest of the line, but ignore
1226  // leading whitespace.
1227  if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
1228  Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
1229 
1230  // Scan ahead to the end of line.
1231  size_t EOL = Buffer.find_first_of("\n\r");
1232 
1233  // Remember the location of the start of the pattern, for diagnostics.
1234  SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
1235 
1236  // Parse the pattern.
1237  FileCheckPattern P(CheckTy, &PatternContext, LineNumber);
1238  if (P.parsePattern(Buffer.substr(0, EOL), UsedPrefix, SM, Req))
1239  return true;
1240 
1241  // Verify that CHECK-LABEL lines do not define or use variables
1242  if ((CheckTy == Check::CheckLabel) && P.hasVariable()) {
1243  SM.PrintMessage(
1244  SMLoc::getFromPointer(UsedPrefixStart), SourceMgr::DK_Error,
1245  "found '" + UsedPrefix + "-LABEL:'"
1246  " with variable definition or use");
1247  return true;
1248  }
1249 
1250  Buffer = Buffer.substr(EOL);
1251 
1252  // Verify that CHECK-NEXT/SAME/EMPTY lines have at least one CHECK line before them.
1253  if ((CheckTy == Check::CheckNext || CheckTy == Check::CheckSame ||
1254  CheckTy == Check::CheckEmpty) &&
1255  CheckStrings.empty()) {
1256  StringRef Type = CheckTy == Check::CheckNext
1257  ? "NEXT"
1258  : CheckTy == Check::CheckEmpty ? "EMPTY" : "SAME";
1259  SM.PrintMessage(SMLoc::getFromPointer(UsedPrefixStart),
1261  "found '" + UsedPrefix + "-" + Type +
1262  "' without previous '" + UsedPrefix + ": line");
1263  return true;
1264  }
1265 
1266  // Handle CHECK-DAG/-NOT.
1267  if (CheckTy == Check::CheckDAG || CheckTy == Check::CheckNot) {
1268  DagNotMatches.push_back(P);
1269  continue;
1270  }
1271 
1272  // Okay, add the string we captured to the output vector and move on.
1273  CheckStrings.emplace_back(P, UsedPrefix, PatternLoc);
1274  std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1275  DagNotMatches = ImplicitNegativeChecks;
1276  }
1277 
1278  // Add an EOF pattern for any trailing CHECK-DAG/-NOTs, and use the first
1279  // prefix as a filler for the error message.
1280  if (!DagNotMatches.empty()) {
1281  CheckStrings.emplace_back(
1282  FileCheckPattern(Check::CheckEOF, &PatternContext, LineNumber + 1),
1283  *Req.CheckPrefixes.begin(), SMLoc::getFromPointer(Buffer.data()));
1284  std::swap(DagNotMatches, CheckStrings.back().DagNotStrings);
1285  }
1286 
1287  if (CheckStrings.empty()) {
1288  errs() << "error: no check strings found with prefix"
1289  << (Req.CheckPrefixes.size() > 1 ? "es " : " ");
1290  auto I = Req.CheckPrefixes.begin();
1291  auto E = Req.CheckPrefixes.end();
1292  if (I != E) {
1293  errs() << "\'" << *I << ":'";
1294  ++I;
1295  }
1296  for (; I != E; ++I)
1297  errs() << ", \'" << *I << ":'";
1298 
1299  errs() << '\n';
1300  return true;
1301  }
1302 
1303  return false;
1304 }
1305 
1306 static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
1307  StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat,
1308  int MatchedCount, StringRef Buffer, size_t MatchPos,
1309  size_t MatchLen, const FileCheckRequest &Req,
1310  std::vector<FileCheckDiag> *Diags) {
1311  bool PrintDiag = true;
1312  if (ExpectedMatch) {
1313  if (!Req.Verbose)
1314  return;
1315  if (!Req.VerboseVerbose && Pat.getCheckTy() == Check::CheckEOF)
1316  return;
1317  // Due to their verbosity, we don't print verbose diagnostics here if we're
1318  // gathering them for a different rendering, but we always print other
1319  // diagnostics.
1320  PrintDiag = !Diags;
1321  }
1322  SMRange MatchRange = ProcessMatchResult(
1323  ExpectedMatch ? FileCheckDiag::MatchFoundAndExpected
1325  SM, Loc, Pat.getCheckTy(), Buffer, MatchPos, MatchLen, Diags);
1326  if (!PrintDiag)
1327  return;
1328 
1329  std::string Message = formatv("{0}: {1} string found in input",
1330  Pat.getCheckTy().getDescription(Prefix),
1331  (ExpectedMatch ? "expected" : "excluded"))
1332  .str();
1333  if (Pat.getCount() > 1)
1334  Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1335 
1336  SM.PrintMessage(
1337  Loc, ExpectedMatch ? SourceMgr::DK_Remark : SourceMgr::DK_Error, Message);
1338  SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, "found here",
1339  {MatchRange});
1340  Pat.printSubstitutions(SM, Buffer, MatchRange);
1341 }
1342 
1343 static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM,
1344  const FileCheckString &CheckStr, int MatchedCount,
1345  StringRef Buffer, size_t MatchPos, size_t MatchLen,
1346  FileCheckRequest &Req,
1347  std::vector<FileCheckDiag> *Diags) {
1348  PrintMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
1349  MatchedCount, Buffer, MatchPos, MatchLen, Req, Diags);
1350 }
1351 
1352 static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
1353  StringRef Prefix, SMLoc Loc,
1354  const FileCheckPattern &Pat, int MatchedCount,
1355  StringRef Buffer, bool VerboseVerbose,
1356  std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
1357  assert(MatchErrors && "Called on successful match");
1358  bool PrintDiag = true;
1359  if (!ExpectedMatch) {
1360  if (!VerboseVerbose) {
1361  consumeError(std::move(MatchErrors));
1362  return;
1363  }
1364  // Due to their verbosity, we don't print verbose diagnostics here if we're
1365  // gathering them for a different rendering, but we always print other
1366  // diagnostics.
1367  PrintDiag = !Diags;
1368  }
1369 
1370  // If the current position is at the end of a line, advance to the start of
1371  // the next line.
1372  Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
1373  SMRange SearchRange = ProcessMatchResult(
1374  ExpectedMatch ? FileCheckDiag::MatchNoneButExpected
1376  SM, Loc, Pat.getCheckTy(), Buffer, 0, Buffer.size(), Diags);
1377  if (!PrintDiag) {
1378  consumeError(std::move(MatchErrors));
1379  return;
1380  }
1381 
1382  MatchErrors =
1383  handleErrors(std::move(MatchErrors),
1384  [](const FileCheckErrorDiagnostic &E) { E.log(errs()); });
1385 
1386  // No problem matching the string per se.
1387  if (!MatchErrors)
1388  return;
1389  consumeError(std::move(MatchErrors));
1390 
1391  // Print "not found" diagnostic.
1392  std::string Message = formatv("{0}: {1} string not found in input",
1393  Pat.getCheckTy().getDescription(Prefix),
1394  (ExpectedMatch ? "expected" : "excluded"))
1395  .str();
1396  if (Pat.getCount() > 1)
1397  Message += formatv(" ({0} out of {1})", MatchedCount, Pat.getCount()).str();
1398  SM.PrintMessage(
1399  Loc, ExpectedMatch ? SourceMgr::DK_Error : SourceMgr::DK_Remark, Message);
1400 
1401  // Print the "scanning from here" line.
1402  SM.PrintMessage(SearchRange.Start, SourceMgr::DK_Note, "scanning from here");
1403 
1404  // Allow the pattern to print additional information if desired.
1405  Pat.printSubstitutions(SM, Buffer);
1406 
1407  if (ExpectedMatch)
1408  Pat.printFuzzyMatch(SM, Buffer, Diags);
1409 }
1410 
1411 static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM,
1412  const FileCheckString &CheckStr, int MatchedCount,
1413  StringRef Buffer, bool VerboseVerbose,
1414  std::vector<FileCheckDiag> *Diags, Error MatchErrors) {
1415  PrintNoMatch(ExpectedMatch, SM, CheckStr.Prefix, CheckStr.Loc, CheckStr.Pat,
1416  MatchedCount, Buffer, VerboseVerbose, Diags,
1417  std::move(MatchErrors));
1418 }
1419 
1420 /// Counts the number of newlines in the specified range.
1421 static unsigned CountNumNewlinesBetween(StringRef Range,
1422  const char *&FirstNewLine) {
1423  unsigned NumNewLines = 0;
1424  while (1) {
1425  // Scan for newline.
1426  Range = Range.substr(Range.find_first_of("\n\r"));
1427  if (Range.empty())
1428  return NumNewLines;
1429 
1430  ++NumNewLines;
1431 
1432  // Handle \n\r and \r\n as a single newline.
1433  if (Range.size() > 1 && (Range[1] == '\n' || Range[1] == '\r') &&
1434  (Range[0] != Range[1]))
1435  Range = Range.substr(1);
1436  Range = Range.substr(1);
1437 
1438  if (NumNewLines == 1)
1439  FirstNewLine = Range.begin();
1440  }
1441 }
1442 
1443 size_t FileCheckString::Check(const SourceMgr &SM, StringRef Buffer,
1444  bool IsLabelScanMode, size_t &MatchLen,
1445  FileCheckRequest &Req,
1446  std::vector<FileCheckDiag> *Diags) const {
1447  size_t LastPos = 0;
1448  std::vector<const FileCheckPattern *> NotStrings;
1449 
1450  // IsLabelScanMode is true when we are scanning forward to find CHECK-LABEL
1451  // bounds; we have not processed variable definitions within the bounded block
1452  // yet so cannot handle any final CHECK-DAG yet; this is handled when going
1453  // over the block again (including the last CHECK-LABEL) in normal mode.
1454  if (!IsLabelScanMode) {
1455  // Match "dag strings" (with mixed "not strings" if any).
1456  LastPos = CheckDag(SM, Buffer, NotStrings, Req, Diags);
1457  if (LastPos == StringRef::npos)
1458  return StringRef::npos;
1459  }
1460 
1461  // Match itself from the last position after matching CHECK-DAG.
1462  size_t LastMatchEnd = LastPos;
1463  size_t FirstMatchPos = 0;
1464  // Go match the pattern Count times. Majority of patterns only match with
1465  // count 1 though.
1466  assert(Pat.getCount() != 0 && "pattern count can not be zero");
1467  for (int i = 1; i <= Pat.getCount(); i++) {
1468  StringRef MatchBuffer = Buffer.substr(LastMatchEnd);
1469  size_t CurrentMatchLen;
1470  // get a match at current start point
1471  Expected<size_t> MatchResult = Pat.match(MatchBuffer, CurrentMatchLen, SM);
1472 
1473  // report
1474  if (!MatchResult) {
1475  PrintNoMatch(true, SM, *this, i, MatchBuffer, Req.VerboseVerbose, Diags,
1476  MatchResult.takeError());
1477  return StringRef::npos;
1478  }
1479  size_t MatchPos = *MatchResult;
1480  PrintMatch(true, SM, *this, i, MatchBuffer, MatchPos, CurrentMatchLen, Req,
1481  Diags);
1482  if (i == 1)
1483  FirstMatchPos = LastPos + MatchPos;
1484 
1485  // move start point after the match
1486  LastMatchEnd += MatchPos + CurrentMatchLen;
1487  }
1488  // Full match len counts from first match pos.
1489  MatchLen = LastMatchEnd - FirstMatchPos;
1490 
1491  // Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
1492  // or CHECK-NOT
1493  if (!IsLabelScanMode) {
1494  size_t MatchPos = FirstMatchPos - LastPos;
1495  StringRef MatchBuffer = Buffer.substr(LastPos);
1496  StringRef SkippedRegion = Buffer.substr(LastPos, MatchPos);
1497 
1498  // If this check is a "CHECK-NEXT", verify that the previous match was on
1499  // the previous line (i.e. that there is one newline between them).
1500  if (CheckNext(SM, SkippedRegion)) {
1502  Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
1503  Diags, Req.Verbose);
1504  return StringRef::npos;
1505  }
1506 
1507  // If this check is a "CHECK-SAME", verify that the previous match was on
1508  // the same line (i.e. that there is no newline between them).
1509  if (CheckSame(SM, SkippedRegion)) {
1511  Pat.getCheckTy(), MatchBuffer, MatchPos, MatchLen,
1512  Diags, Req.Verbose);
1513  return StringRef::npos;
1514  }
1515 
1516  // If this match had "not strings", verify that they don't exist in the
1517  // skipped region.
1518  if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
1519  return StringRef::npos;
1520  }
1521 
1522  return FirstMatchPos;
1523 }
1524 
1525 bool FileCheckString::CheckNext(const SourceMgr &SM, StringRef Buffer) const {
1526  if (Pat.getCheckTy() != Check::CheckNext &&
1527  Pat.getCheckTy() != Check::CheckEmpty)
1528  return false;
1529 
1530  Twine CheckName =
1531  Prefix +
1532  Twine(Pat.getCheckTy() == Check::CheckEmpty ? "-EMPTY" : "-NEXT");
1533 
1534  // Count the number of newlines between the previous match and this one.
1535  const char *FirstNewLine = nullptr;
1536  unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1537 
1538  if (NumNewLines == 0) {
1540  CheckName + ": is on the same line as previous match");
1542  "'next' match was here");
1544  "previous match ended here");
1545  return true;
1546  }
1547 
1548  if (NumNewLines != 1) {
1550  CheckName +
1551  ": is not on the line after the previous match");
1553  "'next' match was here");
1555  "previous match ended here");
1557  "non-matching line after previous match is here");
1558  return true;
1559  }
1560 
1561  return false;
1562 }
1563 
1564 bool FileCheckString::CheckSame(const SourceMgr &SM, StringRef Buffer) const {
1565  if (Pat.getCheckTy() != Check::CheckSame)
1566  return false;
1567 
1568  // Count the number of newlines between the previous match and this one.
1569  const char *FirstNewLine = nullptr;
1570  unsigned NumNewLines = CountNumNewlinesBetween(Buffer, FirstNewLine);
1571 
1572  if (NumNewLines != 0) {
1574  Prefix +
1575  "-SAME: is not on the same line as the previous match");
1577  "'next' match was here");
1579  "previous match ended here");
1580  return true;
1581  }
1582 
1583  return false;
1584 }
1585 
1587  const SourceMgr &SM, StringRef Buffer,
1588  const std::vector<const FileCheckPattern *> &NotStrings,
1589  const FileCheckRequest &Req, std::vector<FileCheckDiag> *Diags) const {
1590  for (const FileCheckPattern *Pat : NotStrings) {
1591  assert((Pat->getCheckTy() == Check::CheckNot) && "Expect CHECK-NOT!");
1592 
1593  size_t MatchLen = 0;
1594  Expected<size_t> MatchResult = Pat->match(Buffer, MatchLen, SM);
1595 
1596  if (!MatchResult) {
1597  PrintNoMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer,
1598  Req.VerboseVerbose, Diags, MatchResult.takeError());
1599  continue;
1600  }
1601  size_t Pos = *MatchResult;
1602 
1603  PrintMatch(false, SM, Prefix, Pat->getLoc(), *Pat, 1, Buffer, Pos, MatchLen,
1604  Req, Diags);
1605 
1606  return true;
1607  }
1608 
1609  return false;
1610 }
1611 
1612 size_t
1614  std::vector<const FileCheckPattern *> &NotStrings,
1615  const FileCheckRequest &Req,
1616  std::vector<FileCheckDiag> *Diags) const {
1617  if (DagNotStrings.empty())
1618  return 0;
1619 
1620  // The start of the search range.
1621  size_t StartPos = 0;
1622 
1623  struct MatchRange {
1624  size_t Pos;
1625  size_t End;
1626  };
1627  // A sorted list of ranges for non-overlapping CHECK-DAG matches. Match
1628  // ranges are erased from this list once they are no longer in the search
1629  // range.
1630  std::list<MatchRange> MatchRanges;
1631 
1632  // We need PatItr and PatEnd later for detecting the end of a CHECK-DAG
1633  // group, so we don't use a range-based for loop here.
1634  for (auto PatItr = DagNotStrings.begin(), PatEnd = DagNotStrings.end();
1635  PatItr != PatEnd; ++PatItr) {
1636  const FileCheckPattern &Pat = *PatItr;
1637  assert((Pat.getCheckTy() == Check::CheckDAG ||
1638  Pat.getCheckTy() == Check::CheckNot) &&
1639  "Invalid CHECK-DAG or CHECK-NOT!");
1640 
1641  if (Pat.getCheckTy() == Check::CheckNot) {
1642  NotStrings.push_back(&Pat);
1643  continue;
1644  }
1645 
1646  assert((Pat.getCheckTy() == Check::CheckDAG) && "Expect CHECK-DAG!");
1647 
1648  // CHECK-DAG always matches from the start.
1649  size_t MatchLen = 0, MatchPos = StartPos;
1650 
1651  // Search for a match that doesn't overlap a previous match in this
1652  // CHECK-DAG group.
1653  for (auto MI = MatchRanges.begin(), ME = MatchRanges.end(); true; ++MI) {
1654  StringRef MatchBuffer = Buffer.substr(MatchPos);
1655  Expected<size_t> MatchResult = Pat.match(MatchBuffer, MatchLen, SM);
1656  // With a group of CHECK-DAGs, a single mismatching means the match on
1657  // that group of CHECK-DAGs fails immediately.
1658  if (!MatchResult) {
1659  PrintNoMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, MatchBuffer,
1660  Req.VerboseVerbose, Diags, MatchResult.takeError());
1661  return StringRef::npos;
1662  }
1663  size_t MatchPosBuf = *MatchResult;
1664  // Re-calc it as the offset relative to the start of the original string.
1665  MatchPos += MatchPosBuf;
1666  if (Req.VerboseVerbose)
1667  PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1668  MatchLen, Req, Diags);
1669  MatchRange M{MatchPos, MatchPos + MatchLen};
1670  if (Req.AllowDeprecatedDagOverlap) {
1671  // We don't need to track all matches in this mode, so we just maintain
1672  // one match range that encompasses the current CHECK-DAG group's
1673  // matches.
1674  if (MatchRanges.empty())
1675  MatchRanges.insert(MatchRanges.end(), M);
1676  else {
1677  auto Block = MatchRanges.begin();
1678  Block->Pos = std::min(Block->Pos, M.Pos);
1679  Block->End = std::max(Block->End, M.End);
1680  }
1681  break;
1682  }
1683  // Iterate previous matches until overlapping match or insertion point.
1684  bool Overlap = false;
1685  for (; MI != ME; ++MI) {
1686  if (M.Pos < MI->End) {
1687  // !Overlap => New match has no overlap and is before this old match.
1688  // Overlap => New match overlaps this old match.
1689  Overlap = MI->Pos < M.End;
1690  break;
1691  }
1692  }
1693  if (!Overlap) {
1694  // Insert non-overlapping match into list.
1695  MatchRanges.insert(MI, M);
1696  break;
1697  }
1698  if (Req.VerboseVerbose) {
1699  // Due to their verbosity, we don't print verbose diagnostics here if
1700  // we're gathering them for a different rendering, but we always print
1701  // other diagnostics.
1702  if (!Diags) {
1703  SMLoc OldStart = SMLoc::getFromPointer(Buffer.data() + MI->Pos);
1704  SMLoc OldEnd = SMLoc::getFromPointer(Buffer.data() + MI->End);
1705  SMRange OldRange(OldStart, OldEnd);
1706  SM.PrintMessage(OldStart, SourceMgr::DK_Note,
1707  "match discarded, overlaps earlier DAG match here",
1708  {OldRange});
1709  } else
1710  Diags->rbegin()->MatchTy = FileCheckDiag::MatchFoundButDiscarded;
1711  }
1712  MatchPos = MI->End;
1713  }
1714  if (!Req.VerboseVerbose)
1715  PrintMatch(true, SM, Prefix, Pat.getLoc(), Pat, 1, Buffer, MatchPos,
1716  MatchLen, Req, Diags);
1717 
1718  // Handle the end of a CHECK-DAG group.
1719  if (std::next(PatItr) == PatEnd ||
1720  std::next(PatItr)->getCheckTy() == Check::CheckNot) {
1721  if (!NotStrings.empty()) {
1722  // If there are CHECK-NOTs between two CHECK-DAGs or from CHECK to
1723  // CHECK-DAG, verify that there are no 'not' strings occurred in that
1724  // region.
1725  StringRef SkippedRegion =
1726  Buffer.slice(StartPos, MatchRanges.begin()->Pos);
1727  if (CheckNot(SM, SkippedRegion, NotStrings, Req, Diags))
1728  return StringRef::npos;
1729  // Clear "not strings".
1730  NotStrings.clear();
1731  }
1732  // All subsequent CHECK-DAGs and CHECK-NOTs should be matched from the
1733  // end of this CHECK-DAG group's match range.
1734  StartPos = MatchRanges.rbegin()->End;
1735  // Don't waste time checking for (impossible) overlaps before that.
1736  MatchRanges.clear();
1737  }
1738  }
1739 
1740  return StartPos;
1741 }
1742 
1743 // A check prefix must contain only alphanumeric, hyphens and underscores.
1744 static bool ValidateCheckPrefix(StringRef CheckPrefix) {
1745  Regex Validator("^[a-zA-Z0-9_-]*$");
1746  return Validator.match(CheckPrefix);
1747 }
1748 
1750  StringSet<> PrefixSet;
1751 
1752  for (StringRef Prefix : Req.CheckPrefixes) {
1753  // Reject empty prefixes.
1754  if (Prefix == "")
1755  return false;
1756 
1757  if (!PrefixSet.insert(Prefix).second)
1758  return false;
1759 
1760  if (!ValidateCheckPrefix(Prefix))
1761  return false;
1762  }
1763 
1764  return true;
1765 }
1766 
1768  // I don't think there's a way to specify an initial value for cl::list,
1769  // so if nothing was specified, add the default
1770  if (Req.CheckPrefixes.empty())
1771  Req.CheckPrefixes.push_back("CHECK");
1772 
1773  // We already validated the contents of CheckPrefixes so just concatenate
1774  // them as alternatives.
1775  SmallString<32> PrefixRegexStr;
1776  for (StringRef Prefix : Req.CheckPrefixes) {
1777  if (Prefix != Req.CheckPrefixes.front())
1778  PrefixRegexStr.push_back('|');
1779 
1780  PrefixRegexStr.append(Prefix);
1781  }
1782 
1783  return Regex(PrefixRegexStr);
1784 }
1785 
1787  std::vector<std::string> &CmdlineDefines, SourceMgr &SM) {
1788  assert(GlobalVariableTable.empty() && GlobalNumericVariableTable.empty() &&
1789  "Overriding defined variable with command-line variable definitions");
1790 
1791  if (CmdlineDefines.empty())
1792  return Error::success();
1793 
1794  // Create a string representing the vector of command-line definitions. Each
1795  // definition is on its own line and prefixed with a definition number to
1796  // clarify which definition a given diagnostic corresponds to.
1797  unsigned I = 0;
1798  Error Errs = Error::success();
1799  std::string CmdlineDefsDiag;
1800  SmallVector<std::pair<size_t, size_t>, 4> CmdlineDefsIndices;
1801  for (StringRef CmdlineDef : CmdlineDefines) {
1802  std::string DefPrefix = ("Global define #" + Twine(++I) + ": ").str();
1803  size_t EqIdx = CmdlineDef.find('=');
1804  if (EqIdx == StringRef::npos) {
1805  CmdlineDefsIndices.push_back(std::make_pair(CmdlineDefsDiag.size(), 0));
1806  continue;
1807  }
1808  // Numeric variable definition.
1809  if (CmdlineDef[0] == '#') {
1810  // Append a copy of the command-line definition adapted to use the same
1811  // format as in the input file to be able to reuse
1812  // parseNumericSubstitutionBlock.
1813  CmdlineDefsDiag += (DefPrefix + CmdlineDef + " (parsed as: [[").str();
1814  std::string SubstitutionStr = CmdlineDef;
1815  SubstitutionStr[EqIdx] = ':';
1816  CmdlineDefsIndices.push_back(
1817  std::make_pair(CmdlineDefsDiag.size(), SubstitutionStr.size()));
1818  CmdlineDefsDiag += (SubstitutionStr + Twine("]])\n")).str();
1819  } else {
1820  CmdlineDefsDiag += DefPrefix;
1821  CmdlineDefsIndices.push_back(
1822  std::make_pair(CmdlineDefsDiag.size(), CmdlineDef.size()));
1823  CmdlineDefsDiag += (CmdlineDef + "\n").str();
1824  }
1825  }
1826 
1827  // Create a buffer with fake command line content in order to display
1828  // parsing diagnostic with location information and point to the
1829  // global definition with invalid syntax.
1830  std::unique_ptr<MemoryBuffer> CmdLineDefsDiagBuffer =
1831  MemoryBuffer::getMemBufferCopy(CmdlineDefsDiag, "Global defines");
1832  StringRef CmdlineDefsDiagRef = CmdLineDefsDiagBuffer->getBuffer();
1833  SM.AddNewSourceBuffer(std::move(CmdLineDefsDiagBuffer), SMLoc());
1834 
1835  for (std::pair<size_t, size_t> CmdlineDefIndices : CmdlineDefsIndices) {
1836  StringRef CmdlineDef = CmdlineDefsDiagRef.substr(CmdlineDefIndices.first,
1837  CmdlineDefIndices.second);
1838  if (CmdlineDef.empty()) {
1839  Errs = joinErrors(
1840  std::move(Errs),
1842  SM, CmdlineDef, "missing equal sign in global definition"));
1843  continue;
1844  }
1845 
1846  // Numeric variable definition.
1847  if (CmdlineDef[0] == '#') {
1848  // Now parse the definition both to check that the syntax is correct and
1849  // to create the necessary class instance.
1850  StringRef CmdlineDefExpr = CmdlineDef.substr(1);
1851  Optional<FileCheckNumericVariable *> DefinedNumericVariable;
1854  CmdlineDefExpr, DefinedNumericVariable, false, None, this, SM);
1855  if (!ExpressionASTResult) {
1856  Errs = joinErrors(std::move(Errs), ExpressionASTResult.takeError());
1857  continue;
1858  }
1859  std::unique_ptr<FileCheckExpressionAST> ExpressionAST =
1860  std::move(*ExpressionASTResult);
1861  // Now evaluate the expression whose value this variable should be set
1862  // to, since the expression of a command-line variable definition should
1863  // only use variables defined earlier on the command-line. If not, this
1864  // is an error and we report it.
1865  Expected<uint64_t> Value = ExpressionAST->eval();
1866  if (!Value) {
1867  Errs = joinErrors(std::move(Errs), Value.takeError());
1868  continue;
1869  }
1870 
1871  assert(DefinedNumericVariable && "No variable defined");
1872  (*DefinedNumericVariable)->setValue(*Value);
1873 
1874  // Record this variable definition.
1875  GlobalNumericVariableTable[(*DefinedNumericVariable)->getName()] =
1876  *DefinedNumericVariable;
1877  } else {
1878  // String variable definition.
1879  std::pair<StringRef, StringRef> CmdlineNameVal = CmdlineDef.split('=');
1880  StringRef CmdlineName = CmdlineNameVal.first;
1881  StringRef OrigCmdlineName = CmdlineName;
1883  FileCheckPattern::parseVariable(CmdlineName, SM);
1884  if (!ParseVarResult) {
1885  Errs = joinErrors(std::move(Errs), ParseVarResult.takeError());
1886  continue;
1887  }
1888  // Check that CmdlineName does not denote a pseudo variable is only
1889  // composed of the parsed numeric variable. This catches cases like
1890  // "FOO+2" in a "FOO+2=10" definition.
1891  if (ParseVarResult->IsPseudo || !CmdlineName.empty()) {
1892  Errs = joinErrors(std::move(Errs),
1894  SM, OrigCmdlineName,
1895  "invalid name in string variable definition '" +
1896  OrigCmdlineName + "'"));
1897  continue;
1898  }
1899  StringRef Name = ParseVarResult->Name;
1900 
1901  // Detect collisions between string and numeric variables when the former
1902  // is created later than the latter.
1903  if (GlobalNumericVariableTable.find(Name) !=
1904  GlobalNumericVariableTable.end()) {
1905  Errs = joinErrors(std::move(Errs), FileCheckErrorDiagnostic::get(
1906  SM, Name,
1907  "numeric variable with name '" +
1908  Name + "' already exists"));
1909  continue;
1910  }
1911  GlobalVariableTable.insert(CmdlineNameVal);
1912  // Mark the string variable as defined to detect collisions between
1913  // string and numeric variables in defineCmdlineVariables when the latter
1914  // is created later than the former. We cannot reuse GlobalVariableTable
1915  // for this by populating it with an empty string since we would then
1916  // lose the ability to detect the use of an undefined variable in
1917  // match().
1918  DefinedVariableTable[Name] = true;
1919  }
1920  }
1921 
1922  return Errs;
1923 }
1924 
1926  SmallVector<StringRef, 16> LocalPatternVars, LocalNumericVars;
1927  for (const StringMapEntry<StringRef> &Var : GlobalVariableTable)
1928  if (Var.first()[0] != '$')
1929  LocalPatternVars.push_back(Var.first());
1930 
1931  // Numeric substitution reads the value of a variable directly, not via
1932  // GlobalNumericVariableTable. Therefore, we clear local variables by
1933  // clearing their value which will lead to a numeric substitution failure. We
1934  // also mark the variable for removal from GlobalNumericVariableTable since
1935  // this is what defineCmdlineVariables checks to decide that no global
1936  // variable has been defined.
1937  for (const auto &Var : GlobalNumericVariableTable)
1938  if (Var.first()[0] != '$') {
1939  Var.getValue()->clearValue();
1940  LocalNumericVars.push_back(Var.first());
1941  }
1942 
1943  for (const auto &Var : LocalPatternVars)
1944  GlobalVariableTable.erase(Var);
1945  for (const auto &Var : LocalNumericVars)
1946  GlobalNumericVariableTable.erase(Var);
1947 }
1948 
1950  ArrayRef<FileCheckString> CheckStrings,
1951  std::vector<FileCheckDiag> *Diags) {
1952  bool ChecksFailed = false;
1953 
1954  unsigned i = 0, j = 0, e = CheckStrings.size();
1955  while (true) {
1956  StringRef CheckRegion;
1957  if (j == e) {
1958  CheckRegion = Buffer;
1959  } else {
1960  const FileCheckString &CheckLabelStr = CheckStrings[j];
1961  if (CheckLabelStr.Pat.getCheckTy() != Check::CheckLabel) {
1962  ++j;
1963  continue;
1964  }
1965 
1966  // Scan to next CHECK-LABEL match, ignoring CHECK-NOT and CHECK-DAG
1967  size_t MatchLabelLen = 0;
1968  size_t MatchLabelPos =
1969  CheckLabelStr.Check(SM, Buffer, true, MatchLabelLen, Req, Diags);
1970  if (MatchLabelPos == StringRef::npos)
1971  // Immediately bail if CHECK-LABEL fails, nothing else we can do.
1972  return false;
1973 
1974  CheckRegion = Buffer.substr(0, MatchLabelPos + MatchLabelLen);
1975  Buffer = Buffer.substr(MatchLabelPos + MatchLabelLen);
1976  ++j;
1977  }
1978 
1979  // Do not clear the first region as it's the one before the first
1980  // CHECK-LABEL and it would clear variables defined on the command-line
1981  // before they get used.
1982  if (i != 0 && Req.EnableVarScope)
1983  PatternContext.clearLocalVars();
1984 
1985  for (; i != j; ++i) {
1986  const FileCheckString &CheckStr = CheckStrings[i];
1987 
1988  // Check each string within the scanned region, including a second check
1989  // of any final CHECK-LABEL (to verify CHECK-NOT and CHECK-DAG)
1990  size_t MatchLen = 0;
1991  size_t MatchPos =
1992  CheckStr.Check(SM, CheckRegion, false, MatchLen, Req, Diags);
1993 
1994  if (MatchPos == StringRef::npos) {
1995  ChecksFailed = true;
1996  i = j;
1997  break;
1998  }
1999 
2000  CheckRegion = CheckRegion.substr(MatchPos + MatchLen);
2001  }
2002 
2003  if (j == e)
2004  break;
2005  }
2006 
2007  // Success if no checks failed.
2008  return !ChecksFailed;
2009 }
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:703
uint64_t CallInst * C
static void PrintNoMatch(bool ExpectedMatch, const SourceMgr &SM, StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat, int MatchedCount, StringRef Buffer, bool VerboseVerbose, std::vector< FileCheckDiag > *Diags, Error MatchErrors)
Definition: FileCheck.cpp:1352
static Error get(const SourceMgr &SM, SMLoc Loc, const Twine &ErrMsg)
Definition: FileCheck.h:417
Represents a range in source code.
Definition: SMLoc.h:48
LLVM_NODISCARD StringRef take_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with only the first N elements remaining.
Definition: StringRef.h:587
Indicates a good match for an expected pattern.
Definition: FileCheck.h:675
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Indicates no match for an excluded pattern.
Definition: FileCheck.h:684
Parsing information about a variable.
Definition: FileCheck.h:524
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:218
LLVMContext & Context
This class represents lattice values for constants.
Definition: AllocatorList.h:23
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
Definition: StringMap.h:125
Indicates a discarded match for an expected pattern.
Definition: FileCheck.h:682
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
void push_back(const T &Elt)
Definition: SmallVector.h:211
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:649
bool CheckSame(const SourceMgr &SM, StringRef Buffer) const
Verifies that there is no newline in the given Buffer.
Definition: FileCheck.cpp:1564
static std::string escape(StringRef String)
Turn String into a regex by escaping its special characters.
Definition: Regex.cpp:200
iterator find(StringRef Key)
Definition: StringMap.h:332
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:530
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
std::string getDescription(StringRef Prefix) const
Definition: FileCheck.cpp:980
Marks when parsing found a -NOT check combined with another CHECK suffix.
Definition: FileCheck.h:295
size_t getBufferSize() const
Definition: MemoryBuffer.h:61
Regex buildCheckPrefixRegex()
Definition: FileCheck.cpp:1767
LLVM_NODISCARD StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
Definition: StringRef.h:789
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
void printSubstitutions(const SourceMgr &SM, StringRef Buffer, SMRange MatchRange=None) const
Prints the value of successful substitutions or the name of the undefined string or numeric variables...
Definition: FileCheck.cpp:745
bool isValueKnownAtMatchTime() const
Definition: FileCheck.cpp:27
void reserve(size_type N)
Definition: SmallVector.h:369
std::pair< unsigned, unsigned > getLineAndColumn(SMLoc Loc, unsigned BufferID=0) const
Find the line and column number for the specified location in the specified file. ...
Definition: SourceMgr.cpp:125
LLVM_NODISCARD unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
Definition: StringRef.cpp:94
size_t CheckDag(const SourceMgr &SM, StringRef Buffer, std::vector< const FileCheckPattern *> &NotStrings, const FileCheckRequest &Req, std::vector< FileCheckDiag > *Diags) const
Matches "dag strings" and their mixed "not strings".
Definition: FileCheck.cpp:1613
bool CheckNext(const SourceMgr &SM, StringRef Buffer) const
Verifies that there is a single line in the given Buffer.
Definition: FileCheck.cpp:1525
SMLoc Start
Definition: SMLoc.h:50
Class representing a numeric variable and its associated current value.
Definition: FileCheck.h:96
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode *>> &RecordedNodes)
CheckSame - Implements OP_CheckSame.
StringRef Prefix
Which prefix name this check matched.
Definition: FileCheck.h:713
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:47
FileCheckPattern Pat
The pattern to match.
Definition: FileCheck.h:710
void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None, bool ShowColors=true) const
Emit a message about the specified location with the specified string.
Definition: SourceMgr.cpp:242
Class holding the FileCheckPattern global state, shared by all patterns: tables holding values of var...
Definition: FileCheck.h:324
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the first N elements dropped.
Definition: StringRef.h:620
LLVM_NODISCARD size_t count(char C) const
Return the number of occurrences of C in the string.
Definition: StringRef.h:457
SMLoc Loc
The location in the match file that the check string was specified.
Definition: FileCheck.h:716
Check::FileCheckType CheckTy
What is the FileCheck directive for this diagnostic?
Definition: FileCheck.h:656
Indicates a match for an expected pattern, but the match is on the wrong line.
Definition: FileCheck.h:680
bool parsePattern(StringRef PatternStr, StringRef Prefix, SourceMgr &SM, const FileCheckRequest &Req)
Parses the pattern in PatternStr and initializes this FileCheckPattern instance accordingly.
Definition: FileCheck.cpp:348
LLVM_NODISCARD StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition: StringRef.h:679
Expected< std::string > getResult() const override
Definition: FileCheck.cpp:79
Class representing a substitution to perform in the RegExStr string.
Definition: FileCheck.h:209
Tagged union holding either a T or a Error.
Definition: yaml2obj.h:21
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:578
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
Marks when parsing found a -COUNT directive with invalid count value.
Definition: FileCheck.h:298
Expected< std::string > getResult() const override
Definition: FileCheck.cpp:86
static Expected< std::unique_ptr< FileCheckExpressionAST > > parseNumericSubstitutionBlock(StringRef Expr, Optional< FileCheckNumericVariable *> &DefinedNumericVariable, bool IsLegacyLineExpr, Optional< size_t > LineNumber, FileCheckPatternContext *Context, const SourceMgr &SM)
Parses Expr for a numeric substitution block at line LineNumber, or before input is parsed if LineNum...
Definition: FileCheck.cpp:295
Class to represent an error holding a diagnostic with location information used when printing it...
Definition: FileCheck.h:401
static std::pair< Check::FileCheckType, StringRef > FindCheckType(StringRef Buffer, StringRef Prefix)
Definition: FileCheck.cpp:1011
Base class representing the AST of a given expression.
Definition: FileCheck.h:48
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type consumeInteger(unsigned Radix, T &Result)
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:512
static unsigned CountNumNewlinesBetween(StringRef Range, const char *&FirstNewLine)
Counts the number of newlines in the specified range.
Definition: FileCheck.cpp:1421
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:153
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
Contains info about various FileCheck options.
Definition: FileCheck.h:30
static bool ValidateCheckPrefix(StringRef CheckPrefix)
Definition: FileCheck.cpp:1744
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
Expected< uint64_t > eval() const
Definition: FileCheck.cpp:49
size_t Check(const SourceMgr &SM, StringRef Buffer, bool IsLabelScanMode, size_t &MatchLen, FileCheckRequest &Req, std::vector< FileCheckDiag > *Diags) const
Matches check string and its "not strings" and/or "dag strings".
Definition: FileCheck.cpp:1443
void append(in_iter S, in_iter E)
Append from an iterator pair.
Definition: SmallString.h:74
bool ValidateCheckPrefixes()
Definition: FileCheck.cpp:1749
unsigned InputEndLine
Definition: FileCheck.h:697
#define P(N)
A check that we found in the input file.
Definition: FileCheck.h:708
void clearLocalVars()
Undefines local variables (variables whose name does not start with a &#39;$&#39; sign), i.e.
Definition: FileCheck.cpp:1925
FileCheckDiag(const SourceMgr &SM, const Check::FileCheckType &CheckTy, SMLoc CheckLoc, MatchType MatchTy, SMRange InputRange)
Definition: FileCheck.cpp:952
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
StringRef CanonicalizeFile(MemoryBuffer &MB, SmallVectorImpl< char > &OutputBuffer)
Canonicalizes whitespaces in the file.
Definition: FileCheck.cpp:923
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_NODISCARD size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Definition: StringRef.cpp:249
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:285
unsigned CheckLine
Where is the FileCheck directive for this diagnostic?
Definition: FileCheck.h:658
SMLoc getLoc() const
Definition: FileCheck.h:514
void createLineVariable()
Create pseudo variable.
Definition: FileCheck.cpp:1142
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
Definition: SourceMgr.h:41
Check::FileCheckType getCheckTy() const
Definition: FileCheck.h:586
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:981
size_t size() const
Definition: SmallVector.h:52
LLVM_NODISCARD char back() const
back - Get the last character in the string.
Definition: StringRef.h:141
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition: Error.cpp:61
Class to represent an undefined variable error, which quotes that variable&#39;s name when printed...
Definition: FileCheck.h:73
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::pair< typename base::iterator, bool > insert(StringRef Key)
Definition: StringSet.h:38
bool ReadCheckFile(SourceMgr &SM, StringRef Buffer, Regex &PrefixRE, std::vector< FileCheckString > &CheckStrings)
Reads the check file from Buffer and records the expected strings it contains in the CheckStrings vec...
Definition: FileCheck.cpp:1149
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:478
Indicates the pattern only matches the end of file.
Definition: FileCheck.h:292
bool isValid() const
Definition: SMLoc.h:59
static size_t SkipWord(StringRef Str, size_t Loc)
Definition: FileCheck.cpp:1066
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:904
raw_ostream & write_escaped(StringRef Str, bool UseHexEscapes=false)
Output Str, turning &#39;\&#39;, &#39;&#39;, &#39; &#39;, &#39;"&#39;, and anything that doesn&#39;t satisfy llvm::isPrint into an escape...
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
Indicates a fuzzy match that serves as a suggestion for the next intended match for an expected patte...
Definition: FileCheck.h:691
static std::pair< StringRef, StringRef > FindFirstMatchingPrefix(Regex &PrefixRE, StringRef &Buffer, unsigned &LineNumber, Check::FileCheckType &CheckTy)
Searches the buffer for the first prefix in the prefix regular expression.
Definition: FileCheck.cpp:1096
void log(raw_ostream &OS) const override
Print diagnostic associated with this error when printing the error.
Definition: FileCheck.h:415
static uint64_t add(uint64_t LeftOp, uint64_t RightOp)
Definition: FileCheck.cpp:243
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition: Operator.h:30
Indicates no match for an expected pattern, but this might follow good matches when multiple matches ...
Definition: FileCheck.h:688
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:696
static Expected< VariableProperties > parseVariable(StringRef &Str, const SourceMgr &SM)
Parses the string at the start of Str for a variable name.
Definition: FileCheck.cpp:99
bool isValid(std::string &Error) const
isValid - returns the error encountered during regex compilation, or matching, if any...
Definition: Regex.cpp:55
StringRef str()
Return a StringRef for the vector contents.
Definition: raw_ostream.h:555
unsigned InputEndCol
Definition: FileCheck.h:698
uint64_t(*)(uint64_t, uint64_t) binop_eval_t
Type of functions evaluating a given binary operation.
Definition: FileCheck.h:176
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
Expected< uint64_t > eval() const
Evaluates the value of the binary operation represented by this AST, using EvalBinop on the result of...
Definition: FileCheck.cpp:61
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:41
static void PrintMatch(bool ExpectedMatch, const SourceMgr &SM, StringRef Prefix, SMLoc Loc, const FileCheckPattern &Pat, int MatchedCount, StringRef Buffer, size_t MatchPos, size_t MatchLen, const FileCheckRequest &Req, std::vector< FileCheckDiag > *Diags)
Definition: FileCheck.cpp:1306
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
StringRef SpaceChars
Definition: FileCheck.cpp:128
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it...
static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy, const SourceMgr &SM, SMLoc Loc, Check::FileCheckType CheckTy, StringRef Buffer, size_t Pos, size_t Len, std::vector< FileCheckDiag > *Diags, bool AdjustPrevDiag=false)
Definition: FileCheck.cpp:787
bool CheckNot(const SourceMgr &SM, StringRef Buffer, const std::vector< const FileCheckPattern *> &NotStrings, const FileCheckRequest &Req, std::vector< FileCheckDiag > *Diags) const
Verifies that none of the strings in NotStrings are found in the given Buffer.
Definition: FileCheck.cpp:1586
SMLoc End
Definition: SMLoc.h:50
void printFuzzyMatch(const SourceMgr &SM, StringRef Buffer, std::vector< FileCheckDiag > *Diags) const
Definition: FileCheck.cpp:805
unsigned getNumMatches() const
getNumMatches - In a valid regex, return the number of parenthesized matches it contains.
Definition: Regex.cpp:68
Expected< StringRef > getPatternVarValue(StringRef VarName)
Definition: FileCheck.cpp:853
iterator begin() const
Definition: StringRef.h:101
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
unsigned InputStartLine
The search range if MatchTy is MatchNoneAndExcluded or MatchNoneButExpected, or the match range other...
Definition: FileCheck.h:695
LLVM_NODISCARD bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
Definition: StringRef.h:160
bool CheckInput(SourceMgr &SM, StringRef Buffer, ArrayRef< FileCheckString > CheckStrings, std::vector< FileCheckDiag > *Diags=nullptr)
Checks the input to FileCheck provided in the Buffer against the CheckStrings read from the check fil...
Definition: FileCheck.cpp:1949
Indicates a match for an excluded pattern.
Definition: FileCheck.h:677
const char * getBufferEnd() const
Definition: MemoryBuffer.h:60
FileCheckType & setCount(int C)
Definition: FileCheck.cpp:972
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:144
static const size_t npos
Definition: StringRef.h:50
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:423
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:380
#define I(x, y, z)
Definition: MD5.cpp:58
const char * getBufferStart() const
Definition: MemoryBuffer.h:59
Compile for newline-sensitive matching.
Definition: Regex.h:38
static bool IsPartOfWord(char c)
Definition: FileCheck.cpp:968
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:122
unsigned InputStartCol
Definition: FileCheck.h:696
Expected< size_t > match(StringRef Buffer, size_t &MatchLen, const SourceMgr &SM) const
Matches the pattern string against the input buffer Buffer.
Definition: FileCheck.cpp:640
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM_NODISCARD char front() const
front - Get the first character in the string.
Definition: StringRef.h:134
Error defineCmdlineVariables(std::vector< std::string > &CmdlineDefines, SourceMgr &SM)
Defines string and numeric variables from definitions given on the command line, passed as a vector o...
Definition: FileCheck.cpp:1786
LLVM Value Representation.
Definition: Value.h:73
static char popFront(StringRef &S)
Definition: FileCheck.cpp:131
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:27
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition: Error.h:881
static uint64_t sub(uint64_t LeftOp, uint64_t RightOp)
Definition: FileCheck.cpp:247
bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr)
matches - Match the regex against a given String.
Definition: Regex.cpp:72
IRTranslator LLVM IR MI
virtual Expected< uint64_t > eval() const =0
Evaluates and.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
MatchType
What type of match result does this diagnostic describe?
Definition: FileCheck.h:673
int getCount() const
Definition: FileCheck.h:588
Represents a location in source code.
Definition: SMLoc.h:23
iterator end() const
Definition: StringRef.h:103
static bool isValidVarNameStart(char C)
Definition: FileCheck.cpp:94
void setValue(uint64_t NewValue)
Sets value of this numeric variable to NewValue.
Definition: FileCheck.cpp:34
iterator end()
Definition: StringMap.h:317