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