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