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