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