1 //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
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 /// \file
10 /// Implements # directive processing for the Preprocessor.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/Module.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TokenKinds.h"
22 #include "clang/Lex/CodeCompletionHandler.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Lex/LexDiagnostic.h"
25 #include "clang/Lex/LiteralSupport.h"
26 #include "clang/Lex/MacroInfo.h"
27 #include "clang/Lex/ModuleLoader.h"
28 #include "clang/Lex/ModuleMap.h"
29 #include "clang/Lex/PPCallbacks.h"
30 #include "clang/Lex/Pragma.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/PreprocessorOptions.h"
33 #include "clang/Lex/Token.h"
34 #include "clang/Lex/VariadicMacroSupport.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/ScopeExit.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/StringSwitch.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/Support/AlignOf.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/Path.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstring>
48 #include <new>
49 #include <string>
50 #include <utility>
51 
52 using namespace clang;
53 
54 //===----------------------------------------------------------------------===//
55 // Utility Methods for Preprocessor Directive Handling.
56 //===----------------------------------------------------------------------===//
57 
58 MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
59   auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead};
60   MIChainHead = MIChain;
61   return &MIChain->MI;
62 }
63 
64 DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
65                                                            SourceLocation Loc) {
66   return new (BP) DefMacroDirective(MI, Loc);
67 }
68 
69 UndefMacroDirective *
70 Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
71   return new (BP) UndefMacroDirective(UndefLoc);
72 }
73 
74 VisibilityMacroDirective *
75 Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
76                                                bool isPublic) {
77   return new (BP) VisibilityMacroDirective(Loc, isPublic);
78 }
79 
80 /// Read and discard all tokens remaining on the current line until
81 /// the tok::eod token is found.
82 SourceRange Preprocessor::DiscardUntilEndOfDirective() {
83   Token Tmp;
84   SourceRange Res;
85 
86   LexUnexpandedToken(Tmp);
87   Res.setBegin(Tmp.getLocation());
88   while (Tmp.isNot(tok::eod)) {
89     assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
90     LexUnexpandedToken(Tmp);
91   }
92   Res.setEnd(Tmp.getLocation());
93   return Res;
94 }
95 
96 /// Enumerates possible cases of #define/#undef a reserved identifier.
97 enum MacroDiag {
98   MD_NoWarn,        //> Not a reserved identifier
99   MD_KeywordDef,    //> Macro hides keyword, enabled by default
100   MD_ReservedMacro  //> #define of #undef reserved id, disabled by default
101 };
102 
103 /// Enumerates possible %select values for the pp_err_elif_after_else and
104 /// pp_err_elif_without_if diagnostics.
105 enum PPElifDiag {
106   PED_Elif,
107   PED_Elifdef,
108   PED_Elifndef
109 };
110 
111 // The -fmodule-name option tells the compiler to textually include headers in
112 // the specified module, meaning clang won't build the specified module. This is
113 // useful in a number of situations, for instance, when building a library that
114 // vends a module map, one might want to avoid hitting intermediate build
115 // products containing the the module map or avoid finding the system installed
116 // modulemap for that library.
117 static bool isForModuleBuilding(Module *M, StringRef CurrentModule,
118                                 StringRef ModuleName) {
119   StringRef TopLevelName = M->getTopLevelModuleName();
120 
121   // When building framework Foo, we wanna make sure that Foo *and* Foo_Private
122   // are textually included and no modules are built for both.
123   if (M->getTopLevelModule()->IsFramework && CurrentModule == ModuleName &&
124       !CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
125     TopLevelName = TopLevelName.drop_back(8);
126 
127   return TopLevelName == CurrentModule;
128 }
129 
130 static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
131   const LangOptions &Lang = PP.getLangOpts();
132   if (II->isReserved(Lang) != ReservedIdentifierStatus::NotReserved) {
133     // list from:
134     // - https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_macros.html
135     // - https://docs.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt?view=msvc-160
136     // - man 7 feature_test_macros
137     // The list must be sorted for correct binary search.
138     static constexpr StringRef ReservedMacro[] = {
139         "_ATFILE_SOURCE",
140         "_BSD_SOURCE",
141         "_CRT_NONSTDC_NO_WARNINGS",
142         "_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES",
143         "_CRT_SECURE_NO_WARNINGS",
144         "_FILE_OFFSET_BITS",
145         "_FORTIFY_SOURCE",
146         "_GLIBCXX_ASSERTIONS",
147         "_GLIBCXX_CONCEPT_CHECKS",
148         "_GLIBCXX_DEBUG",
149         "_GLIBCXX_DEBUG_PEDANTIC",
150         "_GLIBCXX_PARALLEL",
151         "_GLIBCXX_PARALLEL_ASSERTIONS",
152         "_GLIBCXX_SANITIZE_VECTOR",
153         "_GLIBCXX_USE_CXX11_ABI",
154         "_GLIBCXX_USE_DEPRECATED",
155         "_GNU_SOURCE",
156         "_ISOC11_SOURCE",
157         "_ISOC95_SOURCE",
158         "_ISOC99_SOURCE",
159         "_LARGEFILE64_SOURCE",
160         "_POSIX_C_SOURCE",
161         "_REENTRANT",
162         "_SVID_SOURCE",
163         "_THREAD_SAFE",
164         "_XOPEN_SOURCE",
165         "_XOPEN_SOURCE_EXTENDED",
166         "__STDCPP_WANT_MATH_SPEC_FUNCS__",
167         "__STDC_FORMAT_MACROS",
168     };
169     if (std::binary_search(std::begin(ReservedMacro), std::end(ReservedMacro),
170                            II->getName()))
171       return MD_NoWarn;
172 
173     return MD_ReservedMacro;
174   }
175   StringRef Text = II->getName();
176   if (II->isKeyword(Lang))
177     return MD_KeywordDef;
178   if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
179     return MD_KeywordDef;
180   return MD_NoWarn;
181 }
182 
183 static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
184   const LangOptions &Lang = PP.getLangOpts();
185   // Do not warn on keyword undef.  It is generally harmless and widely used.
186   if (II->isReserved(Lang) != ReservedIdentifierStatus::NotReserved)
187     return MD_ReservedMacro;
188   return MD_NoWarn;
189 }
190 
191 // Return true if we want to issue a diagnostic by default if we
192 // encounter this name in a #include with the wrong case. For now,
193 // this includes the standard C and C++ headers, Posix headers,
194 // and Boost headers. Improper case for these #includes is a
195 // potential portability issue.
196 static bool warnByDefaultOnWrongCase(StringRef Include) {
197   // If the first component of the path is "boost", treat this like a standard header
198   // for the purposes of diagnostics.
199   if (::llvm::sys::path::begin(Include)->equals_lower("boost"))
200     return true;
201 
202   // "condition_variable" is the longest standard header name at 18 characters.
203   // If the include file name is longer than that, it can't be a standard header.
204   static const size_t MaxStdHeaderNameLen = 18u;
205   if (Include.size() > MaxStdHeaderNameLen)
206     return false;
207 
208   // Lowercase and normalize the search string.
209   SmallString<32> LowerInclude{Include};
210   for (char &Ch : LowerInclude) {
211     // In the ASCII range?
212     if (static_cast<unsigned char>(Ch) > 0x7f)
213       return false; // Can't be a standard header
214     // ASCII lowercase:
215     if (Ch >= 'A' && Ch <= 'Z')
216       Ch += 'a' - 'A';
217     // Normalize path separators for comparison purposes.
218     else if (::llvm::sys::path::is_separator(Ch))
219       Ch = '/';
220   }
221 
222   // The standard C/C++ and Posix headers
223   return llvm::StringSwitch<bool>(LowerInclude)
224     // C library headers
225     .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
226     .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
227     .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
228     .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
229     .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
230     .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
231 
232     // C++ headers for C library facilities
233     .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
234     .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
235     .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
236     .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
237     .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
238     .Case("cwctype", true)
239 
240     // C++ library headers
241     .Cases("algorithm", "fstream", "list", "regex", "thread", true)
242     .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
243     .Cases("atomic", "future", "map", "set", "type_traits", true)
244     .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
245     .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
246     .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
247     .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
248     .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
249     .Cases("deque", "istream", "queue", "string", "valarray", true)
250     .Cases("exception", "iterator", "random", "strstream", "vector", true)
251     .Cases("forward_list", "limits", "ratio", "system_error", true)
252 
253     // POSIX headers (which aren't also C headers)
254     .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
255     .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
256     .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
257     .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
258     .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
259     .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
260     .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
261     .Cases("sys/resource.h", "sys/select.h",  "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
262     .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
263     .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
264     .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
265     .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
266     .Default(false);
267 }
268 
269 bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
270                                   bool *ShadowFlag) {
271   // Missing macro name?
272   if (MacroNameTok.is(tok::eod))
273     return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
274 
275   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
276   if (!II)
277     return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
278 
279   if (II->isCPlusPlusOperatorKeyword()) {
280     // C++ 2.5p2: Alternative tokens behave the same as its primary token
281     // except for their spellings.
282     Diag(MacroNameTok, getLangOpts().MicrosoftExt
283                            ? diag::ext_pp_operator_used_as_macro_name
284                            : diag::err_pp_operator_used_as_macro_name)
285         << II << MacroNameTok.getKind();
286     // Allow #defining |and| and friends for Microsoft compatibility or
287     // recovery when legacy C headers are included in C++.
288   }
289 
290   if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
291     // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
292     return Diag(MacroNameTok, diag::err_defined_macro_name);
293   }
294 
295   if (isDefineUndef == MU_Undef) {
296     auto *MI = getMacroInfo(II);
297     if (MI && MI->isBuiltinMacro()) {
298       // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
299       // and C++ [cpp.predefined]p4], but allow it as an extension.
300       Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
301     }
302   }
303 
304   // If defining/undefining reserved identifier or a keyword, we need to issue
305   // a warning.
306   SourceLocation MacroNameLoc = MacroNameTok.getLocation();
307   if (ShadowFlag)
308     *ShadowFlag = false;
309   if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
310       (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
311     MacroDiag D = MD_NoWarn;
312     if (isDefineUndef == MU_Define) {
313       D = shouldWarnOnMacroDef(*this, II);
314     }
315     else if (isDefineUndef == MU_Undef)
316       D = shouldWarnOnMacroUndef(*this, II);
317     if (D == MD_KeywordDef) {
318       // We do not want to warn on some patterns widely used in configuration
319       // scripts.  This requires analyzing next tokens, so do not issue warnings
320       // now, only inform caller.
321       if (ShadowFlag)
322         *ShadowFlag = true;
323     }
324     if (D == MD_ReservedMacro)
325       Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
326   }
327 
328   // Okay, we got a good identifier.
329   return false;
330 }
331 
332 /// Lex and validate a macro name, which occurs after a
333 /// \#define or \#undef.
334 ///
335 /// This sets the token kind to eod and discards the rest of the macro line if
336 /// the macro name is invalid.
337 ///
338 /// \param MacroNameTok Token that is expected to be a macro name.
339 /// \param isDefineUndef Context in which macro is used.
340 /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
341 void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
342                                  bool *ShadowFlag) {
343   // Read the token, don't allow macro expansion on it.
344   LexUnexpandedToken(MacroNameTok);
345 
346   if (MacroNameTok.is(tok::code_completion)) {
347     if (CodeComplete)
348       CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
349     setCodeCompletionReached();
350     LexUnexpandedToken(MacroNameTok);
351   }
352 
353   if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
354     return;
355 
356   // Invalid macro name, read and discard the rest of the line and set the
357   // token kind to tok::eod if necessary.
358   if (MacroNameTok.isNot(tok::eod)) {
359     MacroNameTok.setKind(tok::eod);
360     DiscardUntilEndOfDirective();
361   }
362 }
363 
364 /// Ensure that the next token is a tok::eod token.
365 ///
366 /// If not, emit a diagnostic and consume up until the eod.  If EnableMacros is
367 /// true, then we consider macros that expand to zero tokens as being ok.
368 ///
369 /// Returns the location of the end of the directive.
370 SourceLocation Preprocessor::CheckEndOfDirective(const char *DirType,
371                                                  bool EnableMacros) {
372   Token Tmp;
373   // Lex unexpanded tokens for most directives: macros might expand to zero
374   // tokens, causing us to miss diagnosing invalid lines.  Some directives (like
375   // #line) allow empty macros.
376   if (EnableMacros)
377     Lex(Tmp);
378   else
379     LexUnexpandedToken(Tmp);
380 
381   // There should be no tokens after the directive, but we allow them as an
382   // extension.
383   while (Tmp.is(tok::comment))  // Skip comments in -C mode.
384     LexUnexpandedToken(Tmp);
385 
386   if (Tmp.is(tok::eod))
387     return Tmp.getLocation();
388 
389   // Add a fixit in GNU/C99/C++ mode.  Don't offer a fixit for strict-C89,
390   // or if this is a macro-style preprocessing directive, because it is more
391   // trouble than it is worth to insert /**/ and check that there is no /**/
392   // in the range also.
393   FixItHint Hint;
394   if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
395       !CurTokenLexer)
396     Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
397   Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
398   return DiscardUntilEndOfDirective().getEnd();
399 }
400 
401 Optional<unsigned> Preprocessor::getSkippedRangeForExcludedConditionalBlock(
402     SourceLocation HashLoc) {
403   if (!ExcludedConditionalDirectiveSkipMappings)
404     return None;
405   if (!HashLoc.isFileID())
406     return None;
407 
408   std::pair<FileID, unsigned> HashFileOffset =
409       SourceMgr.getDecomposedLoc(HashLoc);
410   Optional<llvm::MemoryBufferRef> Buf =
411       SourceMgr.getBufferOrNone(HashFileOffset.first);
412   if (!Buf)
413     return None;
414   auto It =
415       ExcludedConditionalDirectiveSkipMappings->find(Buf->getBufferStart());
416   if (It == ExcludedConditionalDirectiveSkipMappings->end())
417     return None;
418 
419   const PreprocessorSkippedRangeMapping &SkippedRanges = *It->getSecond();
420   // Check if the offset of '#' is mapped in the skipped ranges.
421   auto MappingIt = SkippedRanges.find(HashFileOffset.second);
422   if (MappingIt == SkippedRanges.end())
423     return None;
424 
425   unsigned BytesToSkip = MappingIt->getSecond();
426   unsigned CurLexerBufferOffset = CurLexer->getCurrentBufferOffset();
427   assert(CurLexerBufferOffset >= HashFileOffset.second &&
428          "lexer is before the hash?");
429   // Take into account the fact that the lexer has already advanced, so the
430   // number of bytes to skip must be adjusted.
431   unsigned LengthDiff = CurLexerBufferOffset - HashFileOffset.second;
432   assert(BytesToSkip >= LengthDiff && "lexer is after the skipped range?");
433   return BytesToSkip - LengthDiff;
434 }
435 
436 /// SkipExcludedConditionalBlock - We just read a \#if or related directive and
437 /// decided that the subsequent tokens are in the \#if'd out portion of the
438 /// file.  Lex the rest of the file, until we see an \#endif.  If
439 /// FoundNonSkipPortion is true, then we have already emitted code for part of
440 /// this \#if directive, so \#else/\#elif blocks should never be entered.
441 /// If ElseOk is true, then \#else directives are ok, if not, then we have
442 /// already seen one so a \#else directive is a duplicate.  When this returns,
443 /// the caller can lex the first valid token.
444 void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
445                                                 SourceLocation IfTokenLoc,
446                                                 bool FoundNonSkipPortion,
447                                                 bool FoundElse,
448                                                 SourceLocation ElseLoc) {
449   ++NumSkipped;
450   assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
451 
452   if (PreambleConditionalStack.reachedEOFWhileSkipping())
453     PreambleConditionalStack.clearSkipInfo();
454   else
455     CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
456                                      FoundNonSkipPortion, FoundElse);
457 
458   // Enter raw mode to disable identifier lookup (and thus macro expansion),
459   // disabling warnings, etc.
460   CurPPLexer->LexingRawMode = true;
461   Token Tok;
462   if (auto SkipLength =
463           getSkippedRangeForExcludedConditionalBlock(HashTokenLoc)) {
464     // Skip to the next '#endif' / '#else' / '#elif'.
465     CurLexer->skipOver(*SkipLength);
466   }
467   SourceLocation endLoc;
468   while (true) {
469     CurLexer->Lex(Tok);
470 
471     if (Tok.is(tok::code_completion)) {
472       setCodeCompletionReached();
473       if (CodeComplete)
474         CodeComplete->CodeCompleteInConditionalExclusion();
475       continue;
476     }
477 
478     // If this is the end of the buffer, we have an error.
479     if (Tok.is(tok::eof)) {
480       // We don't emit errors for unterminated conditionals here,
481       // Lexer::LexEndOfFile can do that properly.
482       // Just return and let the caller lex after this #include.
483       if (PreambleConditionalStack.isRecording())
484         PreambleConditionalStack.SkipInfo.emplace(
485             HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc);
486       break;
487     }
488 
489     // If this token is not a preprocessor directive, just skip it.
490     if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
491       continue;
492 
493     // We just parsed a # character at the start of a line, so we're in
494     // directive mode.  Tell the lexer this so any newlines we see will be
495     // converted into an EOD token (this terminates the macro).
496     CurPPLexer->ParsingPreprocessorDirective = true;
497     if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
498 
499 
500     // Read the next token, the directive flavor.
501     LexUnexpandedToken(Tok);
502 
503     // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
504     // something bogus), skip it.
505     if (Tok.isNot(tok::raw_identifier)) {
506       CurPPLexer->ParsingPreprocessorDirective = false;
507       // Restore comment saving mode.
508       if (CurLexer) CurLexer->resetExtendedTokenMode();
509       continue;
510     }
511 
512     // If the first letter isn't i or e, it isn't intesting to us.  We know that
513     // this is safe in the face of spelling differences, because there is no way
514     // to spell an i/e in a strange way that is another letter.  Skipping this
515     // allows us to avoid looking up the identifier info for #define/#undef and
516     // other common directives.
517     StringRef RI = Tok.getRawIdentifier();
518 
519     char FirstChar = RI[0];
520     if (FirstChar >= 'a' && FirstChar <= 'z' &&
521         FirstChar != 'i' && FirstChar != 'e') {
522       CurPPLexer->ParsingPreprocessorDirective = false;
523       // Restore comment saving mode.
524       if (CurLexer) CurLexer->resetExtendedTokenMode();
525       continue;
526     }
527 
528     // Get the identifier name without trigraphs or embedded newlines.  Note
529     // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
530     // when skipping.
531     char DirectiveBuf[20];
532     StringRef Directive;
533     if (!Tok.needsCleaning() && RI.size() < 20) {
534       Directive = RI;
535     } else {
536       std::string DirectiveStr = getSpelling(Tok);
537       size_t IdLen = DirectiveStr.size();
538       if (IdLen >= 20) {
539         CurPPLexer->ParsingPreprocessorDirective = false;
540         // Restore comment saving mode.
541         if (CurLexer) CurLexer->resetExtendedTokenMode();
542         continue;
543       }
544       memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
545       Directive = StringRef(DirectiveBuf, IdLen);
546     }
547 
548     if (Directive.startswith("if")) {
549       StringRef Sub = Directive.substr(2);
550       if (Sub.empty() ||   // "if"
551           Sub == "def" ||   // "ifdef"
552           Sub == "ndef") {  // "ifndef"
553         // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
554         // bother parsing the condition.
555         DiscardUntilEndOfDirective();
556         CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
557                                        /*foundnonskip*/false,
558                                        /*foundelse*/false);
559       }
560     } else if (Directive[0] == 'e') {
561       StringRef Sub = Directive.substr(1);
562       if (Sub == "ndif") {  // "endif"
563         PPConditionalInfo CondInfo;
564         CondInfo.WasSkipping = true; // Silence bogus warning.
565         bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
566         (void)InCond;  // Silence warning in no-asserts mode.
567         assert(!InCond && "Can't be skipping if not in a conditional!");
568 
569         // If we popped the outermost skipping block, we're done skipping!
570         if (!CondInfo.WasSkipping) {
571           // Restore the value of LexingRawMode so that trailing comments
572           // are handled correctly, if we've reached the outermost block.
573           CurPPLexer->LexingRawMode = false;
574           endLoc = CheckEndOfDirective("endif");
575           CurPPLexer->LexingRawMode = true;
576           if (Callbacks)
577             Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
578           break;
579         } else {
580           DiscardUntilEndOfDirective();
581         }
582       } else if (Sub == "lse") { // "else".
583         // #else directive in a skipping conditional.  If not in some other
584         // skipping conditional, and if #else hasn't already been seen, enter it
585         // as a non-skipping conditional.
586         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
587 
588         // If this is a #else with a #else before it, report the error.
589         if (CondInfo.FoundElse)
590           Diag(Tok, diag::pp_err_else_after_else) << PED_Elif;
591 
592         // Note that we've seen a #else in this conditional.
593         CondInfo.FoundElse = true;
594 
595         // If the conditional is at the top level, and the #if block wasn't
596         // entered, enter the #else block now.
597         if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
598           CondInfo.FoundNonSkip = true;
599           // Restore the value of LexingRawMode so that trailing comments
600           // are handled correctly.
601           CurPPLexer->LexingRawMode = false;
602           endLoc = CheckEndOfDirective("else");
603           CurPPLexer->LexingRawMode = true;
604           if (Callbacks)
605             Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
606           break;
607         } else {
608           DiscardUntilEndOfDirective();  // C99 6.10p4.
609         }
610       } else if (Sub == "lif") {  // "elif".
611         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
612 
613         // If this is a #elif with a #else before it, report the error.
614         if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
615 
616         // If this is in a skipping block or if we're already handled this #if
617         // block, don't bother parsing the condition.
618         if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
619           DiscardUntilEndOfDirective();
620         } else {
621           // Restore the value of LexingRawMode so that identifiers are
622           // looked up, etc, inside the #elif expression.
623           assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
624           CurPPLexer->LexingRawMode = false;
625           IdentifierInfo *IfNDefMacro = nullptr;
626           DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
627           // Stop if Lexer became invalid after hitting code completion token.
628           if (!CurPPLexer)
629             return;
630           const bool CondValue = DER.Conditional;
631           CurPPLexer->LexingRawMode = true;
632           if (Callbacks) {
633             Callbacks->Elif(
634                 Tok.getLocation(), DER.ExprRange,
635                 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
636                 CondInfo.IfLoc);
637           }
638           // If this condition is true, enter it!
639           if (CondValue) {
640             CondInfo.FoundNonSkip = true;
641             break;
642           }
643         }
644       } else if (Sub == "lifdef" ||  // "elifdef"
645                  Sub == "lifndef") { // "elifndef"
646         bool IsElifDef = Sub == "lifdef";
647         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
648         Token DirectiveToken = Tok;
649 
650         // If this is a #elif with a #else before it, report the error.
651         if (CondInfo.FoundElse)
652           Diag(Tok, diag::pp_err_elif_after_else)
653               << (IsElifDef ? PED_Elifdef : PED_Elifndef);
654 
655         // If this is in a skipping block or if we're already handled this #if
656         // block, don't bother parsing the condition.
657         if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
658           DiscardUntilEndOfDirective();
659         } else {
660           // Restore the value of LexingRawMode so that identifiers are
661           // looked up, etc, inside the #elif[n]def expression.
662           assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
663           CurPPLexer->LexingRawMode = false;
664           Token MacroNameTok;
665           ReadMacroName(MacroNameTok);
666           CurPPLexer->LexingRawMode = true;
667 
668           // If the macro name token is tok::eod, there was an error that was
669           // already reported.
670           if (MacroNameTok.is(tok::eod)) {
671             // Skip code until we get to #endif.  This helps with recovery by
672             // not emitting an error when the #endif is reached.
673             continue;
674           }
675 
676           CheckEndOfDirective(IsElifDef ? "elifdef" : "elifndef");
677 
678           IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
679           auto MD = getMacroDefinition(MII);
680           MacroInfo *MI = MD.getMacroInfo();
681 
682           if (Callbacks) {
683             if (IsElifDef) {
684               Callbacks->Elifdef(DirectiveToken.getLocation(), MacroNameTok,
685                                  MD);
686             } else {
687               Callbacks->Elifndef(DirectiveToken.getLocation(), MacroNameTok,
688                                   MD);
689             }
690           }
691           // If this condition is true, enter it!
692           if (static_cast<bool>(MI) == IsElifDef) {
693             CondInfo.FoundNonSkip = true;
694             break;
695           }
696         }
697       }
698     }
699 
700     CurPPLexer->ParsingPreprocessorDirective = false;
701     // Restore comment saving mode.
702     if (CurLexer) CurLexer->resetExtendedTokenMode();
703   }
704 
705   // Finally, if we are out of the conditional (saw an #endif or ran off the end
706   // of the file, just stop skipping and return to lexing whatever came after
707   // the #if block.
708   CurPPLexer->LexingRawMode = false;
709 
710   // The last skipped range isn't actually skipped yet if it's truncated
711   // by the end of the preamble; we'll resume parsing after the preamble.
712   if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
713     Callbacks->SourceRangeSkipped(
714         SourceRange(HashTokenLoc, endLoc.isValid()
715                                       ? endLoc
716                                       : CurPPLexer->getSourceLocation()),
717         Tok.getLocation());
718 }
719 
720 Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
721   if (!SourceMgr.isInMainFile(Loc)) {
722     // Try to determine the module of the include directive.
723     // FIXME: Look into directly passing the FileEntry from LookupFile instead.
724     FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
725     if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
726       // The include comes from an included file.
727       return HeaderInfo.getModuleMap()
728           .findModuleForHeader(EntryOfIncl)
729           .getModule();
730     }
731   }
732 
733   // This is either in the main file or not in a file at all. It belongs
734   // to the current module, if there is one.
735   return getLangOpts().CurrentModule.empty()
736              ? nullptr
737              : HeaderInfo.lookupModule(getLangOpts().CurrentModule);
738 }
739 
740 const FileEntry *
741 Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
742                                                SourceLocation Loc) {
743   Module *IncM = getModuleForLocation(IncLoc);
744 
745   // Walk up through the include stack, looking through textual headers of M
746   // until we hit a non-textual header that we can #include. (We assume textual
747   // headers of a module with non-textual headers aren't meant to be used to
748   // import entities from the module.)
749   auto &SM = getSourceManager();
750   while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
751     auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
752     auto *FE = SM.getFileEntryForID(ID);
753     if (!FE)
754       break;
755 
756     // We want to find all possible modules that might contain this header, so
757     // search all enclosing directories for module maps and load them.
758     HeaderInfo.hasModuleMap(FE->getName(), /*Root*/ nullptr,
759                             SourceMgr.isInSystemHeader(Loc));
760 
761     bool InPrivateHeader = false;
762     for (auto Header : HeaderInfo.findAllModulesForHeader(FE)) {
763       if (!Header.isAccessibleFrom(IncM)) {
764         // It's in a private header; we can't #include it.
765         // FIXME: If there's a public header in some module that re-exports it,
766         // then we could suggest including that, but it's not clear that's the
767         // expected way to make this entity visible.
768         InPrivateHeader = true;
769         continue;
770       }
771 
772       // We'll suggest including textual headers below if they're
773       // include-guarded.
774       if (Header.getRole() & ModuleMap::TextualHeader)
775         continue;
776 
777       // If we have a module import syntax, we shouldn't include a header to
778       // make a particular module visible. Let the caller know they should
779       // suggest an import instead.
780       if (getLangOpts().ObjC || getLangOpts().CPlusPlusModules ||
781           getLangOpts().ModulesTS)
782         return nullptr;
783 
784       // If this is an accessible, non-textual header of M's top-level module
785       // that transitively includes the given location and makes the
786       // corresponding module visible, this is the thing to #include.
787       return FE;
788     }
789 
790     // FIXME: If we're bailing out due to a private header, we shouldn't suggest
791     // an import either.
792     if (InPrivateHeader)
793       return nullptr;
794 
795     // If the header is includable and has an include guard, assume the
796     // intended way to expose its contents is by #include, not by importing a
797     // module that transitively includes it.
798     if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
799       return FE;
800 
801     Loc = SM.getIncludeLoc(ID);
802   }
803 
804   return nullptr;
805 }
806 
807 Optional<FileEntryRef> Preprocessor::LookupFile(
808     SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
809     const DirectoryLookup *FromDir, const FileEntry *FromFile,
810     const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath,
811     SmallVectorImpl<char> *RelativePath,
812     ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
813     bool *IsFrameworkFound, bool SkipCache) {
814   Module *RequestingModule = getModuleForLocation(FilenameLoc);
815   bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
816 
817   // If the header lookup mechanism may be relative to the current inclusion
818   // stack, record the parent #includes.
819   SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
820       Includers;
821   bool BuildSystemModule = false;
822   if (!FromDir && !FromFile) {
823     FileID FID = getCurrentFileLexer()->getFileID();
824     const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
825 
826     // If there is no file entry associated with this file, it must be the
827     // predefines buffer or the module includes buffer. Any other file is not
828     // lexed with a normal lexer, so it won't be scanned for preprocessor
829     // directives.
830     //
831     // If we have the predefines buffer, resolve #include references (which come
832     // from the -include command line argument) from the current working
833     // directory instead of relative to the main file.
834     //
835     // If we have the module includes buffer, resolve #include references (which
836     // come from header declarations in the module map) relative to the module
837     // map file.
838     if (!FileEnt) {
839       if (FID == SourceMgr.getMainFileID() && MainFileDir) {
840         Includers.push_back(std::make_pair(nullptr, MainFileDir));
841         BuildSystemModule = getCurrentModule()->IsSystem;
842       } else if ((FileEnt =
843                     SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
844         Includers.push_back(std::make_pair(FileEnt, *FileMgr.getDirectory(".")));
845     } else {
846       Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
847     }
848 
849     // MSVC searches the current include stack from top to bottom for
850     // headers included by quoted include directives.
851     // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
852     if (LangOpts.MSVCCompat && !isAngled) {
853       for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
854         if (IsFileLexer(ISEntry))
855           if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
856             Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
857       }
858     }
859   }
860 
861   CurDir = CurDirLookup;
862 
863   if (FromFile) {
864     // We're supposed to start looking from after a particular file. Search
865     // the include path until we find that file or run out of files.
866     const DirectoryLookup *TmpCurDir = CurDir;
867     const DirectoryLookup *TmpFromDir = nullptr;
868     while (Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
869                Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
870                Includers, SearchPath, RelativePath, RequestingModule,
871                SuggestedModule, /*IsMapped=*/nullptr,
872                /*IsFrameworkFound=*/nullptr, SkipCache)) {
873       // Keep looking as if this file did a #include_next.
874       TmpFromDir = TmpCurDir;
875       ++TmpFromDir;
876       if (&FE->getFileEntry() == FromFile) {
877         // Found it.
878         FromDir = TmpFromDir;
879         CurDir = TmpCurDir;
880         break;
881       }
882     }
883   }
884 
885   // Do a standard file entry lookup.
886   Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
887       Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
888       RelativePath, RequestingModule, SuggestedModule, IsMapped,
889       IsFrameworkFound, SkipCache, BuildSystemModule);
890   if (FE) {
891     if (SuggestedModule && !LangOpts.AsmPreprocessor)
892       HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
893           RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
894           Filename, &FE->getFileEntry());
895     return FE;
896   }
897 
898   const FileEntry *CurFileEnt;
899   // Otherwise, see if this is a subframework header.  If so, this is relative
900   // to one of the headers on the #include stack.  Walk the list of the current
901   // headers on the #include stack and pass them to HeaderInfo.
902   if (IsFileLexer()) {
903     if ((CurFileEnt = CurPPLexer->getFileEntry())) {
904       if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
905               Filename, CurFileEnt, SearchPath, RelativePath, RequestingModule,
906               SuggestedModule)) {
907         if (SuggestedModule && !LangOpts.AsmPreprocessor)
908           HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
909               RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
910               Filename, &FE->getFileEntry());
911         return FE;
912       }
913     }
914   }
915 
916   for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
917     if (IsFileLexer(ISEntry)) {
918       if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
919         if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
920                 Filename, CurFileEnt, SearchPath, RelativePath,
921                 RequestingModule, SuggestedModule)) {
922           if (SuggestedModule && !LangOpts.AsmPreprocessor)
923             HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
924                 RequestingModule, RequestingModuleIsModuleInterface,
925                 FilenameLoc, Filename, &FE->getFileEntry());
926           return FE;
927         }
928       }
929     }
930   }
931 
932   // Otherwise, we really couldn't find the file.
933   return None;
934 }
935 
936 //===----------------------------------------------------------------------===//
937 // Preprocessor Directive Handling.
938 //===----------------------------------------------------------------------===//
939 
940 class Preprocessor::ResetMacroExpansionHelper {
941 public:
942   ResetMacroExpansionHelper(Preprocessor *pp)
943     : PP(pp), save(pp->DisableMacroExpansion) {
944     if (pp->MacroExpansionInDirectivesOverride)
945       pp->DisableMacroExpansion = false;
946   }
947 
948   ~ResetMacroExpansionHelper() {
949     PP->DisableMacroExpansion = save;
950   }
951 
952 private:
953   Preprocessor *PP;
954   bool save;
955 };
956 
957 /// Process a directive while looking for the through header or a #pragma
958 /// hdrstop. The following directives are handled:
959 /// #include (to check if it is the through header)
960 /// #define (to warn about macros that don't match the PCH)
961 /// #pragma (to check for pragma hdrstop).
962 /// All other directives are completely discarded.
963 void Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result,
964                                                        SourceLocation HashLoc) {
965   if (const IdentifierInfo *II = Result.getIdentifierInfo()) {
966     if (II->getPPKeywordID() == tok::pp_define) {
967       return HandleDefineDirective(Result,
968                                    /*ImmediatelyAfterHeaderGuard=*/false);
969     }
970     if (SkippingUntilPCHThroughHeader &&
971         II->getPPKeywordID() == tok::pp_include) {
972       return HandleIncludeDirective(HashLoc, Result);
973     }
974     if (SkippingUntilPragmaHdrStop && II->getPPKeywordID() == tok::pp_pragma) {
975       Lex(Result);
976       auto *II = Result.getIdentifierInfo();
977       if (II && II->getName() == "hdrstop")
978         return HandlePragmaHdrstop(Result);
979     }
980   }
981   DiscardUntilEndOfDirective();
982 }
983 
984 /// HandleDirective - This callback is invoked when the lexer sees a # token
985 /// at the start of a line.  This consumes the directive, modifies the
986 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
987 /// read is the correct one.
988 void Preprocessor::HandleDirective(Token &Result) {
989   // FIXME: Traditional: # with whitespace before it not recognized by K&R?
990 
991   // We just parsed a # character at the start of a line, so we're in directive
992   // mode.  Tell the lexer this so any newlines we see will be converted into an
993   // EOD token (which terminates the directive).
994   CurPPLexer->ParsingPreprocessorDirective = true;
995   if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
996 
997   bool ImmediatelyAfterTopLevelIfndef =
998       CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
999   CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
1000 
1001   ++NumDirectives;
1002 
1003   // We are about to read a token.  For the multiple-include optimization FA to
1004   // work, we have to remember if we had read any tokens *before* this
1005   // pp-directive.
1006   bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
1007 
1008   // Save the '#' token in case we need to return it later.
1009   Token SavedHash = Result;
1010 
1011   // Read the next token, the directive flavor.  This isn't expanded due to
1012   // C99 6.10.3p8.
1013   LexUnexpandedToken(Result);
1014 
1015   // C99 6.10.3p11: Is this preprocessor directive in macro invocation?  e.g.:
1016   //   #define A(x) #x
1017   //   A(abc
1018   //     #warning blah
1019   //   def)
1020   // If so, the user is relying on undefined behavior, emit a diagnostic. Do
1021   // not support this for #include-like directives, since that can result in
1022   // terrible diagnostics, and does not work in GCC.
1023   if (InMacroArgs) {
1024     if (IdentifierInfo *II = Result.getIdentifierInfo()) {
1025       switch (II->getPPKeywordID()) {
1026       case tok::pp_include:
1027       case tok::pp_import:
1028       case tok::pp_include_next:
1029       case tok::pp___include_macros:
1030       case tok::pp_pragma:
1031         Diag(Result, diag::err_embedded_directive) << II->getName();
1032         Diag(*ArgMacro, diag::note_macro_expansion_here)
1033             << ArgMacro->getIdentifierInfo();
1034         DiscardUntilEndOfDirective();
1035         return;
1036       default:
1037         break;
1038       }
1039     }
1040     Diag(Result, diag::ext_embedded_directive);
1041   }
1042 
1043   // Temporarily enable macro expansion if set so
1044   // and reset to previous state when returning from this function.
1045   ResetMacroExpansionHelper helper(this);
1046 
1047   if (SkippingUntilPCHThroughHeader || SkippingUntilPragmaHdrStop)
1048     return HandleSkippedDirectiveWhileUsingPCH(Result, SavedHash.getLocation());
1049 
1050   switch (Result.getKind()) {
1051   case tok::eod:
1052     return;   // null directive.
1053   case tok::code_completion:
1054     setCodeCompletionReached();
1055     if (CodeComplete)
1056       CodeComplete->CodeCompleteDirective(
1057                                     CurPPLexer->getConditionalStackDepth() > 0);
1058     return;
1059   case tok::numeric_constant:  // # 7  GNU line marker directive.
1060     if (getLangOpts().AsmPreprocessor)
1061       break;  // # 4 is not a preprocessor directive in .S files.
1062     return HandleDigitDirective(Result);
1063   default:
1064     IdentifierInfo *II = Result.getIdentifierInfo();
1065     if (!II) break; // Not an identifier.
1066 
1067     // Ask what the preprocessor keyword ID is.
1068     switch (II->getPPKeywordID()) {
1069     default: break;
1070     // C99 6.10.1 - Conditional Inclusion.
1071     case tok::pp_if:
1072       return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
1073     case tok::pp_ifdef:
1074       return HandleIfdefDirective(Result, SavedHash, false,
1075                                   true /*not valid for miopt*/);
1076     case tok::pp_ifndef:
1077       return HandleIfdefDirective(Result, SavedHash, true,
1078                                   ReadAnyTokensBeforeDirective);
1079     case tok::pp_elif:
1080     case tok::pp_elifdef:
1081     case tok::pp_elifndef:
1082       return HandleElifFamilyDirective(Result, SavedHash, II->getPPKeywordID());
1083 
1084     case tok::pp_else:
1085       return HandleElseDirective(Result, SavedHash);
1086     case tok::pp_endif:
1087       return HandleEndifDirective(Result);
1088 
1089     // C99 6.10.2 - Source File Inclusion.
1090     case tok::pp_include:
1091       // Handle #include.
1092       return HandleIncludeDirective(SavedHash.getLocation(), Result);
1093     case tok::pp___include_macros:
1094       // Handle -imacros.
1095       return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
1096 
1097     // C99 6.10.3 - Macro Replacement.
1098     case tok::pp_define:
1099       return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
1100     case tok::pp_undef:
1101       return HandleUndefDirective();
1102 
1103     // C99 6.10.4 - Line Control.
1104     case tok::pp_line:
1105       return HandleLineDirective();
1106 
1107     // C99 6.10.5 - Error Directive.
1108     case tok::pp_error:
1109       return HandleUserDiagnosticDirective(Result, false);
1110 
1111     // C99 6.10.6 - Pragma Directive.
1112     case tok::pp_pragma:
1113       return HandlePragmaDirective({PIK_HashPragma, SavedHash.getLocation()});
1114 
1115     // GNU Extensions.
1116     case tok::pp_import:
1117       return HandleImportDirective(SavedHash.getLocation(), Result);
1118     case tok::pp_include_next:
1119       return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
1120 
1121     case tok::pp_warning:
1122       Diag(Result, diag::ext_pp_warning_directive);
1123       return HandleUserDiagnosticDirective(Result, true);
1124     case tok::pp_ident:
1125       return HandleIdentSCCSDirective(Result);
1126     case tok::pp_sccs:
1127       return HandleIdentSCCSDirective(Result);
1128     case tok::pp_assert:
1129       //isExtension = true;  // FIXME: implement #assert
1130       break;
1131     case tok::pp_unassert:
1132       //isExtension = true;  // FIXME: implement #unassert
1133       break;
1134 
1135     case tok::pp___public_macro:
1136       if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
1137         return HandleMacroPublicDirective(Result);
1138       break;
1139 
1140     case tok::pp___private_macro:
1141       if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
1142         return HandleMacroPrivateDirective();
1143       break;
1144     }
1145     break;
1146   }
1147 
1148   // If this is a .S file, treat unknown # directives as non-preprocessor
1149   // directives.  This is important because # may be a comment or introduce
1150   // various pseudo-ops.  Just return the # token and push back the following
1151   // token to be lexed next time.
1152   if (getLangOpts().AsmPreprocessor) {
1153     auto Toks = std::make_unique<Token[]>(2);
1154     // Return the # and the token after it.
1155     Toks[0] = SavedHash;
1156     Toks[1] = Result;
1157 
1158     // If the second token is a hashhash token, then we need to translate it to
1159     // unknown so the token lexer doesn't try to perform token pasting.
1160     if (Result.is(tok::hashhash))
1161       Toks[1].setKind(tok::unknown);
1162 
1163     // Enter this token stream so that we re-lex the tokens.  Make sure to
1164     // enable macro expansion, in case the token after the # is an identifier
1165     // that is expanded.
1166     EnterTokenStream(std::move(Toks), 2, false, /*IsReinject*/false);
1167     return;
1168   }
1169 
1170   // If we reached here, the preprocessing token is not valid!
1171   Diag(Result, diag::err_pp_invalid_directive);
1172 
1173   // Read the rest of the PP line.
1174   DiscardUntilEndOfDirective();
1175 
1176   // Okay, we're done parsing the directive.
1177 }
1178 
1179 /// GetLineValue - Convert a numeric token into an unsigned value, emitting
1180 /// Diagnostic DiagID if it is invalid, and returning the value in Val.
1181 static bool GetLineValue(Token &DigitTok, unsigned &Val,
1182                          unsigned DiagID, Preprocessor &PP,
1183                          bool IsGNULineDirective=false) {
1184   if (DigitTok.isNot(tok::numeric_constant)) {
1185     PP.Diag(DigitTok, DiagID);
1186 
1187     if (DigitTok.isNot(tok::eod))
1188       PP.DiscardUntilEndOfDirective();
1189     return true;
1190   }
1191 
1192   SmallString<64> IntegerBuffer;
1193   IntegerBuffer.resize(DigitTok.getLength());
1194   const char *DigitTokBegin = &IntegerBuffer[0];
1195   bool Invalid = false;
1196   unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1197   if (Invalid)
1198     return true;
1199 
1200   // Verify that we have a simple digit-sequence, and compute the value.  This
1201   // is always a simple digit string computed in decimal, so we do this manually
1202   // here.
1203   Val = 0;
1204   for (unsigned i = 0; i != ActualLength; ++i) {
1205     // C++1y [lex.fcon]p1:
1206     //   Optional separating single quotes in a digit-sequence are ignored
1207     if (DigitTokBegin[i] == '\'')
1208       continue;
1209 
1210     if (!isDigit(DigitTokBegin[i])) {
1211       PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
1212               diag::err_pp_line_digit_sequence) << IsGNULineDirective;
1213       PP.DiscardUntilEndOfDirective();
1214       return true;
1215     }
1216 
1217     unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1218     if (NextVal < Val) { // overflow.
1219       PP.Diag(DigitTok, DiagID);
1220       PP.DiscardUntilEndOfDirective();
1221       return true;
1222     }
1223     Val = NextVal;
1224   }
1225 
1226   if (DigitTokBegin[0] == '0' && Val)
1227     PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1228       << IsGNULineDirective;
1229 
1230   return false;
1231 }
1232 
1233 /// Handle a \#line directive: C99 6.10.4.
1234 ///
1235 /// The two acceptable forms are:
1236 /// \verbatim
1237 ///   # line digit-sequence
1238 ///   # line digit-sequence "s-char-sequence"
1239 /// \endverbatim
1240 void Preprocessor::HandleLineDirective() {
1241   // Read the line # and string argument.  Per C99 6.10.4p5, these tokens are
1242   // expanded.
1243   Token DigitTok;
1244   Lex(DigitTok);
1245 
1246   // Validate the number and convert it to an unsigned.
1247   unsigned LineNo;
1248   if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
1249     return;
1250 
1251   if (LineNo == 0)
1252     Diag(DigitTok, diag::ext_pp_line_zero);
1253 
1254   // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1255   // number greater than 2147483647".  C90 requires that the line # be <= 32767.
1256   unsigned LineLimit = 32768U;
1257   if (LangOpts.C99 || LangOpts.CPlusPlus11)
1258     LineLimit = 2147483648U;
1259   if (LineNo >= LineLimit)
1260     Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
1261   else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
1262     Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
1263 
1264   int FilenameID = -1;
1265   Token StrTok;
1266   Lex(StrTok);
1267 
1268   // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
1269   // string followed by eod.
1270   if (StrTok.is(tok::eod))
1271     ; // ok
1272   else if (StrTok.isNot(tok::string_literal)) {
1273     Diag(StrTok, diag::err_pp_line_invalid_filename);
1274     DiscardUntilEndOfDirective();
1275     return;
1276   } else if (StrTok.hasUDSuffix()) {
1277     Diag(StrTok, diag::err_invalid_string_udl);
1278     DiscardUntilEndOfDirective();
1279     return;
1280   } else {
1281     // Parse and validate the string, converting it into a unique ID.
1282     StringLiteralParser Literal(StrTok, *this);
1283     assert(Literal.isAscii() && "Didn't allow wide strings in");
1284     if (Literal.hadError) {
1285       DiscardUntilEndOfDirective();
1286       return;
1287     }
1288     if (Literal.Pascal) {
1289       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1290       DiscardUntilEndOfDirective();
1291       return;
1292     }
1293     FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1294 
1295     // Verify that there is nothing after the string, other than EOD.  Because
1296     // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1297     CheckEndOfDirective("line", true);
1298   }
1299 
1300   // Take the file kind of the file containing the #line directive. #line
1301   // directives are often used for generated sources from the same codebase, so
1302   // the new file should generally be classified the same way as the current
1303   // file. This is visible in GCC's pre-processed output, which rewrites #line
1304   // to GNU line markers.
1305   SrcMgr::CharacteristicKind FileKind =
1306       SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1307 
1308   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1309                         false, FileKind);
1310 
1311   if (Callbacks)
1312     Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1313                            PPCallbacks::RenameFile, FileKind);
1314 }
1315 
1316 /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1317 /// marker directive.
1318 static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1319                                 SrcMgr::CharacteristicKind &FileKind,
1320                                 Preprocessor &PP) {
1321   unsigned FlagVal;
1322   Token FlagTok;
1323   PP.Lex(FlagTok);
1324   if (FlagTok.is(tok::eod)) return false;
1325   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1326     return true;
1327 
1328   if (FlagVal == 1) {
1329     IsFileEntry = true;
1330 
1331     PP.Lex(FlagTok);
1332     if (FlagTok.is(tok::eod)) return false;
1333     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1334       return true;
1335   } else if (FlagVal == 2) {
1336     IsFileExit = true;
1337 
1338     SourceManager &SM = PP.getSourceManager();
1339     // If we are leaving the current presumed file, check to make sure the
1340     // presumed include stack isn't empty!
1341     FileID CurFileID =
1342       SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
1343     PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
1344     if (PLoc.isInvalid())
1345       return true;
1346 
1347     // If there is no include loc (main file) or if the include loc is in a
1348     // different physical file, then we aren't in a "1" line marker flag region.
1349     SourceLocation IncLoc = PLoc.getIncludeLoc();
1350     if (IncLoc.isInvalid() ||
1351         SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
1352       PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1353       PP.DiscardUntilEndOfDirective();
1354       return true;
1355     }
1356 
1357     PP.Lex(FlagTok);
1358     if (FlagTok.is(tok::eod)) return false;
1359     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1360       return true;
1361   }
1362 
1363   // We must have 3 if there are still flags.
1364   if (FlagVal != 3) {
1365     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1366     PP.DiscardUntilEndOfDirective();
1367     return true;
1368   }
1369 
1370   FileKind = SrcMgr::C_System;
1371 
1372   PP.Lex(FlagTok);
1373   if (FlagTok.is(tok::eod)) return false;
1374   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1375     return true;
1376 
1377   // We must have 4 if there is yet another flag.
1378   if (FlagVal != 4) {
1379     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1380     PP.DiscardUntilEndOfDirective();
1381     return true;
1382   }
1383 
1384   FileKind = SrcMgr::C_ExternCSystem;
1385 
1386   PP.Lex(FlagTok);
1387   if (FlagTok.is(tok::eod)) return false;
1388 
1389   // There are no more valid flags here.
1390   PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1391   PP.DiscardUntilEndOfDirective();
1392   return true;
1393 }
1394 
1395 /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1396 /// one of the following forms:
1397 ///
1398 ///     # 42
1399 ///     # 42 "file" ('1' | '2')?
1400 ///     # 42 "file" ('1' | '2')? '3' '4'?
1401 ///
1402 void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1403   // Validate the number and convert it to an unsigned.  GNU does not have a
1404   // line # limit other than it fit in 32-bits.
1405   unsigned LineNo;
1406   if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
1407                    *this, true))
1408     return;
1409 
1410   Token StrTok;
1411   Lex(StrTok);
1412 
1413   bool IsFileEntry = false, IsFileExit = false;
1414   int FilenameID = -1;
1415   SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1416 
1417   // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
1418   // string followed by eod.
1419   if (StrTok.is(tok::eod)) {
1420     // Treat this like "#line NN", which doesn't change file characteristics.
1421     FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1422   } else if (StrTok.isNot(tok::string_literal)) {
1423     Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1424     DiscardUntilEndOfDirective();
1425     return;
1426   } else if (StrTok.hasUDSuffix()) {
1427     Diag(StrTok, diag::err_invalid_string_udl);
1428     DiscardUntilEndOfDirective();
1429     return;
1430   } else {
1431     // Parse and validate the string, converting it into a unique ID.
1432     StringLiteralParser Literal(StrTok, *this);
1433     assert(Literal.isAscii() && "Didn't allow wide strings in");
1434     if (Literal.hadError) {
1435       DiscardUntilEndOfDirective();
1436       return;
1437     }
1438     if (Literal.Pascal) {
1439       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1440       DiscardUntilEndOfDirective();
1441       return;
1442     }
1443     FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1444 
1445     // If a filename was present, read any flags that are present.
1446     if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
1447       return;
1448   }
1449 
1450   // Create a line note with this information.
1451   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1452                         IsFileExit, FileKind);
1453 
1454   // If the preprocessor has callbacks installed, notify them of the #line
1455   // change.  This is used so that the line marker comes out in -E mode for
1456   // example.
1457   if (Callbacks) {
1458     PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1459     if (IsFileEntry)
1460       Reason = PPCallbacks::EnterFile;
1461     else if (IsFileExit)
1462       Reason = PPCallbacks::ExitFile;
1463 
1464     Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
1465   }
1466 }
1467 
1468 /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1469 ///
1470 void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
1471                                                  bool isWarning) {
1472   // Read the rest of the line raw.  We do this because we don't want macros
1473   // to be expanded and we don't require that the tokens be valid preprocessing
1474   // tokens.  For example, this is allowed: "#warning `   'foo".  GCC does
1475   // collapse multiple consecutive white space between tokens, but this isn't
1476   // specified by the standard.
1477   SmallString<128> Message;
1478   CurLexer->ReadToEndOfLine(&Message);
1479 
1480   // Find the first non-whitespace character, so that we can make the
1481   // diagnostic more succinct.
1482   StringRef Msg = StringRef(Message).ltrim(' ');
1483 
1484   if (isWarning)
1485     Diag(Tok, diag::pp_hash_warning) << Msg;
1486   else
1487     Diag(Tok, diag::err_pp_hash_error) << Msg;
1488 }
1489 
1490 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1491 ///
1492 void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1493   // Yes, this directive is an extension.
1494   Diag(Tok, diag::ext_pp_ident_directive);
1495 
1496   // Read the string argument.
1497   Token StrTok;
1498   Lex(StrTok);
1499 
1500   // If the token kind isn't a string, it's a malformed directive.
1501   if (StrTok.isNot(tok::string_literal) &&
1502       StrTok.isNot(tok::wide_string_literal)) {
1503     Diag(StrTok, diag::err_pp_malformed_ident);
1504     if (StrTok.isNot(tok::eod))
1505       DiscardUntilEndOfDirective();
1506     return;
1507   }
1508 
1509   if (StrTok.hasUDSuffix()) {
1510     Diag(StrTok, diag::err_invalid_string_udl);
1511     DiscardUntilEndOfDirective();
1512     return;
1513   }
1514 
1515   // Verify that there is nothing after the string, other than EOD.
1516   CheckEndOfDirective("ident");
1517 
1518   if (Callbacks) {
1519     bool Invalid = false;
1520     std::string Str = getSpelling(StrTok, &Invalid);
1521     if (!Invalid)
1522       Callbacks->Ident(Tok.getLocation(), Str);
1523   }
1524 }
1525 
1526 /// Handle a #public directive.
1527 void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
1528   Token MacroNameTok;
1529   ReadMacroName(MacroNameTok, MU_Undef);
1530 
1531   // Error reading macro name?  If so, diagnostic already issued.
1532   if (MacroNameTok.is(tok::eod))
1533     return;
1534 
1535   // Check to see if this is the last token on the #__public_macro line.
1536   CheckEndOfDirective("__public_macro");
1537 
1538   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1539   // Okay, we finally have a valid identifier to undef.
1540   MacroDirective *MD = getLocalMacroDirective(II);
1541 
1542   // If the macro is not defined, this is an error.
1543   if (!MD) {
1544     Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1545     return;
1546   }
1547 
1548   // Note that this macro has now been exported.
1549   appendMacroDirective(II, AllocateVisibilityMacroDirective(
1550                                 MacroNameTok.getLocation(), /*isPublic=*/true));
1551 }
1552 
1553 /// Handle a #private directive.
1554 void Preprocessor::HandleMacroPrivateDirective() {
1555   Token MacroNameTok;
1556   ReadMacroName(MacroNameTok, MU_Undef);
1557 
1558   // Error reading macro name?  If so, diagnostic already issued.
1559   if (MacroNameTok.is(tok::eod))
1560     return;
1561 
1562   // Check to see if this is the last token on the #__private_macro line.
1563   CheckEndOfDirective("__private_macro");
1564 
1565   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1566   // Okay, we finally have a valid identifier to undef.
1567   MacroDirective *MD = getLocalMacroDirective(II);
1568 
1569   // If the macro is not defined, this is an error.
1570   if (!MD) {
1571     Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1572     return;
1573   }
1574 
1575   // Note that this macro has now been marked private.
1576   appendMacroDirective(II, AllocateVisibilityMacroDirective(
1577                                MacroNameTok.getLocation(), /*isPublic=*/false));
1578 }
1579 
1580 //===----------------------------------------------------------------------===//
1581 // Preprocessor Include Directive Handling.
1582 //===----------------------------------------------------------------------===//
1583 
1584 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1585 /// checked and spelled filename, e.g. as an operand of \#include. This returns
1586 /// true if the input filename was in <>'s or false if it were in ""'s.  The
1587 /// caller is expected to provide a buffer that is large enough to hold the
1588 /// spelling of the filename, but is also expected to handle the case when
1589 /// this method decides to use a different buffer.
1590 bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
1591                                               StringRef &Buffer) {
1592   // Get the text form of the filename.
1593   assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1594 
1595   // FIXME: Consider warning on some of the cases described in C11 6.4.7/3 and
1596   // C++20 [lex.header]/2:
1597   //
1598   // If `"`, `'`, `\`, `/*`, or `//` appears in a header-name, then
1599   //   in C: behavior is undefined
1600   //   in C++: program is conditionally-supported with implementation-defined
1601   //           semantics
1602 
1603   // Make sure the filename is <x> or "x".
1604   bool isAngled;
1605   if (Buffer[0] == '<') {
1606     if (Buffer.back() != '>') {
1607       Diag(Loc, diag::err_pp_expects_filename);
1608       Buffer = StringRef();
1609       return true;
1610     }
1611     isAngled = true;
1612   } else if (Buffer[0] == '"') {
1613     if (Buffer.back() != '"') {
1614       Diag(Loc, diag::err_pp_expects_filename);
1615       Buffer = StringRef();
1616       return true;
1617     }
1618     isAngled = false;
1619   } else {
1620     Diag(Loc, diag::err_pp_expects_filename);
1621     Buffer = StringRef();
1622     return true;
1623   }
1624 
1625   // Diagnose #include "" as invalid.
1626   if (Buffer.size() <= 2) {
1627     Diag(Loc, diag::err_pp_empty_filename);
1628     Buffer = StringRef();
1629     return true;
1630   }
1631 
1632   // Skip the brackets.
1633   Buffer = Buffer.substr(1, Buffer.size()-2);
1634   return isAngled;
1635 }
1636 
1637 /// Push a token onto the token stream containing an annotation.
1638 void Preprocessor::EnterAnnotationToken(SourceRange Range,
1639                                         tok::TokenKind Kind,
1640                                         void *AnnotationVal) {
1641   // FIXME: Produce this as the current token directly, rather than
1642   // allocating a new token for it.
1643   auto Tok = std::make_unique<Token[]>(1);
1644   Tok[0].startToken();
1645   Tok[0].setKind(Kind);
1646   Tok[0].setLocation(Range.getBegin());
1647   Tok[0].setAnnotationEndLoc(Range.getEnd());
1648   Tok[0].setAnnotationValue(AnnotationVal);
1649   EnterTokenStream(std::move(Tok), 1, true, /*IsReinject*/ false);
1650 }
1651 
1652 /// Produce a diagnostic informing the user that a #include or similar
1653 /// was implicitly treated as a module import.
1654 static void diagnoseAutoModuleImport(
1655     Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1656     ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1657     SourceLocation PathEnd) {
1658   StringRef ImportKeyword;
1659   if (PP.getLangOpts().ObjC)
1660     ImportKeyword = "@import";
1661   else if (PP.getLangOpts().ModulesTS || PP.getLangOpts().CPlusPlusModules)
1662     ImportKeyword = "import";
1663   else
1664     return; // no import syntax available
1665 
1666   SmallString<128> PathString;
1667   for (size_t I = 0, N = Path.size(); I != N; ++I) {
1668     if (I)
1669       PathString += '.';
1670     PathString += Path[I].first->getName();
1671   }
1672   int IncludeKind = 0;
1673 
1674   switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1675   case tok::pp_include:
1676     IncludeKind = 0;
1677     break;
1678 
1679   case tok::pp_import:
1680     IncludeKind = 1;
1681     break;
1682 
1683   case tok::pp_include_next:
1684     IncludeKind = 2;
1685     break;
1686 
1687   case tok::pp___include_macros:
1688     IncludeKind = 3;
1689     break;
1690 
1691   default:
1692     llvm_unreachable("unknown include directive kind");
1693   }
1694 
1695   CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1696                                /*IsTokenRange=*/false);
1697   PP.Diag(HashLoc, diag::warn_auto_module_import)
1698       << IncludeKind << PathString
1699       << FixItHint::CreateReplacement(
1700              ReplaceRange, (ImportKeyword + " " + PathString + ";").str());
1701 }
1702 
1703 // Given a vector of path components and a string containing the real
1704 // path to the file, build a properly-cased replacement in the vector,
1705 // and return true if the replacement should be suggested.
1706 static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1707                             StringRef RealPathName) {
1708   auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1709   auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1710   int Cnt = 0;
1711   bool SuggestReplacement = false;
1712   // Below is a best-effort to handle ".." in paths. It is admittedly
1713   // not 100% correct in the presence of symlinks.
1714   for (auto &Component : llvm::reverse(Components)) {
1715     if ("." == Component) {
1716     } else if (".." == Component) {
1717       ++Cnt;
1718     } else if (Cnt) {
1719       --Cnt;
1720     } else if (RealPathComponentIter != RealPathComponentEnd) {
1721       if (Component != *RealPathComponentIter) {
1722         // If these path components differ by more than just case, then we
1723         // may be looking at symlinked paths. Bail on this diagnostic to avoid
1724         // noisy false positives.
1725         SuggestReplacement = RealPathComponentIter->equals_lower(Component);
1726         if (!SuggestReplacement)
1727           break;
1728         Component = *RealPathComponentIter;
1729       }
1730       ++RealPathComponentIter;
1731     }
1732   }
1733   return SuggestReplacement;
1734 }
1735 
1736 bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1737                                           const TargetInfo &TargetInfo,
1738                                           DiagnosticsEngine &Diags, Module *M) {
1739   Module::Requirement Requirement;
1740   Module::UnresolvedHeaderDirective MissingHeader;
1741   Module *ShadowingModule = nullptr;
1742   if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
1743                      ShadowingModule))
1744     return false;
1745 
1746   if (MissingHeader.FileNameLoc.isValid()) {
1747     Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1748         << MissingHeader.IsUmbrella << MissingHeader.FileName;
1749   } else if (ShadowingModule) {
1750     Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
1751     Diags.Report(ShadowingModule->DefinitionLoc,
1752                  diag::note_previous_definition);
1753   } else {
1754     // FIXME: Track the location at which the requirement was specified, and
1755     // use it here.
1756     Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1757         << M->getFullModuleName() << Requirement.second << Requirement.first;
1758   }
1759   return true;
1760 }
1761 
1762 /// HandleIncludeDirective - The "\#include" tokens have just been read, read
1763 /// the file to be included from the lexer, then include it!  This is a common
1764 /// routine with functionality shared between \#include, \#include_next and
1765 /// \#import.  LookupFrom is set when this is a \#include_next directive, it
1766 /// specifies the file to start searching from.
1767 void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1768                                           Token &IncludeTok,
1769                                           const DirectoryLookup *LookupFrom,
1770                                           const FileEntry *LookupFromFile) {
1771   Token FilenameTok;
1772   if (LexHeaderName(FilenameTok))
1773     return;
1774 
1775   if (FilenameTok.isNot(tok::header_name)) {
1776     Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1777     if (FilenameTok.isNot(tok::eod))
1778       DiscardUntilEndOfDirective();
1779     return;
1780   }
1781 
1782   // Verify that there is nothing after the filename, other than EOD.  Note
1783   // that we allow macros that expand to nothing after the filename, because
1784   // this falls into the category of "#include pp-tokens new-line" specified
1785   // in C99 6.10.2p4.
1786   SourceLocation EndLoc =
1787       CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1788 
1789   auto Action = HandleHeaderIncludeOrImport(HashLoc, IncludeTok, FilenameTok,
1790                                             EndLoc, LookupFrom, LookupFromFile);
1791   switch (Action.Kind) {
1792   case ImportAction::None:
1793   case ImportAction::SkippedModuleImport:
1794     break;
1795   case ImportAction::ModuleBegin:
1796     EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1797                          tok::annot_module_begin, Action.ModuleForHeader);
1798     break;
1799   case ImportAction::ModuleImport:
1800     EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1801                          tok::annot_module_include, Action.ModuleForHeader);
1802     break;
1803   case ImportAction::Failure:
1804     assert(TheModuleLoader.HadFatalFailure &&
1805            "This should be an early exit only to a fatal error");
1806     TheModuleLoader.HadFatalFailure = true;
1807     IncludeTok.setKind(tok::eof);
1808     CurLexer->cutOffLexing();
1809     return;
1810   }
1811 }
1812 
1813 Optional<FileEntryRef> Preprocessor::LookupHeaderIncludeOrImport(
1814     const DirectoryLookup *&CurDir, StringRef& Filename,
1815     SourceLocation FilenameLoc, CharSourceRange FilenameRange,
1816     const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
1817     bool &IsMapped, const DirectoryLookup *LookupFrom,
1818     const FileEntry *LookupFromFile, StringRef& LookupFilename,
1819     SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
1820     ModuleMap::KnownHeader &SuggestedModule, bool isAngled) {
1821   Optional<FileEntryRef> File = LookupFile(
1822       FilenameLoc, LookupFilename,
1823       isAngled, LookupFrom, LookupFromFile, CurDir,
1824       Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1825       &SuggestedModule, &IsMapped, &IsFrameworkFound);
1826   if (File)
1827     return File;
1828 
1829   if (Callbacks) {
1830     // Give the clients a chance to recover.
1831     SmallString<128> RecoveryPath;
1832     if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
1833       if (auto DE = FileMgr.getOptionalDirectoryRef(RecoveryPath)) {
1834         // Add the recovery path to the list of search paths.
1835         DirectoryLookup DL(*DE, SrcMgr::C_User, false);
1836         HeaderInfo.AddSearchPath(DL, isAngled);
1837 
1838         // Try the lookup again, skipping the cache.
1839         Optional<FileEntryRef> File = LookupFile(
1840             FilenameLoc,
1841             LookupFilename, isAngled,
1842             LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
1843             &SuggestedModule, &IsMapped, /*IsFrameworkFound=*/nullptr,
1844             /*SkipCache*/ true);
1845         if (File)
1846           return File;
1847       }
1848     }
1849   }
1850 
1851   if (SuppressIncludeNotFoundError)
1852     return None;
1853 
1854   // If the file could not be located and it was included via angle
1855   // brackets, we can attempt a lookup as though it were a quoted path to
1856   // provide the user with a possible fixit.
1857   if (isAngled) {
1858     Optional<FileEntryRef> File = LookupFile(
1859         FilenameLoc, LookupFilename,
1860         false, LookupFrom, LookupFromFile, CurDir,
1861         Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1862         &SuggestedModule, &IsMapped,
1863         /*IsFrameworkFound=*/nullptr);
1864     if (File) {
1865       Diag(FilenameTok, diag::err_pp_file_not_found_angled_include_not_fatal)
1866           << Filename << IsImportDecl
1867           << FixItHint::CreateReplacement(FilenameRange,
1868                                           "\"" + Filename.str() + "\"");
1869       return File;
1870     }
1871   }
1872 
1873   // Check for likely typos due to leading or trailing non-isAlphanumeric
1874   // characters
1875   StringRef OriginalFilename = Filename;
1876   if (LangOpts.SpellChecking) {
1877     // A heuristic to correct a typo file name by removing leading and
1878     // trailing non-isAlphanumeric characters.
1879     auto CorrectTypoFilename = [](llvm::StringRef Filename) {
1880       Filename = Filename.drop_until(isAlphanumeric);
1881       while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
1882         Filename = Filename.drop_back();
1883       }
1884       return Filename;
1885     };
1886     StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
1887     StringRef TypoCorrectionLookupName = CorrectTypoFilename(LookupFilename);
1888 
1889     Optional<FileEntryRef> File = LookupFile(
1890         FilenameLoc, TypoCorrectionLookupName, isAngled, LookupFrom, LookupFromFile,
1891         CurDir, Callbacks ? &SearchPath : nullptr,
1892         Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
1893         /*IsFrameworkFound=*/nullptr);
1894     if (File) {
1895       auto Hint =
1896           isAngled ? FixItHint::CreateReplacement(
1897                          FilenameRange, "<" + TypoCorrectionName.str() + ">")
1898                    : FixItHint::CreateReplacement(
1899                          FilenameRange, "\"" + TypoCorrectionName.str() + "\"");
1900       Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
1901           << OriginalFilename << TypoCorrectionName << Hint;
1902       // We found the file, so set the Filename to the name after typo
1903       // correction.
1904       Filename = TypoCorrectionName;
1905       LookupFilename = TypoCorrectionLookupName;
1906       return File;
1907     }
1908   }
1909 
1910   // If the file is still not found, just go with the vanilla diagnostic
1911   assert(!File.hasValue() && "expected missing file");
1912   Diag(FilenameTok, diag::err_pp_file_not_found)
1913       << OriginalFilename << FilenameRange;
1914   if (IsFrameworkFound) {
1915     size_t SlashPos = OriginalFilename.find('/');
1916     assert(SlashPos != StringRef::npos &&
1917            "Include with framework name should have '/' in the filename");
1918     StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
1919     FrameworkCacheEntry &CacheEntry =
1920         HeaderInfo.LookupFrameworkCache(FrameworkName);
1921     assert(CacheEntry.Directory && "Found framework should be in cache");
1922     Diag(FilenameTok, diag::note_pp_framework_without_header)
1923         << OriginalFilename.substr(SlashPos + 1) << FrameworkName
1924         << CacheEntry.Directory->getName();
1925   }
1926 
1927   return None;
1928 }
1929 
1930 /// Handle either a #include-like directive or an import declaration that names
1931 /// a header file.
1932 ///
1933 /// \param HashLoc The location of the '#' token for an include, or
1934 ///        SourceLocation() for an import declaration.
1935 /// \param IncludeTok The include / include_next / import token.
1936 /// \param FilenameTok The header-name token.
1937 /// \param EndLoc The location at which any imported macros become visible.
1938 /// \param LookupFrom For #include_next, the starting directory for the
1939 ///        directory lookup.
1940 /// \param LookupFromFile For #include_next, the starting file for the directory
1941 ///        lookup.
1942 Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
1943     SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok,
1944     SourceLocation EndLoc, const DirectoryLookup *LookupFrom,
1945     const FileEntry *LookupFromFile) {
1946   SmallString<128> FilenameBuffer;
1947   StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
1948   SourceLocation CharEnd = FilenameTok.getEndLoc();
1949 
1950   CharSourceRange FilenameRange
1951     = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
1952   StringRef OriginalFilename = Filename;
1953   bool isAngled =
1954     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
1955 
1956   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1957   // error.
1958   if (Filename.empty())
1959     return {ImportAction::None};
1960 
1961   bool IsImportDecl = HashLoc.isInvalid();
1962   SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc;
1963 
1964   // Complain about attempts to #include files in an audit pragma.
1965   if (PragmaARCCFCodeAuditedInfo.second.isValid()) {
1966     Diag(StartLoc, diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl;
1967     Diag(PragmaARCCFCodeAuditedInfo.second, diag::note_pragma_entered_here);
1968 
1969     // Immediately leave the pragma.
1970     PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
1971   }
1972 
1973   // Complain about attempts to #include files in an assume-nonnull pragma.
1974   if (PragmaAssumeNonNullLoc.isValid()) {
1975     Diag(StartLoc, diag::err_pp_include_in_assume_nonnull) << IsImportDecl;
1976     Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
1977 
1978     // Immediately leave the pragma.
1979     PragmaAssumeNonNullLoc = SourceLocation();
1980   }
1981 
1982   if (HeaderInfo.HasIncludeAliasMap()) {
1983     // Map the filename with the brackets still attached.  If the name doesn't
1984     // map to anything, fall back on the filename we've already gotten the
1985     // spelling for.
1986     StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
1987     if (!NewName.empty())
1988       Filename = NewName;
1989   }
1990 
1991   // Search include directories.
1992   bool IsMapped = false;
1993   bool IsFrameworkFound = false;
1994   const DirectoryLookup *CurDir;
1995   SmallString<1024> SearchPath;
1996   SmallString<1024> RelativePath;
1997   // We get the raw path only if we have 'Callbacks' to which we later pass
1998   // the path.
1999   ModuleMap::KnownHeader SuggestedModule;
2000   SourceLocation FilenameLoc = FilenameTok.getLocation();
2001   StringRef LookupFilename = Filename;
2002 
2003 #ifdef _WIN32
2004   llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::windows;
2005 #else
2006   // Normalize slashes when compiling with -fms-extensions on non-Windows. This
2007   // is unnecessary on Windows since the filesystem there handles backslashes.
2008   SmallString<128> NormalizedPath;
2009   llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::posix;
2010   if (LangOpts.MicrosoftExt) {
2011     NormalizedPath = Filename.str();
2012     llvm::sys::path::native(NormalizedPath);
2013     LookupFilename = NormalizedPath;
2014     BackslashStyle = llvm::sys::path::Style::windows;
2015   }
2016 #endif
2017 
2018   Optional<FileEntryRef> File = LookupHeaderIncludeOrImport(
2019       CurDir, Filename, FilenameLoc, FilenameRange, FilenameTok,
2020       IsFrameworkFound, IsImportDecl, IsMapped, LookupFrom, LookupFromFile,
2021       LookupFilename, RelativePath, SearchPath, SuggestedModule, isAngled);
2022 
2023   if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
2024     if (File && isPCHThroughHeader(&File->getFileEntry()))
2025       SkippingUntilPCHThroughHeader = false;
2026     return {ImportAction::None};
2027   }
2028 
2029   // Should we enter the source file? Set to Skip if either the source file is
2030   // known to have no effect beyond its effect on module visibility -- that is,
2031   // if it's got an include guard that is already defined, set to Import if it
2032   // is a modular header we've already built and should import.
2033   enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter;
2034 
2035   if (PPOpts->SingleFileParseMode)
2036     Action = IncludeLimitReached;
2037 
2038   // If we've reached the max allowed include depth, it is usually due to an
2039   // include cycle. Don't enter already processed files again as it can lead to
2040   // reaching the max allowed include depth again.
2041   if (Action == Enter && HasReachedMaxIncludeDepth && File &&
2042       HeaderInfo.getFileInfo(&File->getFileEntry()).NumIncludes)
2043     Action = IncludeLimitReached;
2044 
2045   // Determine whether we should try to import the module for this #include, if
2046   // there is one. Don't do so if precompiled module support is disabled or we
2047   // are processing this module textually (because we're building the module).
2048   if (Action == Enter && File && SuggestedModule && getLangOpts().Modules &&
2049       !isForModuleBuilding(SuggestedModule.getModule(),
2050                            getLangOpts().CurrentModule,
2051                            getLangOpts().ModuleName)) {
2052     // If this include corresponds to a module but that module is
2053     // unavailable, diagnose the situation and bail out.
2054     // FIXME: Remove this; loadModule does the same check (but produces
2055     // slightly worse diagnostics).
2056     if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
2057                                SuggestedModule.getModule())) {
2058       Diag(FilenameTok.getLocation(),
2059            diag::note_implicit_top_level_module_import_here)
2060           << SuggestedModule.getModule()->getTopLevelModuleName();
2061       return {ImportAction::None};
2062     }
2063 
2064     // Compute the module access path corresponding to this module.
2065     // FIXME: Should we have a second loadModule() overload to avoid this
2066     // extra lookup step?
2067     SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2068     for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
2069       Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
2070                                     FilenameTok.getLocation()));
2071     std::reverse(Path.begin(), Path.end());
2072 
2073     // Warn that we're replacing the include/import with a module import.
2074     if (!IsImportDecl)
2075       diagnoseAutoModuleImport(*this, StartLoc, IncludeTok, Path, CharEnd);
2076 
2077     // Load the module to import its macros. We'll make the declarations
2078     // visible when the parser gets here.
2079     // FIXME: Pass SuggestedModule in here rather than converting it to a path
2080     // and making the module loader convert it back again.
2081     ModuleLoadResult Imported = TheModuleLoader.loadModule(
2082         IncludeTok.getLocation(), Path, Module::Hidden,
2083         /*IsInclusionDirective=*/true);
2084     assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
2085            "the imported module is different than the suggested one");
2086 
2087     if (Imported) {
2088       Action = Import;
2089     } else if (Imported.isMissingExpected()) {
2090       // We failed to find a submodule that we assumed would exist (because it
2091       // was in the directory of an umbrella header, for instance), but no
2092       // actual module containing it exists (because the umbrella header is
2093       // incomplete).  Treat this as a textual inclusion.
2094       SuggestedModule = ModuleMap::KnownHeader();
2095     } else if (Imported.isConfigMismatch()) {
2096       // On a configuration mismatch, enter the header textually. We still know
2097       // that it's part of the corresponding module.
2098     } else {
2099       // We hit an error processing the import. Bail out.
2100       if (hadModuleLoaderFatalFailure()) {
2101         // With a fatal failure in the module loader, we abort parsing.
2102         Token &Result = IncludeTok;
2103         assert(CurLexer && "#include but no current lexer set!");
2104         Result.startToken();
2105         CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
2106         CurLexer->cutOffLexing();
2107       }
2108       return {ImportAction::None};
2109     }
2110   }
2111 
2112   // The #included file will be considered to be a system header if either it is
2113   // in a system include directory, or if the #includer is a system include
2114   // header.
2115   SrcMgr::CharacteristicKind FileCharacter =
2116       SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
2117   if (File)
2118     FileCharacter = std::max(HeaderInfo.getFileDirFlavor(&File->getFileEntry()),
2119                              FileCharacter);
2120 
2121   // If this is a '#import' or an import-declaration, don't re-enter the file.
2122   //
2123   // FIXME: If we have a suggested module for a '#include', and we've already
2124   // visited this file, don't bother entering it again. We know it has no
2125   // further effect.
2126   bool EnterOnce =
2127       IsImportDecl ||
2128       IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import;
2129 
2130   // Ask HeaderInfo if we should enter this #include file.  If not, #including
2131   // this file will have no effect.
2132   if (Action == Enter && File &&
2133       !HeaderInfo.ShouldEnterIncludeFile(*this, &File->getFileEntry(),
2134                                          EnterOnce, getLangOpts().Modules,
2135                                          SuggestedModule.getModule())) {
2136     // Even if we've already preprocessed this header once and know that we
2137     // don't need to see its contents again, we still need to import it if it's
2138     // modular because we might not have imported it from this submodule before.
2139     //
2140     // FIXME: We don't do this when compiling a PCH because the AST
2141     // serialization layer can't cope with it. This means we get local
2142     // submodule visibility semantics wrong in that case.
2143     Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip;
2144   }
2145 
2146   // Check for circular inclusion of the main file.
2147   // We can't generate a consistent preamble with regard to the conditional
2148   // stack if the main file is included again as due to the preamble bounds
2149   // some directives (e.g. #endif of a header guard) will never be seen.
2150   // Since this will lead to confusing errors, avoid the inclusion.
2151   if (Action == Enter && File && PreambleConditionalStack.isRecording() &&
2152       SourceMgr.isMainFile(File->getFileEntry())) {
2153     Diag(FilenameTok.getLocation(),
2154          diag::err_pp_including_mainfile_in_preamble);
2155     return {ImportAction::None};
2156   }
2157 
2158   if (Callbacks && !IsImportDecl) {
2159     // Notify the callback object that we've seen an inclusion directive.
2160     // FIXME: Use a different callback for a pp-import?
2161     Callbacks->InclusionDirective(
2162         HashLoc, IncludeTok, LookupFilename, isAngled, FilenameRange,
2163         File ? &File->getFileEntry() : nullptr, SearchPath, RelativePath,
2164         Action == Import ? SuggestedModule.getModule() : nullptr,
2165         FileCharacter);
2166     if (Action == Skip && File)
2167       Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
2168   }
2169 
2170   if (!File)
2171     return {ImportAction::None};
2172 
2173   // If this is a C++20 pp-import declaration, diagnose if we didn't find any
2174   // module corresponding to the named header.
2175   if (IsImportDecl && !SuggestedModule) {
2176     Diag(FilenameTok, diag::err_header_import_not_header_unit)
2177       << OriginalFilename << File->getName();
2178     return {ImportAction::None};
2179   }
2180 
2181   // Issue a diagnostic if the name of the file on disk has a different case
2182   // than the one we're about to open.
2183   const bool CheckIncludePathPortability =
2184       !IsMapped && !File->getFileEntry().tryGetRealPathName().empty();
2185 
2186   if (CheckIncludePathPortability) {
2187     StringRef Name = LookupFilename;
2188     StringRef NameWithoriginalSlashes = Filename;
2189 #if defined(_WIN32)
2190     // Skip UNC prefix if present. (tryGetRealPathName() always
2191     // returns a path with the prefix skipped.)
2192     bool NameWasUNC = Name.consume_front("\\\\?\\");
2193     NameWithoriginalSlashes.consume_front("\\\\?\\");
2194 #endif
2195     StringRef RealPathName = File->getFileEntry().tryGetRealPathName();
2196     SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
2197                                           llvm::sys::path::end(Name));
2198 #if defined(_WIN32)
2199     // -Wnonportable-include-path is designed to diagnose includes using
2200     // case even on systems with a case-insensitive file system.
2201     // On Windows, RealPathName always starts with an upper-case drive
2202     // letter for absolute paths, but Name might start with either
2203     // case depending on if `cd c:\foo` or `cd C:\foo` was used in the shell.
2204     // ("foo" will always have on-disk case, no matter which case was
2205     // used in the cd command). To not emit this warning solely for
2206     // the drive letter, whose case is dependent on if `cd` is used
2207     // with upper- or lower-case drive letters, always consider the
2208     // given drive letter case as correct for the purpose of this warning.
2209     SmallString<128> FixedDriveRealPath;
2210     if (llvm::sys::path::is_absolute(Name) &&
2211         llvm::sys::path::is_absolute(RealPathName) &&
2212         toLowercase(Name[0]) == toLowercase(RealPathName[0]) &&
2213         isLowercase(Name[0]) != isLowercase(RealPathName[0])) {
2214       assert(Components.size() >= 3 && "should have drive, backslash, name");
2215       assert(Components[0].size() == 2 && "should start with drive");
2216       assert(Components[0][1] == ':' && "should have colon");
2217       FixedDriveRealPath = (Name.substr(0, 1) + RealPathName.substr(1)).str();
2218       RealPathName = FixedDriveRealPath;
2219     }
2220 #endif
2221 
2222     if (trySimplifyPath(Components, RealPathName)) {
2223       SmallString<128> Path;
2224       Path.reserve(Name.size()+2);
2225       Path.push_back(isAngled ? '<' : '"');
2226 
2227       const auto IsSep = [BackslashStyle](char c) {
2228         return llvm::sys::path::is_separator(c, BackslashStyle);
2229       };
2230 
2231       for (auto Component : Components) {
2232         // On POSIX, Components will contain a single '/' as first element
2233         // exactly if Name is an absolute path.
2234         // On Windows, it will contain "C:" followed by '\' for absolute paths.
2235         // The drive letter is optional for absolute paths on Windows, but
2236         // clang currently cannot process absolute paths in #include lines that
2237         // don't have a drive.
2238         // If the first entry in Components is a directory separator,
2239         // then the code at the bottom of this loop that keeps the original
2240         // directory separator style copies it. If the second entry is
2241         // a directory separator (the C:\ case), then that separator already
2242         // got copied when the C: was processed and we want to skip that entry.
2243         if (!(Component.size() == 1 && IsSep(Component[0])))
2244           Path.append(Component);
2245         else if (!Path.empty())
2246           continue;
2247 
2248         // Append the separator(s) the user used, or the close quote
2249         if (Path.size() > NameWithoriginalSlashes.size()) {
2250           Path.push_back(isAngled ? '>' : '"');
2251           continue;
2252         }
2253         assert(IsSep(NameWithoriginalSlashes[Path.size()-1]));
2254         do
2255           Path.push_back(NameWithoriginalSlashes[Path.size()-1]);
2256         while (Path.size() <= NameWithoriginalSlashes.size() &&
2257                IsSep(NameWithoriginalSlashes[Path.size()-1]));
2258       }
2259 
2260 #if defined(_WIN32)
2261       // Restore UNC prefix if it was there.
2262       if (NameWasUNC)
2263         Path = (Path.substr(0, 1) + "\\\\?\\" + Path.substr(1)).str();
2264 #endif
2265 
2266       // For user files and known standard headers, issue a diagnostic.
2267       // For other system headers, don't. They can be controlled separately.
2268       auto DiagId =
2269           (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name))
2270               ? diag::pp_nonportable_path
2271               : diag::pp_nonportable_system_path;
2272       Diag(FilenameTok, DiagId) << Path <<
2273         FixItHint::CreateReplacement(FilenameRange, Path);
2274     }
2275   }
2276 
2277   switch (Action) {
2278   case Skip:
2279     // If we don't need to enter the file, stop now.
2280     if (Module *M = SuggestedModule.getModule())
2281       return {ImportAction::SkippedModuleImport, M};
2282     return {ImportAction::None};
2283 
2284   case IncludeLimitReached:
2285     // If we reached our include limit and don't want to enter any more files,
2286     // don't go any further.
2287     return {ImportAction::None};
2288 
2289   case Import: {
2290     // If this is a module import, make it visible if needed.
2291     Module *M = SuggestedModule.getModule();
2292     assert(M && "no module to import");
2293 
2294     makeModuleVisible(M, EndLoc);
2295 
2296     if (IncludeTok.getIdentifierInfo()->getPPKeywordID() ==
2297         tok::pp___include_macros)
2298       return {ImportAction::None};
2299 
2300     return {ImportAction::ModuleImport, M};
2301   }
2302 
2303   case Enter:
2304     break;
2305   }
2306 
2307   // Check that we don't have infinite #include recursion.
2308   if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
2309     Diag(FilenameTok, diag::err_pp_include_too_deep);
2310     HasReachedMaxIncludeDepth = true;
2311     return {ImportAction::None};
2312   }
2313 
2314   // Look up the file, create a File ID for it.
2315   SourceLocation IncludePos = FilenameTok.getLocation();
2316   // If the filename string was the result of macro expansions, set the include
2317   // position on the file where it will be included and after the expansions.
2318   if (IncludePos.isMacroID())
2319     IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
2320   FileID FID = SourceMgr.createFileID(*File, IncludePos, FileCharacter);
2321   if (!FID.isValid()) {
2322     TheModuleLoader.HadFatalFailure = true;
2323     return ImportAction::Failure;
2324   }
2325 
2326   // If all is good, enter the new file!
2327   if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
2328     return {ImportAction::None};
2329 
2330   // Determine if we're switching to building a new submodule, and which one.
2331   if (auto *M = SuggestedModule.getModule()) {
2332     if (M->getTopLevelModule()->ShadowingModule) {
2333       // We are building a submodule that belongs to a shadowed module. This
2334       // means we find header files in the shadowed module.
2335       Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
2336         << M->getFullModuleName();
2337       Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
2338            diag::note_previous_definition);
2339       return {ImportAction::None};
2340     }
2341     // When building a pch, -fmodule-name tells the compiler to textually
2342     // include headers in the specified module. We are not building the
2343     // specified module.
2344     //
2345     // FIXME: This is the wrong way to handle this. We should produce a PCH
2346     // that behaves the same as the header would behave in a compilation using
2347     // that PCH, which means we should enter the submodule. We need to teach
2348     // the AST serialization layer to deal with the resulting AST.
2349     if (getLangOpts().CompilingPCH &&
2350         isForModuleBuilding(M, getLangOpts().CurrentModule,
2351                             getLangOpts().ModuleName))
2352       return {ImportAction::None};
2353 
2354     assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2355     CurLexerSubmodule = M;
2356 
2357     // Let the macro handling code know that any future macros are within
2358     // the new submodule.
2359     EnterSubmodule(M, EndLoc, /*ForPragma*/false);
2360 
2361     // Let the parser know that any future declarations are within the new
2362     // submodule.
2363     // FIXME: There's no point doing this if we're handling a #__include_macros
2364     // directive.
2365     return {ImportAction::ModuleBegin, M};
2366   }
2367 
2368   assert(!IsImportDecl && "failed to diagnose missing module for import decl");
2369   return {ImportAction::None};
2370 }
2371 
2372 /// HandleIncludeNextDirective - Implements \#include_next.
2373 ///
2374 void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2375                                               Token &IncludeNextTok) {
2376   Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
2377 
2378   // #include_next is like #include, except that we start searching after
2379   // the current found directory.  If we can't do this, issue a
2380   // diagnostic.
2381   const DirectoryLookup *Lookup = CurDirLookup;
2382   const FileEntry *LookupFromFile = nullptr;
2383   if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
2384     // If the main file is a header, then it's either for PCH/AST generation,
2385     // or libclang opened it. Either way, handle it as a normal include below
2386     // and do not complain about include_next.
2387   } else if (isInPrimaryFile()) {
2388     Lookup = nullptr;
2389     Diag(IncludeNextTok, diag::pp_include_next_in_primary);
2390   } else if (CurLexerSubmodule) {
2391     // Start looking up in the directory *after* the one in which the current
2392     // file would be found, if any.
2393     assert(CurPPLexer && "#include_next directive in macro?");
2394     LookupFromFile = CurPPLexer->getFileEntry();
2395     Lookup = nullptr;
2396   } else if (!Lookup) {
2397     // The current file was not found by walking the include path. Either it
2398     // is the primary file (handled above), or it was found by absolute path,
2399     // or it was found relative to such a file.
2400     // FIXME: Track enough information so we know which case we're in.
2401     Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
2402   } else {
2403     // Start looking up in the next directory.
2404     ++Lookup;
2405   }
2406 
2407   return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2408                                 LookupFromFile);
2409 }
2410 
2411 /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
2412 void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2413   // The Microsoft #import directive takes a type library and generates header
2414   // files from it, and includes those.  This is beyond the scope of what clang
2415   // does, so we ignore it and error out.  However, #import can optionally have
2416   // trailing attributes that span multiple lines.  We're going to eat those
2417   // so we can continue processing from there.
2418   Diag(Tok, diag::err_pp_import_directive_ms );
2419 
2420   // Read tokens until we get to the end of the directive.  Note that the
2421   // directive can be split over multiple lines using the backslash character.
2422   DiscardUntilEndOfDirective();
2423 }
2424 
2425 /// HandleImportDirective - Implements \#import.
2426 ///
2427 void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2428                                          Token &ImportTok) {
2429   if (!LangOpts.ObjC) {  // #import is standard for ObjC.
2430     if (LangOpts.MSVCCompat)
2431       return HandleMicrosoftImportDirective(ImportTok);
2432     Diag(ImportTok, diag::ext_pp_import_directive);
2433   }
2434   return HandleIncludeDirective(HashLoc, ImportTok);
2435 }
2436 
2437 /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2438 /// pseudo directive in the predefines buffer.  This handles it by sucking all
2439 /// tokens through the preprocessor and discarding them (only keeping the side
2440 /// effects on the preprocessor).
2441 void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2442                                                 Token &IncludeMacrosTok) {
2443   // This directive should only occur in the predefines buffer.  If not, emit an
2444   // error and reject it.
2445   SourceLocation Loc = IncludeMacrosTok.getLocation();
2446   if (SourceMgr.getBufferName(Loc) != "<built-in>") {
2447     Diag(IncludeMacrosTok.getLocation(),
2448          diag::pp_include_macros_out_of_predefines);
2449     DiscardUntilEndOfDirective();
2450     return;
2451   }
2452 
2453   // Treat this as a normal #include for checking purposes.  If this is
2454   // successful, it will push a new lexer onto the include stack.
2455   HandleIncludeDirective(HashLoc, IncludeMacrosTok);
2456 
2457   Token TmpTok;
2458   do {
2459     Lex(TmpTok);
2460     assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2461   } while (TmpTok.isNot(tok::hashhash));
2462 }
2463 
2464 //===----------------------------------------------------------------------===//
2465 // Preprocessor Macro Directive Handling.
2466 //===----------------------------------------------------------------------===//
2467 
2468 /// ReadMacroParameterList - The ( starting a parameter list of a macro
2469 /// definition has just been read.  Lex the rest of the parameters and the
2470 /// closing ), updating MI with what we learn.  Return true if an error occurs
2471 /// parsing the param list.
2472 bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
2473   SmallVector<IdentifierInfo*, 32> Parameters;
2474 
2475   while (true) {
2476     LexUnexpandedToken(Tok);
2477     switch (Tok.getKind()) {
2478     case tok::r_paren:
2479       // Found the end of the parameter list.
2480       if (Parameters.empty())  // #define FOO()
2481         return false;
2482       // Otherwise we have #define FOO(A,)
2483       Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2484       return true;
2485     case tok::ellipsis:  // #define X(... -> C99 varargs
2486       if (!LangOpts.C99)
2487         Diag(Tok, LangOpts.CPlusPlus11 ?
2488              diag::warn_cxx98_compat_variadic_macro :
2489              diag::ext_variadic_macro);
2490 
2491       // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2492       if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus) {
2493         Diag(Tok, diag::ext_pp_opencl_variadic_macros);
2494       }
2495 
2496       // Lex the token after the identifier.
2497       LexUnexpandedToken(Tok);
2498       if (Tok.isNot(tok::r_paren)) {
2499         Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2500         return true;
2501       }
2502       // Add the __VA_ARGS__ identifier as a parameter.
2503       Parameters.push_back(Ident__VA_ARGS__);
2504       MI->setIsC99Varargs();
2505       MI->setParameterList(Parameters, BP);
2506       return false;
2507     case tok::eod:  // #define X(
2508       Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2509       return true;
2510     default:
2511       // Handle keywords and identifiers here to accept things like
2512       // #define Foo(for) for.
2513       IdentifierInfo *II = Tok.getIdentifierInfo();
2514       if (!II) {
2515         // #define X(1
2516         Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2517         return true;
2518       }
2519 
2520       // If this is already used as a parameter, it is used multiple times (e.g.
2521       // #define X(A,A.
2522       if (llvm::find(Parameters, II) != Parameters.end()) { // C99 6.10.3p6
2523         Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
2524         return true;
2525       }
2526 
2527       // Add the parameter to the macro info.
2528       Parameters.push_back(II);
2529 
2530       // Lex the token after the identifier.
2531       LexUnexpandedToken(Tok);
2532 
2533       switch (Tok.getKind()) {
2534       default:          // #define X(A B
2535         Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2536         return true;
2537       case tok::r_paren: // #define X(A)
2538         MI->setParameterList(Parameters, BP);
2539         return false;
2540       case tok::comma:  // #define X(A,
2541         break;
2542       case tok::ellipsis:  // #define X(A... -> GCC extension
2543         // Diagnose extension.
2544         Diag(Tok, diag::ext_named_variadic_macro);
2545 
2546         // Lex the token after the identifier.
2547         LexUnexpandedToken(Tok);
2548         if (Tok.isNot(tok::r_paren)) {
2549           Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2550           return true;
2551         }
2552 
2553         MI->setIsGNUVarargs();
2554         MI->setParameterList(Parameters, BP);
2555         return false;
2556       }
2557     }
2558   }
2559 }
2560 
2561 static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2562                                    const LangOptions &LOptions) {
2563   if (MI->getNumTokens() == 1) {
2564     const Token &Value = MI->getReplacementToken(0);
2565 
2566     // Macro that is identity, like '#define inline inline' is a valid pattern.
2567     if (MacroName.getKind() == Value.getKind())
2568       return true;
2569 
2570     // Macro that maps a keyword to the same keyword decorated with leading/
2571     // trailing underscores is a valid pattern:
2572     //    #define inline __inline
2573     //    #define inline __inline__
2574     //    #define inline _inline (in MS compatibility mode)
2575     StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2576     if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2577       if (!II->isKeyword(LOptions))
2578         return false;
2579       StringRef ValueText = II->getName();
2580       StringRef TrimmedValue = ValueText;
2581       if (!ValueText.startswith("__")) {
2582         if (ValueText.startswith("_"))
2583           TrimmedValue = TrimmedValue.drop_front(1);
2584         else
2585           return false;
2586       } else {
2587         TrimmedValue = TrimmedValue.drop_front(2);
2588         if (TrimmedValue.endswith("__"))
2589           TrimmedValue = TrimmedValue.drop_back(2);
2590       }
2591       return TrimmedValue.equals(MacroText);
2592     } else {
2593       return false;
2594     }
2595   }
2596 
2597   // #define inline
2598   return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2599                            tok::kw_const) &&
2600          MI->getNumTokens() == 0;
2601 }
2602 
2603 // ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2604 // entire line) of the macro's tokens and adds them to MacroInfo, and while
2605 // doing so performs certain validity checks including (but not limited to):
2606 //   - # (stringization) is followed by a macro parameter
2607 //
2608 //  Returns a nullptr if an invalid sequence of tokens is encountered or returns
2609 //  a pointer to a MacroInfo object.
2610 
2611 MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2612     const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
2613 
2614   Token LastTok = MacroNameTok;
2615   // Create the new macro.
2616   MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
2617 
2618   Token Tok;
2619   LexUnexpandedToken(Tok);
2620 
2621   // Ensure we consume the rest of the macro body if errors occur.
2622   auto _ = llvm::make_scope_exit([&]() {
2623     // The flag indicates if we are still waiting for 'eod'.
2624     if (CurLexer->ParsingPreprocessorDirective)
2625       DiscardUntilEndOfDirective();
2626   });
2627 
2628   // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2629   // within their appropriate context.
2630   VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2631 
2632   // If this is a function-like macro definition, parse the argument list,
2633   // marking each of the identifiers as being used as macro arguments.  Also,
2634   // check other constraints on the first token of the macro body.
2635   if (Tok.is(tok::eod)) {
2636     if (ImmediatelyAfterHeaderGuard) {
2637       // Save this macro information since it may part of a header guard.
2638       CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2639                                         MacroNameTok.getLocation());
2640     }
2641     // If there is no body to this macro, we have no special handling here.
2642   } else if (Tok.hasLeadingSpace()) {
2643     // This is a normal token with leading space.  Clear the leading space
2644     // marker on the first token to get proper expansion.
2645     Tok.clearFlag(Token::LeadingSpace);
2646   } else if (Tok.is(tok::l_paren)) {
2647     // This is a function-like macro definition.  Read the argument list.
2648     MI->setIsFunctionLike();
2649     if (ReadMacroParameterList(MI, LastTok))
2650       return nullptr;
2651 
2652     // If this is a definition of an ISO C/C++ variadic function-like macro (not
2653     // using the GNU named varargs extension) inform our variadic scope guard
2654     // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2655     // allowed only within the definition of a variadic macro.
2656 
2657     if (MI->isC99Varargs()) {
2658       VariadicMacroScopeGuard.enterScope();
2659     }
2660 
2661     // Read the first token after the arg list for down below.
2662     LexUnexpandedToken(Tok);
2663   } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
2664     // C99 requires whitespace between the macro definition and the body.  Emit
2665     // a diagnostic for something like "#define X+".
2666     Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
2667   } else {
2668     // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2669     // first character of a replacement list is not a character required by
2670     // subclause 5.2.1, then there shall be white-space separation between the
2671     // identifier and the replacement list.".  5.2.1 lists this set:
2672     //   "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2673     // is irrelevant here.
2674     bool isInvalid = false;
2675     if (Tok.is(tok::at)) // @ is not in the list above.
2676       isInvalid = true;
2677     else if (Tok.is(tok::unknown)) {
2678       // If we have an unknown token, it is something strange like "`".  Since
2679       // all of valid characters would have lexed into a single character
2680       // token of some sort, we know this is not a valid case.
2681       isInvalid = true;
2682     }
2683     if (isInvalid)
2684       Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2685     else
2686       Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
2687   }
2688 
2689   if (!Tok.is(tok::eod))
2690     LastTok = Tok;
2691 
2692   // Read the rest of the macro body.
2693   if (MI->isObjectLike()) {
2694     // Object-like macros are very simple, just read their body.
2695     while (Tok.isNot(tok::eod)) {
2696       LastTok = Tok;
2697       MI->AddTokenToBody(Tok);
2698       // Get the next token of the macro.
2699       LexUnexpandedToken(Tok);
2700     }
2701   } else {
2702     // Otherwise, read the body of a function-like macro.  While we are at it,
2703     // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2704     // parameters in function-like macro expansions.
2705 
2706     VAOptDefinitionContext VAOCtx(*this);
2707 
2708     while (Tok.isNot(tok::eod)) {
2709       LastTok = Tok;
2710 
2711       if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
2712         MI->AddTokenToBody(Tok);
2713 
2714         if (VAOCtx.isVAOptToken(Tok)) {
2715           // If we're already within a VAOPT, emit an error.
2716           if (VAOCtx.isInVAOpt()) {
2717             Diag(Tok, diag::err_pp_vaopt_nested_use);
2718             return nullptr;
2719           }
2720           // Ensure VAOPT is followed by a '(' .
2721           LexUnexpandedToken(Tok);
2722           if (Tok.isNot(tok::l_paren)) {
2723             Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
2724             return nullptr;
2725           }
2726           MI->AddTokenToBody(Tok);
2727           VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
2728           LexUnexpandedToken(Tok);
2729           if (Tok.is(tok::hashhash)) {
2730             Diag(Tok, diag::err_vaopt_paste_at_start);
2731             return nullptr;
2732           }
2733           continue;
2734         } else if (VAOCtx.isInVAOpt()) {
2735           if (Tok.is(tok::r_paren)) {
2736             if (VAOCtx.sawClosingParen()) {
2737               const unsigned NumTokens = MI->getNumTokens();
2738               assert(NumTokens >= 3 && "Must have seen at least __VA_OPT__( "
2739                                        "and a subsequent tok::r_paren");
2740               if (MI->getReplacementToken(NumTokens - 2).is(tok::hashhash)) {
2741                 Diag(Tok, diag::err_vaopt_paste_at_end);
2742                 return nullptr;
2743               }
2744             }
2745           } else if (Tok.is(tok::l_paren)) {
2746             VAOCtx.sawOpeningParen(Tok.getLocation());
2747           }
2748         }
2749         // Get the next token of the macro.
2750         LexUnexpandedToken(Tok);
2751         continue;
2752       }
2753 
2754       // If we're in -traditional mode, then we should ignore stringification
2755       // and token pasting. Mark the tokens as unknown so as not to confuse
2756       // things.
2757       if (getLangOpts().TraditionalCPP) {
2758         Tok.setKind(tok::unknown);
2759         MI->AddTokenToBody(Tok);
2760 
2761         // Get the next token of the macro.
2762         LexUnexpandedToken(Tok);
2763         continue;
2764       }
2765 
2766       if (Tok.is(tok::hashhash)) {
2767         // If we see token pasting, check if it looks like the gcc comma
2768         // pasting extension.  We'll use this information to suppress
2769         // diagnostics later on.
2770 
2771         // Get the next token of the macro.
2772         LexUnexpandedToken(Tok);
2773 
2774         if (Tok.is(tok::eod)) {
2775           MI->AddTokenToBody(LastTok);
2776           break;
2777         }
2778 
2779         unsigned NumTokens = MI->getNumTokens();
2780         if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2781             MI->getReplacementToken(NumTokens-1).is(tok::comma))
2782           MI->setHasCommaPasting();
2783 
2784         // Things look ok, add the '##' token to the macro.
2785         MI->AddTokenToBody(LastTok);
2786         continue;
2787       }
2788 
2789       // Our Token is a stringization operator.
2790       // Get the next token of the macro.
2791       LexUnexpandedToken(Tok);
2792 
2793       // Check for a valid macro arg identifier or __VA_OPT__.
2794       if (!VAOCtx.isVAOptToken(Tok) &&
2795           (Tok.getIdentifierInfo() == nullptr ||
2796            MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
2797 
2798         // If this is assembler-with-cpp mode, we accept random gibberish after
2799         // the '#' because '#' is often a comment character.  However, change
2800         // the kind of the token to tok::unknown so that the preprocessor isn't
2801         // confused.
2802         if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
2803           LastTok.setKind(tok::unknown);
2804           MI->AddTokenToBody(LastTok);
2805           continue;
2806         } else {
2807           Diag(Tok, diag::err_pp_stringize_not_parameter)
2808             << LastTok.is(tok::hashat);
2809           return nullptr;
2810         }
2811       }
2812 
2813       // Things look ok, add the '#' and param name tokens to the macro.
2814       MI->AddTokenToBody(LastTok);
2815 
2816       // If the token following '#' is VAOPT, let the next iteration handle it
2817       // and check it for correctness, otherwise add the token and prime the
2818       // loop with the next one.
2819       if (!VAOCtx.isVAOptToken(Tok)) {
2820         MI->AddTokenToBody(Tok);
2821         LastTok = Tok;
2822 
2823         // Get the next token of the macro.
2824         LexUnexpandedToken(Tok);
2825       }
2826     }
2827     if (VAOCtx.isInVAOpt()) {
2828       assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
2829       Diag(Tok, diag::err_pp_expected_after)
2830         << LastTok.getKind() << tok::r_paren;
2831       Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
2832       return nullptr;
2833     }
2834   }
2835   MI->setDefinitionEndLoc(LastTok.getLocation());
2836   return MI;
2837 }
2838 /// HandleDefineDirective - Implements \#define.  This consumes the entire macro
2839 /// line then lets the caller lex the next real token.
2840 void Preprocessor::HandleDefineDirective(
2841     Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2842   ++NumDefined;
2843 
2844   Token MacroNameTok;
2845   bool MacroShadowsKeyword;
2846   ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2847 
2848   // Error reading macro name?  If so, diagnostic already issued.
2849   if (MacroNameTok.is(tok::eod))
2850     return;
2851 
2852   // If we are supposed to keep comments in #defines, reenable comment saving
2853   // mode.
2854   if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2855 
2856   MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2857       MacroNameTok, ImmediatelyAfterHeaderGuard);
2858 
2859   if (!MI) return;
2860 
2861   if (MacroShadowsKeyword &&
2862       !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2863     Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2864   }
2865   // Check that there is no paste (##) operator at the beginning or end of the
2866   // replacement list.
2867   unsigned NumTokens = MI->getNumTokens();
2868   if (NumTokens != 0) {
2869     if (MI->getReplacementToken(0).is(tok::hashhash)) {
2870       Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2871       return;
2872     }
2873     if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2874       Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2875       return;
2876     }
2877   }
2878 
2879   // When skipping just warn about macros that do not match.
2880   if (SkippingUntilPCHThroughHeader) {
2881     const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
2882     if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
2883                              /*Syntactic=*/LangOpts.MicrosoftExt))
2884       Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
2885           << MacroNameTok.getIdentifierInfo();
2886     // Issue the diagnostic but allow the change if msvc extensions are enabled
2887     if (!LangOpts.MicrosoftExt)
2888       return;
2889   }
2890 
2891   // Finally, if this identifier already had a macro defined for it, verify that
2892   // the macro bodies are identical, and issue diagnostics if they are not.
2893   if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
2894     // In Objective-C, ignore attempts to directly redefine the builtin
2895     // definitions of the ownership qualifiers.  It's still possible to
2896     // #undef them.
2897     auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2898       return II->isStr("__strong") ||
2899              II->isStr("__weak") ||
2900              II->isStr("__unsafe_unretained") ||
2901              II->isStr("__autoreleasing");
2902     };
2903    if (getLangOpts().ObjC &&
2904         SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2905           == getPredefinesFileID() &&
2906         isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2907       // Warn if it changes the tokens.
2908       if ((!getDiagnostics().getSuppressSystemWarnings() ||
2909            !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2910           !MI->isIdenticalTo(*OtherMI, *this,
2911                              /*Syntactic=*/LangOpts.MicrosoftExt)) {
2912         Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2913       }
2914       assert(!OtherMI->isWarnIfUnused());
2915       return;
2916     }
2917 
2918     // It is very common for system headers to have tons of macro redefinitions
2919     // and for warnings to be disabled in system headers.  If this is the case,
2920     // then don't bother calling MacroInfo::isIdenticalTo.
2921     if (!getDiagnostics().getSuppressSystemWarnings() ||
2922         !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
2923       if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
2924         Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
2925 
2926       // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
2927       // C++ [cpp.predefined]p4, but allow it as an extension.
2928       if (OtherMI->isBuiltinMacro())
2929         Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
2930       // Macros must be identical.  This means all tokens and whitespace
2931       // separation must be the same.  C99 6.10.3p2.
2932       else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
2933                !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
2934         Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
2935           << MacroNameTok.getIdentifierInfo();
2936         Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
2937       }
2938     }
2939     if (OtherMI->isWarnIfUnused())
2940       WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
2941   }
2942 
2943   DefMacroDirective *MD =
2944       appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
2945 
2946   assert(!MI->isUsed());
2947   // If we need warning for not using the macro, add its location in the
2948   // warn-because-unused-macro set. If it gets used it will be removed from set.
2949   if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
2950       !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc()) &&
2951       !MacroExpansionInDirectivesOverride &&
2952       getSourceManager().getFileID(MI->getDefinitionLoc()) !=
2953           getPredefinesFileID()) {
2954     MI->setIsWarnIfUnused(true);
2955     WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
2956   }
2957 
2958   // If the callbacks want to know, tell them about the macro definition.
2959   if (Callbacks)
2960     Callbacks->MacroDefined(MacroNameTok, MD);
2961 
2962   // If we're in MS compatibility mode and the macro being defined is the
2963   // assert macro, implicitly add a macro definition for static_assert to work
2964   // around their broken assert.h header file in C. Only do so if there isn't
2965   // already a static_assert macro defined.
2966   if (!getLangOpts().CPlusPlus && getLangOpts().MSVCCompat &&
2967       MacroNameTok.getIdentifierInfo()->isStr("assert") &&
2968       !isMacroDefined("static_assert")) {
2969     MacroInfo *MI = AllocateMacroInfo(SourceLocation());
2970 
2971     Token Tok;
2972     Tok.startToken();
2973     Tok.setKind(tok::kw__Static_assert);
2974     Tok.setIdentifierInfo(getIdentifierInfo("_Static_assert"));
2975     MI->AddTokenToBody(Tok);
2976     (void)appendDefMacroDirective(getIdentifierInfo("static_assert"), MI);
2977   }
2978 }
2979 
2980 /// HandleUndefDirective - Implements \#undef.
2981 ///
2982 void Preprocessor::HandleUndefDirective() {
2983   ++NumUndefined;
2984 
2985   Token MacroNameTok;
2986   ReadMacroName(MacroNameTok, MU_Undef);
2987 
2988   // Error reading macro name?  If so, diagnostic already issued.
2989   if (MacroNameTok.is(tok::eod))
2990     return;
2991 
2992   // Check to see if this is the last token on the #undef line.
2993   CheckEndOfDirective("undef");
2994 
2995   // Okay, we have a valid identifier to undef.
2996   auto *II = MacroNameTok.getIdentifierInfo();
2997   auto MD = getMacroDefinition(II);
2998   UndefMacroDirective *Undef = nullptr;
2999 
3000   // If the macro is not defined, this is a noop undef.
3001   if (const MacroInfo *MI = MD.getMacroInfo()) {
3002     if (!MI->isUsed() && MI->isWarnIfUnused())
3003       Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
3004 
3005     if (MI->isWarnIfUnused())
3006       WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
3007 
3008     Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
3009   }
3010 
3011   // If the callbacks want to know, tell them about the macro #undef.
3012   // Note: no matter if the macro was defined or not.
3013   if (Callbacks)
3014     Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
3015 
3016   if (Undef)
3017     appendMacroDirective(II, Undef);
3018 }
3019 
3020 //===----------------------------------------------------------------------===//
3021 // Preprocessor Conditional Directive Handling.
3022 //===----------------------------------------------------------------------===//
3023 
3024 /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive.  isIfndef
3025 /// is true when this is a \#ifndef directive.  ReadAnyTokensBeforeDirective is
3026 /// true if any tokens have been returned or pp-directives activated before this
3027 /// \#ifndef has been lexed.
3028 ///
3029 void Preprocessor::HandleIfdefDirective(Token &Result,
3030                                         const Token &HashToken,
3031                                         bool isIfndef,
3032                                         bool ReadAnyTokensBeforeDirective) {
3033   ++NumIf;
3034   Token DirectiveTok = Result;
3035 
3036   Token MacroNameTok;
3037   ReadMacroName(MacroNameTok);
3038 
3039   // Error reading macro name?  If so, diagnostic already issued.
3040   if (MacroNameTok.is(tok::eod)) {
3041     // Skip code until we get to #endif.  This helps with recovery by not
3042     // emitting an error when the #endif is reached.
3043     SkipExcludedConditionalBlock(HashToken.getLocation(),
3044                                  DirectiveTok.getLocation(),
3045                                  /*Foundnonskip*/ false, /*FoundElse*/ false);
3046     return;
3047   }
3048 
3049   // Check to see if this is the last token on the #if[n]def line.
3050   CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
3051 
3052   IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
3053   auto MD = getMacroDefinition(MII);
3054   MacroInfo *MI = MD.getMacroInfo();
3055 
3056   if (CurPPLexer->getConditionalStackDepth() == 0) {
3057     // If the start of a top-level #ifdef and if the macro is not defined,
3058     // inform MIOpt that this might be the start of a proper include guard.
3059     // Otherwise it is some other form of unknown conditional which we can't
3060     // handle.
3061     if (!ReadAnyTokensBeforeDirective && !MI) {
3062       assert(isIfndef && "#ifdef shouldn't reach here");
3063       CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
3064     } else
3065       CurPPLexer->MIOpt.EnterTopLevelConditional();
3066   }
3067 
3068   // If there is a macro, process it.
3069   if (MI)  // Mark it used.
3070     markMacroAsUsed(MI);
3071 
3072   if (Callbacks) {
3073     if (isIfndef)
3074       Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
3075     else
3076       Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
3077   }
3078 
3079   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3080     getSourceManager().isInMainFile(DirectiveTok.getLocation());
3081 
3082   // Should we include the stuff contained by this directive?
3083   if (PPOpts->SingleFileParseMode && !MI) {
3084     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3085     // the directive blocks.
3086     CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
3087                                      /*wasskip*/false, /*foundnonskip*/false,
3088                                      /*foundelse*/false);
3089   } else if (!MI == isIfndef || RetainExcludedCB) {
3090     // Yes, remember that we are inside a conditional, then lex the next token.
3091     CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
3092                                      /*wasskip*/false, /*foundnonskip*/true,
3093                                      /*foundelse*/false);
3094   } else {
3095     // No, skip the contents of this block.
3096     SkipExcludedConditionalBlock(HashToken.getLocation(),
3097                                  DirectiveTok.getLocation(),
3098                                  /*Foundnonskip*/ false,
3099                                  /*FoundElse*/ false);
3100   }
3101 }
3102 
3103 /// HandleIfDirective - Implements the \#if directive.
3104 ///
3105 void Preprocessor::HandleIfDirective(Token &IfToken,
3106                                      const Token &HashToken,
3107                                      bool ReadAnyTokensBeforeDirective) {
3108   ++NumIf;
3109 
3110   // Parse and evaluate the conditional expression.
3111   IdentifierInfo *IfNDefMacro = nullptr;
3112   const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
3113   const bool ConditionalTrue = DER.Conditional;
3114   // Lexer might become invalid if we hit code completion point while evaluating
3115   // expression.
3116   if (!CurPPLexer)
3117     return;
3118 
3119   // If this condition is equivalent to #ifndef X, and if this is the first
3120   // directive seen, handle it for the multiple-include optimization.
3121   if (CurPPLexer->getConditionalStackDepth() == 0) {
3122     if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
3123       // FIXME: Pass in the location of the macro name, not the 'if' token.
3124       CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
3125     else
3126       CurPPLexer->MIOpt.EnterTopLevelConditional();
3127   }
3128 
3129   if (Callbacks)
3130     Callbacks->If(
3131         IfToken.getLocation(), DER.ExprRange,
3132         (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
3133 
3134   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3135     getSourceManager().isInMainFile(IfToken.getLocation());
3136 
3137   // Should we include the stuff contained by this directive?
3138   if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
3139     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3140     // the directive blocks.
3141     CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
3142                                      /*foundnonskip*/false, /*foundelse*/false);
3143   } else if (ConditionalTrue || RetainExcludedCB) {
3144     // Yes, remember that we are inside a conditional, then lex the next token.
3145     CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
3146                                    /*foundnonskip*/true, /*foundelse*/false);
3147   } else {
3148     // No, skip the contents of this block.
3149     SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
3150                                  /*Foundnonskip*/ false,
3151                                  /*FoundElse*/ false);
3152   }
3153 }
3154 
3155 /// HandleEndifDirective - Implements the \#endif directive.
3156 ///
3157 void Preprocessor::HandleEndifDirective(Token &EndifToken) {
3158   ++NumEndif;
3159 
3160   // Check that this is the whole directive.
3161   CheckEndOfDirective("endif");
3162 
3163   PPConditionalInfo CondInfo;
3164   if (CurPPLexer->popConditionalLevel(CondInfo)) {
3165     // No conditionals on the stack: this is an #endif without an #if.
3166     Diag(EndifToken, diag::err_pp_endif_without_if);
3167     return;
3168   }
3169 
3170   // If this the end of a top-level #endif, inform MIOpt.
3171   if (CurPPLexer->getConditionalStackDepth() == 0)
3172     CurPPLexer->MIOpt.ExitTopLevelConditional();
3173 
3174   assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
3175          "This code should only be reachable in the non-skipping case!");
3176 
3177   if (Callbacks)
3178     Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
3179 }
3180 
3181 /// HandleElseDirective - Implements the \#else directive.
3182 ///
3183 void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
3184   ++NumElse;
3185 
3186   // #else directive in a non-skipping conditional... start skipping.
3187   CheckEndOfDirective("else");
3188 
3189   PPConditionalInfo CI;
3190   if (CurPPLexer->popConditionalLevel(CI)) {
3191     Diag(Result, diag::pp_err_else_without_if);
3192     return;
3193   }
3194 
3195   // If this is a top-level #else, inform the MIOpt.
3196   if (CurPPLexer->getConditionalStackDepth() == 0)
3197     CurPPLexer->MIOpt.EnterTopLevelConditional();
3198 
3199   // If this is a #else with a #else before it, report the error.
3200   if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
3201 
3202   if (Callbacks)
3203     Callbacks->Else(Result.getLocation(), CI.IfLoc);
3204 
3205   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3206     getSourceManager().isInMainFile(Result.getLocation());
3207 
3208   if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
3209     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3210     // the directive blocks.
3211     CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
3212                                      /*foundnonskip*/false, /*foundelse*/true);
3213     return;
3214   }
3215 
3216   // Finally, skip the rest of the contents of this block.
3217   SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
3218                                /*Foundnonskip*/ true,
3219                                /*FoundElse*/ true, Result.getLocation());
3220 }
3221 
3222 /// Implements the \#elif, \#elifdef, and \#elifndef directives.
3223 void Preprocessor::HandleElifFamilyDirective(Token &ElifToken,
3224                                              const Token &HashToken,
3225                                              tok::PPKeywordKind Kind) {
3226   PPElifDiag DirKind = Kind == tok::pp_elif      ? PED_Elif
3227                        : Kind == tok::pp_elifdef ? PED_Elifdef
3228                                                  : PED_Elifndef;
3229   ++NumElse;
3230 
3231   // #elif directive in a non-skipping conditional... start skipping.
3232   // We don't care what the condition is, because we will always skip it (since
3233   // the block immediately before it was included).
3234   SourceRange ConditionRange = DiscardUntilEndOfDirective();
3235 
3236   PPConditionalInfo CI;
3237   if (CurPPLexer->popConditionalLevel(CI)) {
3238     Diag(ElifToken, diag::pp_err_elif_without_if) << DirKind;
3239     return;
3240   }
3241 
3242   // If this is a top-level #elif, inform the MIOpt.
3243   if (CurPPLexer->getConditionalStackDepth() == 0)
3244     CurPPLexer->MIOpt.EnterTopLevelConditional();
3245 
3246   // If this is a #elif with a #else before it, report the error.
3247   if (CI.FoundElse)
3248     Diag(ElifToken, diag::pp_err_elif_after_else) << DirKind;
3249 
3250   if (Callbacks) {
3251     switch (Kind) {
3252     case tok::pp_elif:
3253       Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
3254                       PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
3255       break;
3256     case tok::pp_elifdef:
3257       Callbacks->Elifdef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
3258       break;
3259     case tok::pp_elifndef:
3260       Callbacks->Elifndef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
3261       break;
3262     default:
3263       assert(false && "unexpected directive kind");
3264       break;
3265     }
3266   }
3267 
3268   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3269     getSourceManager().isInMainFile(ElifToken.getLocation());
3270 
3271   if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
3272     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3273     // the directive blocks.
3274     CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
3275                                      /*foundnonskip*/false, /*foundelse*/false);
3276     return;
3277   }
3278 
3279   // Finally, skip the rest of the contents of this block.
3280   SkipExcludedConditionalBlock(
3281       HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
3282       /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
3283 }
3284