]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/lib/Lex/PPDirectives.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / tools / clang / lib / Lex / PPDirectives.cpp
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 //  This file implements # directive processing for the Preprocessor.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Lex/Preprocessor.h"
15 #include "clang/Lex/LiteralSupport.h"
16 #include "clang/Lex/HeaderSearch.h"
17 #include "clang/Lex/MacroInfo.h"
18 #include "clang/Lex/LexDiagnostic.h"
19 #include "clang/Lex/CodeCompletionHandler.h"
20 #include "clang/Lex/ModuleLoader.h"
21 #include "clang/Lex/Pragma.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "llvm/ADT/APInt.h"
25 using namespace clang;
26
27 //===----------------------------------------------------------------------===//
28 // Utility Methods for Preprocessor Directive Handling.
29 //===----------------------------------------------------------------------===//
30
31 MacroInfo *Preprocessor::AllocateMacroInfo() {
32   MacroInfoChain *MIChain;
33
34   if (MICache) {
35     MIChain = MICache;
36     MICache = MICache->Next;
37   }
38   else {
39     MIChain = BP.Allocate<MacroInfoChain>();
40   }
41
42   MIChain->Next = MIChainHead;
43   MIChain->Prev = 0;
44   if (MIChainHead)
45     MIChainHead->Prev = MIChain;
46   MIChainHead = MIChain;
47
48   return &(MIChain->MI);
49 }
50
51 MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
52   MacroInfo *MI = AllocateMacroInfo();
53   new (MI) MacroInfo(L);
54   return MI;
55 }
56
57 MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
58   MacroInfo *MI = AllocateMacroInfo();
59   new (MI) MacroInfo(MacroToClone, BP);
60   return MI;
61 }
62
63 /// ReleaseMacroInfo - Release the specified MacroInfo.  This memory will
64 ///  be reused for allocating new MacroInfo objects.
65 void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
66   MacroInfoChain *MIChain = (MacroInfoChain*) MI;
67   if (MacroInfoChain *Prev = MIChain->Prev) {
68     MacroInfoChain *Next = MIChain->Next;
69     Prev->Next = Next;
70     if (Next)
71       Next->Prev = Prev;
72   }
73   else {
74     assert(MIChainHead == MIChain);
75     MIChainHead = MIChain->Next;
76     MIChainHead->Prev = 0;
77   }
78   MIChain->Next = MICache;
79   MICache = MIChain;
80
81   MI->Destroy();
82 }
83
84 /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
85 /// current line until the tok::eod token is found.
86 void Preprocessor::DiscardUntilEndOfDirective() {
87   Token Tmp;
88   do {
89     LexUnexpandedToken(Tmp);
90     assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
91   } while (Tmp.isNot(tok::eod));
92 }
93
94 /// ReadMacroName - Lex and validate a macro name, which occurs after a
95 /// #define or #undef.  This sets the token kind to eod and discards the rest
96 /// of the macro line if the macro name is invalid.  isDefineUndef is 1 if
97 /// this is due to a a #define, 2 if #undef directive, 0 if it is something
98 /// else (e.g. #ifdef).
99 void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
100   // Read the token, don't allow macro expansion on it.
101   LexUnexpandedToken(MacroNameTok);
102
103   if (MacroNameTok.is(tok::code_completion)) {
104     if (CodeComplete)
105       CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
106     setCodeCompletionReached();
107     LexUnexpandedToken(MacroNameTok);
108   }
109   
110   // Missing macro name?
111   if (MacroNameTok.is(tok::eod)) {
112     Diag(MacroNameTok, diag::err_pp_missing_macro_name);
113     return;
114   }
115
116   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
117   if (II == 0) {
118     bool Invalid = false;
119     std::string Spelling = getSpelling(MacroNameTok, &Invalid);
120     if (Invalid)
121       return;
122     
123     const IdentifierInfo &Info = Identifiers.get(Spelling);
124     if (Info.isCPlusPlusOperatorKeyword())
125       // C++ 2.5p2: Alternative tokens behave the same as its primary token
126       // except for their spellings.
127       Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
128     else
129       Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
130     // Fall through on error.
131   } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
132     // Error if defining "defined": C99 6.10.8.4.
133     Diag(MacroNameTok, diag::err_defined_macro_name);
134   } else if (isDefineUndef && II->hasMacroDefinition() &&
135              getMacroInfo(II)->isBuiltinMacro()) {
136     // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
137     if (isDefineUndef == 1)
138       Diag(MacroNameTok, diag::pp_redef_builtin_macro);
139     else
140       Diag(MacroNameTok, diag::pp_undef_builtin_macro);
141   } else {
142     // Okay, we got a good identifier node.  Return it.
143     return;
144   }
145
146   // Invalid macro name, read and discard the rest of the line.  Then set the
147   // token kind to tok::eod.
148   MacroNameTok.setKind(tok::eod);
149   return DiscardUntilEndOfDirective();
150 }
151
152 /// CheckEndOfDirective - Ensure that the next token is a tok::eod token.  If
153 /// not, emit a diagnostic and consume up until the eod.  If EnableMacros is
154 /// true, then we consider macros that expand to zero tokens as being ok.
155 void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
156   Token Tmp;
157   // Lex unexpanded tokens for most directives: macros might expand to zero
158   // tokens, causing us to miss diagnosing invalid lines.  Some directives (like
159   // #line) allow empty macros.
160   if (EnableMacros)
161     Lex(Tmp);
162   else
163     LexUnexpandedToken(Tmp);
164
165   // There should be no tokens after the directive, but we allow them as an
166   // extension.
167   while (Tmp.is(tok::comment))  // Skip comments in -C mode.
168     LexUnexpandedToken(Tmp);
169
170   if (Tmp.isNot(tok::eod)) {
171     // Add a fixit in GNU/C99/C++ mode.  Don't offer a fixit for strict-C89,
172     // or if this is a macro-style preprocessing directive, because it is more
173     // trouble than it is worth to insert /**/ and check that there is no /**/
174     // in the range also.
175     FixItHint Hint;
176     if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
177         !CurTokenLexer)
178       Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
179     Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
180     DiscardUntilEndOfDirective();
181   }
182 }
183
184
185
186 /// SkipExcludedConditionalBlock - We just read a #if or related directive and
187 /// decided that the subsequent tokens are in the #if'd out portion of the
188 /// file.  Lex the rest of the file, until we see an #endif.  If
189 /// FoundNonSkipPortion is true, then we have already emitted code for part of
190 /// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
191 /// is true, then #else directives are ok, if not, then we have already seen one
192 /// so a #else directive is a duplicate.  When this returns, the caller can lex
193 /// the first valid token.
194 void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
195                                                 bool FoundNonSkipPortion,
196                                                 bool FoundElse,
197                                                 SourceLocation ElseLoc) {
198   ++NumSkipped;
199   assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
200
201   CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
202                                  FoundNonSkipPortion, FoundElse);
203
204   if (CurPTHLexer) {
205     PTHSkipExcludedConditionalBlock();
206     return;
207   }
208
209   // Enter raw mode to disable identifier lookup (and thus macro expansion),
210   // disabling warnings, etc.
211   CurPPLexer->LexingRawMode = true;
212   Token Tok;
213   while (1) {
214     CurLexer->Lex(Tok);
215
216     if (Tok.is(tok::code_completion)) {
217       if (CodeComplete)
218         CodeComplete->CodeCompleteInConditionalExclusion();
219       setCodeCompletionReached();
220       continue;
221     }
222     
223     // If this is the end of the buffer, we have an error.
224     if (Tok.is(tok::eof)) {
225       // Emit errors for each unterminated conditional on the stack, including
226       // the current one.
227       while (!CurPPLexer->ConditionalStack.empty()) {
228         if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
229           Diag(CurPPLexer->ConditionalStack.back().IfLoc,
230                diag::err_pp_unterminated_conditional);
231         CurPPLexer->ConditionalStack.pop_back();
232       }
233
234       // Just return and let the caller lex after this #include.
235       break;
236     }
237
238     // If this token is not a preprocessor directive, just skip it.
239     if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
240       continue;
241
242     // We just parsed a # character at the start of a line, so we're in
243     // directive mode.  Tell the lexer this so any newlines we see will be
244     // converted into an EOD token (this terminates the macro).
245     CurPPLexer->ParsingPreprocessorDirective = true;
246     if (CurLexer) CurLexer->SetCommentRetentionState(false);
247
248
249     // Read the next token, the directive flavor.
250     LexUnexpandedToken(Tok);
251
252     // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
253     // something bogus), skip it.
254     if (Tok.isNot(tok::raw_identifier)) {
255       CurPPLexer->ParsingPreprocessorDirective = false;
256       // Restore comment saving mode.
257       if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
258       continue;
259     }
260
261     // If the first letter isn't i or e, it isn't intesting to us.  We know that
262     // this is safe in the face of spelling differences, because there is no way
263     // to spell an i/e in a strange way that is another letter.  Skipping this
264     // allows us to avoid looking up the identifier info for #define/#undef and
265     // other common directives.
266     const char *RawCharData = Tok.getRawIdentifierData();
267
268     char FirstChar = RawCharData[0];
269     if (FirstChar >= 'a' && FirstChar <= 'z' &&
270         FirstChar != 'i' && FirstChar != 'e') {
271       CurPPLexer->ParsingPreprocessorDirective = false;
272       // Restore comment saving mode.
273       if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
274       continue;
275     }
276
277     // Get the identifier name without trigraphs or embedded newlines.  Note
278     // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
279     // when skipping.
280     char DirectiveBuf[20];
281     StringRef Directive;
282     if (!Tok.needsCleaning() && Tok.getLength() < 20) {
283       Directive = StringRef(RawCharData, Tok.getLength());
284     } else {
285       std::string DirectiveStr = getSpelling(Tok);
286       unsigned IdLen = DirectiveStr.size();
287       if (IdLen >= 20) {
288         CurPPLexer->ParsingPreprocessorDirective = false;
289         // Restore comment saving mode.
290         if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
291         continue;
292       }
293       memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
294       Directive = StringRef(DirectiveBuf, IdLen);
295     }
296
297     if (Directive.startswith("if")) {
298       StringRef Sub = Directive.substr(2);
299       if (Sub.empty() ||   // "if"
300           Sub == "def" ||   // "ifdef"
301           Sub == "ndef") {  // "ifndef"
302         // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
303         // bother parsing the condition.
304         DiscardUntilEndOfDirective();
305         CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
306                                        /*foundnonskip*/false,
307                                        /*foundelse*/false);
308
309         if (Callbacks)
310           Callbacks->Endif();
311       }
312     } else if (Directive[0] == 'e') {
313       StringRef Sub = Directive.substr(1);
314       if (Sub == "ndif") {  // "endif"
315         CheckEndOfDirective("endif");
316         PPConditionalInfo CondInfo;
317         CondInfo.WasSkipping = true; // Silence bogus warning.
318         bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
319         (void)InCond;  // Silence warning in no-asserts mode.
320         assert(!InCond && "Can't be skipping if not in a conditional!");
321
322         // If we popped the outermost skipping block, we're done skipping!
323         if (!CondInfo.WasSkipping)
324           break;
325       } else if (Sub == "lse") { // "else".
326         // #else directive in a skipping conditional.  If not in some other
327         // skipping conditional, and if #else hasn't already been seen, enter it
328         // as a non-skipping conditional.
329         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
330
331         // If this is a #else with a #else before it, report the error.
332         if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
333
334         // Note that we've seen a #else in this conditional.
335         CondInfo.FoundElse = true;
336
337         if (Callbacks)
338           Callbacks->Else();
339
340         // If the conditional is at the top level, and the #if block wasn't
341         // entered, enter the #else block now.
342         if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
343           CondInfo.FoundNonSkip = true;
344           CheckEndOfDirective("else");
345           break;
346         } else {
347           DiscardUntilEndOfDirective();  // C99 6.10p4.
348         }
349       } else if (Sub == "lif") {  // "elif".
350         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
351
352         bool ShouldEnter;
353         const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
354         // If this is in a skipping block or if we're already handled this #if
355         // block, don't bother parsing the condition.
356         if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
357           DiscardUntilEndOfDirective();
358           ShouldEnter = false;
359         } else {
360           // Restore the value of LexingRawMode so that identifiers are
361           // looked up, etc, inside the #elif expression.
362           assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
363           CurPPLexer->LexingRawMode = false;
364           IdentifierInfo *IfNDefMacro = 0;
365           ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
366           CurPPLexer->LexingRawMode = true;
367         }
368         const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
369
370         // If this is a #elif with a #else before it, report the error.
371         if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
372
373         if (Callbacks)
374           Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
375
376         // If this condition is true, enter it!
377         if (ShouldEnter) {
378           CondInfo.FoundNonSkip = true;
379           break;
380         }
381       }
382     }
383
384     CurPPLexer->ParsingPreprocessorDirective = false;
385     // Restore comment saving mode.
386     if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
387   }
388
389   // Finally, if we are out of the conditional (saw an #endif or ran off the end
390   // of the file, just stop skipping and return to lexing whatever came after
391   // the #if block.
392   CurPPLexer->LexingRawMode = false;
393
394   if (Callbacks) {
395     SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
396     Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
397   }
398 }
399
400 void Preprocessor::PTHSkipExcludedConditionalBlock() {
401
402   while (1) {
403     assert(CurPTHLexer);
404     assert(CurPTHLexer->LexingRawMode == false);
405
406     // Skip to the next '#else', '#elif', or #endif.
407     if (CurPTHLexer->SkipBlock()) {
408       // We have reached an #endif.  Both the '#' and 'endif' tokens
409       // have been consumed by the PTHLexer.  Just pop off the condition level.
410       PPConditionalInfo CondInfo;
411       bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
412       (void)InCond;  // Silence warning in no-asserts mode.
413       assert(!InCond && "Can't be skipping if not in a conditional!");
414       break;
415     }
416
417     // We have reached a '#else' or '#elif'.  Lex the next token to get
418     // the directive flavor.
419     Token Tok;
420     LexUnexpandedToken(Tok);
421
422     // We can actually look up the IdentifierInfo here since we aren't in
423     // raw mode.
424     tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
425
426     if (K == tok::pp_else) {
427       // #else: Enter the else condition.  We aren't in a nested condition
428       //  since we skip those. We're always in the one matching the last
429       //  blocked we skipped.
430       PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
431       // Note that we've seen a #else in this conditional.
432       CondInfo.FoundElse = true;
433
434       // If the #if block wasn't entered then enter the #else block now.
435       if (!CondInfo.FoundNonSkip) {
436         CondInfo.FoundNonSkip = true;
437
438         // Scan until the eod token.
439         CurPTHLexer->ParsingPreprocessorDirective = true;
440         DiscardUntilEndOfDirective();
441         CurPTHLexer->ParsingPreprocessorDirective = false;
442
443         break;
444       }
445
446       // Otherwise skip this block.
447       continue;
448     }
449
450     assert(K == tok::pp_elif);
451     PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
452
453     // If this is a #elif with a #else before it, report the error.
454     if (CondInfo.FoundElse)
455       Diag(Tok, diag::pp_err_elif_after_else);
456
457     // If this is in a skipping block or if we're already handled this #if
458     // block, don't bother parsing the condition.  We just skip this block.
459     if (CondInfo.FoundNonSkip)
460       continue;
461
462     // Evaluate the condition of the #elif.
463     IdentifierInfo *IfNDefMacro = 0;
464     CurPTHLexer->ParsingPreprocessorDirective = true;
465     bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
466     CurPTHLexer->ParsingPreprocessorDirective = false;
467
468     // If this condition is true, enter it!
469     if (ShouldEnter) {
470       CondInfo.FoundNonSkip = true;
471       break;
472     }
473
474     // Otherwise, skip this block and go to the next one.
475     continue;
476   }
477 }
478
479 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
480 /// return null on failure.  isAngled indicates whether the file reference is
481 /// for system #include's or not (i.e. using <> instead of "").
482 const FileEntry *Preprocessor::LookupFile(
483     StringRef Filename,
484     bool isAngled,
485     const DirectoryLookup *FromDir,
486     const DirectoryLookup *&CurDir,
487     SmallVectorImpl<char> *SearchPath,
488     SmallVectorImpl<char> *RelativePath,
489     StringRef *SuggestedModule) {
490   // If the header lookup mechanism may be relative to the current file, pass in
491   // info about where the current file is.
492   const FileEntry *CurFileEnt = 0;
493   if (!FromDir) {
494     FileID FID = getCurrentFileLexer()->getFileID();
495     CurFileEnt = SourceMgr.getFileEntryForID(FID);
496
497     // If there is no file entry associated with this file, it must be the
498     // predefines buffer.  Any other file is not lexed with a normal lexer, so
499     // it won't be scanned for preprocessor directives.   If we have the
500     // predefines buffer, resolve #include references (which come from the
501     // -include command line argument) as if they came from the main file, this
502     // affects file lookup etc.
503     if (CurFileEnt == 0) {
504       FID = SourceMgr.getMainFileID();
505       CurFileEnt = SourceMgr.getFileEntryForID(FID);
506     }
507   }
508
509   // Do a standard file entry lookup.
510   CurDir = CurDirLookup;
511   const FileEntry *FE = HeaderInfo.LookupFile(
512       Filename, isAngled, FromDir, CurDir, CurFileEnt,
513       SearchPath, RelativePath, SuggestedModule);
514   if (FE) return FE;
515
516   // Otherwise, see if this is a subframework header.  If so, this is relative
517   // to one of the headers on the #include stack.  Walk the list of the current
518   // headers on the #include stack and pass them to HeaderInfo.
519   // FIXME: SuggestedModule!
520   if (IsFileLexer()) {
521     if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
522       if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
523                                                     SearchPath, RelativePath)))
524         return FE;
525   }
526
527   for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
528     IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
529     if (IsFileLexer(ISEntry)) {
530       if ((CurFileEnt =
531            SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
532         if ((FE = HeaderInfo.LookupSubframeworkHeader(
533                 Filename, CurFileEnt, SearchPath, RelativePath)))
534           return FE;
535     }
536   }
537
538   // Otherwise, we really couldn't find the file.
539   return 0;
540 }
541
542
543 //===----------------------------------------------------------------------===//
544 // Preprocessor Directive Handling.
545 //===----------------------------------------------------------------------===//
546
547 /// HandleDirective - This callback is invoked when the lexer sees a # token
548 /// at the start of a line.  This consumes the directive, modifies the
549 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
550 /// read is the correct one.
551 void Preprocessor::HandleDirective(Token &Result) {
552   // FIXME: Traditional: # with whitespace before it not recognized by K&R?
553
554   // We just parsed a # character at the start of a line, so we're in directive
555   // mode.  Tell the lexer this so any newlines we see will be converted into an
556   // EOD token (which terminates the directive).
557   CurPPLexer->ParsingPreprocessorDirective = true;
558
559   ++NumDirectives;
560
561   // We are about to read a token.  For the multiple-include optimization FA to
562   // work, we have to remember if we had read any tokens *before* this
563   // pp-directive.
564   bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
565
566   // Save the '#' token in case we need to return it later.
567   Token SavedHash = Result;
568
569   // Read the next token, the directive flavor.  This isn't expanded due to
570   // C99 6.10.3p8.
571   LexUnexpandedToken(Result);
572
573   // C99 6.10.3p11: Is this preprocessor directive in macro invocation?  e.g.:
574   //   #define A(x) #x
575   //   A(abc
576   //     #warning blah
577   //   def)
578   // If so, the user is relying on non-portable behavior, emit a diagnostic.
579   if (InMacroArgs)
580     Diag(Result, diag::ext_embedded_directive);
581
582 TryAgain:
583   switch (Result.getKind()) {
584   case tok::eod:
585     return;   // null directive.
586   case tok::comment:
587     // Handle stuff like "# /*foo*/ define X" in -E -C mode.
588     LexUnexpandedToken(Result);
589     goto TryAgain;
590   case tok::code_completion:
591     if (CodeComplete)
592       CodeComplete->CodeCompleteDirective(
593                                     CurPPLexer->getConditionalStackDepth() > 0);
594     setCodeCompletionReached();
595     return;
596   case tok::numeric_constant:  // # 7  GNU line marker directive.
597     if (getLangOptions().AsmPreprocessor)
598       break;  // # 4 is not a preprocessor directive in .S files.
599     return HandleDigitDirective(Result);
600   default:
601     IdentifierInfo *II = Result.getIdentifierInfo();
602     if (II == 0) break;  // Not an identifier.
603
604     // Ask what the preprocessor keyword ID is.
605     switch (II->getPPKeywordID()) {
606     default: break;
607     // C99 6.10.1 - Conditional Inclusion.
608     case tok::pp_if:
609       return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
610     case tok::pp_ifdef:
611       return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
612     case tok::pp_ifndef:
613       return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
614     case tok::pp_elif:
615       return HandleElifDirective(Result);
616     case tok::pp_else:
617       return HandleElseDirective(Result);
618     case tok::pp_endif:
619       return HandleEndifDirective(Result);
620
621     // C99 6.10.2 - Source File Inclusion.
622     case tok::pp_include:
623       // Handle #include.
624       return HandleIncludeDirective(SavedHash.getLocation(), Result);
625     case tok::pp___include_macros:
626       // Handle -imacros.
627       return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result); 
628
629     // C99 6.10.3 - Macro Replacement.
630     case tok::pp_define:
631       return HandleDefineDirective(Result);
632     case tok::pp_undef:
633       return HandleUndefDirective(Result);
634
635     // C99 6.10.4 - Line Control.
636     case tok::pp_line:
637       return HandleLineDirective(Result);
638
639     // C99 6.10.5 - Error Directive.
640     case tok::pp_error:
641       return HandleUserDiagnosticDirective(Result, false);
642
643     // C99 6.10.6 - Pragma Directive.
644     case tok::pp_pragma:
645       return HandlePragmaDirective(PIK_HashPragma);
646
647     // GNU Extensions.
648     case tok::pp_import:
649       return HandleImportDirective(SavedHash.getLocation(), Result);
650     case tok::pp_include_next:
651       return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
652
653     case tok::pp_warning:
654       Diag(Result, diag::ext_pp_warning_directive);
655       return HandleUserDiagnosticDirective(Result, true);
656     case tok::pp_ident:
657       return HandleIdentSCCSDirective(Result);
658     case tok::pp_sccs:
659       return HandleIdentSCCSDirective(Result);
660     case tok::pp_assert:
661       //isExtension = true;  // FIXME: implement #assert
662       break;
663     case tok::pp_unassert:
664       //isExtension = true;  // FIXME: implement #unassert
665       break;
666         
667     case tok::pp___export_macro__:
668       return HandleMacroExportDirective(Result);
669     }
670     break;
671   }
672
673   // If this is a .S file, treat unknown # directives as non-preprocessor
674   // directives.  This is important because # may be a comment or introduce
675   // various pseudo-ops.  Just return the # token and push back the following
676   // token to be lexed next time.
677   if (getLangOptions().AsmPreprocessor) {
678     Token *Toks = new Token[2];
679     // Return the # and the token after it.
680     Toks[0] = SavedHash;
681     Toks[1] = Result;
682     
683     // If the second token is a hashhash token, then we need to translate it to
684     // unknown so the token lexer doesn't try to perform token pasting.
685     if (Result.is(tok::hashhash))
686       Toks[1].setKind(tok::unknown);
687     
688     // Enter this token stream so that we re-lex the tokens.  Make sure to
689     // enable macro expansion, in case the token after the # is an identifier
690     // that is expanded.
691     EnterTokenStream(Toks, 2, false, true);
692     return;
693   }
694
695   // If we reached here, the preprocessing token is not valid!
696   Diag(Result, diag::err_pp_invalid_directive);
697
698   // Read the rest of the PP line.
699   DiscardUntilEndOfDirective();
700
701   // Okay, we're done parsing the directive.
702 }
703
704 /// GetLineValue - Convert a numeric token into an unsigned value, emitting
705 /// Diagnostic DiagID if it is invalid, and returning the value in Val.
706 static bool GetLineValue(Token &DigitTok, unsigned &Val,
707                          unsigned DiagID, Preprocessor &PP) {
708   if (DigitTok.isNot(tok::numeric_constant)) {
709     PP.Diag(DigitTok, DiagID);
710
711     if (DigitTok.isNot(tok::eod))
712       PP.DiscardUntilEndOfDirective();
713     return true;
714   }
715
716   llvm::SmallString<64> IntegerBuffer;
717   IntegerBuffer.resize(DigitTok.getLength());
718   const char *DigitTokBegin = &IntegerBuffer[0];
719   bool Invalid = false;
720   unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
721   if (Invalid)
722     return true;
723   
724   // Verify that we have a simple digit-sequence, and compute the value.  This
725   // is always a simple digit string computed in decimal, so we do this manually
726   // here.
727   Val = 0;
728   for (unsigned i = 0; i != ActualLength; ++i) {
729     if (!isdigit(DigitTokBegin[i])) {
730       PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
731               diag::err_pp_line_digit_sequence);
732       PP.DiscardUntilEndOfDirective();
733       return true;
734     }
735
736     unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
737     if (NextVal < Val) { // overflow.
738       PP.Diag(DigitTok, DiagID);
739       PP.DiscardUntilEndOfDirective();
740       return true;
741     }
742     Val = NextVal;
743   }
744
745   // Reject 0, this is needed both by #line numbers and flags.
746   if (Val == 0) {
747     PP.Diag(DigitTok, DiagID);
748     PP.DiscardUntilEndOfDirective();
749     return true;
750   }
751
752   if (DigitTokBegin[0] == '0')
753     PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
754
755   return false;
756 }
757
758 /// HandleLineDirective - Handle #line directive: C99 6.10.4.  The two
759 /// acceptable forms are:
760 ///   # line digit-sequence
761 ///   # line digit-sequence "s-char-sequence"
762 void Preprocessor::HandleLineDirective(Token &Tok) {
763   // Read the line # and string argument.  Per C99 6.10.4p5, these tokens are
764   // expanded.
765   Token DigitTok;
766   Lex(DigitTok);
767
768   // Validate the number and convert it to an unsigned.
769   unsigned LineNo;
770   if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
771     return;
772
773   // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
774   // number greater than 2147483647".  C90 requires that the line # be <= 32767.
775   unsigned LineLimit = 32768U;
776   if (Features.C99 || Features.CPlusPlus0x)
777     LineLimit = 2147483648U;
778   if (LineNo >= LineLimit)
779     Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
780   else if (Features.CPlusPlus0x && LineNo >= 32768U)
781     Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
782
783   int FilenameID = -1;
784   Token StrTok;
785   Lex(StrTok);
786
787   // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
788   // string followed by eod.
789   if (StrTok.is(tok::eod))
790     ; // ok
791   else if (StrTok.isNot(tok::string_literal)) {
792     Diag(StrTok, diag::err_pp_line_invalid_filename);
793     DiscardUntilEndOfDirective();
794     return;
795   } else {
796     // Parse and validate the string, converting it into a unique ID.
797     StringLiteralParser Literal(&StrTok, 1, *this);
798     assert(Literal.isAscii() && "Didn't allow wide strings in");
799     if (Literal.hadError)
800       return DiscardUntilEndOfDirective();
801     if (Literal.Pascal) {
802       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
803       return DiscardUntilEndOfDirective();
804     }
805     FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
806
807     // Verify that there is nothing after the string, other than EOD.  Because
808     // of C99 6.10.4p5, macros that expand to empty tokens are ok.
809     CheckEndOfDirective("line", true);
810   }
811
812   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
813
814   if (Callbacks)
815     Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
816                            PPCallbacks::RenameFile,
817                            SrcMgr::C_User);
818 }
819
820 /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
821 /// marker directive.
822 static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
823                                 bool &IsSystemHeader, bool &IsExternCHeader,
824                                 Preprocessor &PP) {
825   unsigned FlagVal;
826   Token FlagTok;
827   PP.Lex(FlagTok);
828   if (FlagTok.is(tok::eod)) return false;
829   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
830     return true;
831
832   if (FlagVal == 1) {
833     IsFileEntry = true;
834
835     PP.Lex(FlagTok);
836     if (FlagTok.is(tok::eod)) return false;
837     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
838       return true;
839   } else if (FlagVal == 2) {
840     IsFileExit = true;
841
842     SourceManager &SM = PP.getSourceManager();
843     // If we are leaving the current presumed file, check to make sure the
844     // presumed include stack isn't empty!
845     FileID CurFileID =
846       SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
847     PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
848     if (PLoc.isInvalid())
849       return true;
850     
851     // If there is no include loc (main file) or if the include loc is in a
852     // different physical file, then we aren't in a "1" line marker flag region.
853     SourceLocation IncLoc = PLoc.getIncludeLoc();
854     if (IncLoc.isInvalid() ||
855         SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
856       PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
857       PP.DiscardUntilEndOfDirective();
858       return true;
859     }
860
861     PP.Lex(FlagTok);
862     if (FlagTok.is(tok::eod)) return false;
863     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
864       return true;
865   }
866
867   // We must have 3 if there are still flags.
868   if (FlagVal != 3) {
869     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
870     PP.DiscardUntilEndOfDirective();
871     return true;
872   }
873
874   IsSystemHeader = true;
875
876   PP.Lex(FlagTok);
877   if (FlagTok.is(tok::eod)) return false;
878   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
879     return true;
880
881   // We must have 4 if there is yet another flag.
882   if (FlagVal != 4) {
883     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
884     PP.DiscardUntilEndOfDirective();
885     return true;
886   }
887
888   IsExternCHeader = true;
889
890   PP.Lex(FlagTok);
891   if (FlagTok.is(tok::eod)) return false;
892
893   // There are no more valid flags here.
894   PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
895   PP.DiscardUntilEndOfDirective();
896   return true;
897 }
898
899 /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
900 /// one of the following forms:
901 ///
902 ///     # 42
903 ///     # 42 "file" ('1' | '2')?
904 ///     # 42 "file" ('1' | '2')? '3' '4'?
905 ///
906 void Preprocessor::HandleDigitDirective(Token &DigitTok) {
907   // Validate the number and convert it to an unsigned.  GNU does not have a
908   // line # limit other than it fit in 32-bits.
909   unsigned LineNo;
910   if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
911                    *this))
912     return;
913
914   Token StrTok;
915   Lex(StrTok);
916
917   bool IsFileEntry = false, IsFileExit = false;
918   bool IsSystemHeader = false, IsExternCHeader = false;
919   int FilenameID = -1;
920
921   // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
922   // string followed by eod.
923   if (StrTok.is(tok::eod))
924     ; // ok
925   else if (StrTok.isNot(tok::string_literal)) {
926     Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
927     return DiscardUntilEndOfDirective();
928   } else {
929     // Parse and validate the string, converting it into a unique ID.
930     StringLiteralParser Literal(&StrTok, 1, *this);
931     assert(Literal.isAscii() && "Didn't allow wide strings in");
932     if (Literal.hadError)
933       return DiscardUntilEndOfDirective();
934     if (Literal.Pascal) {
935       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
936       return DiscardUntilEndOfDirective();
937     }
938     FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
939
940     // If a filename was present, read any flags that are present.
941     if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
942                             IsSystemHeader, IsExternCHeader, *this))
943       return;
944   }
945
946   // Create a line note with this information.
947   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
948                         IsFileEntry, IsFileExit,
949                         IsSystemHeader, IsExternCHeader);
950
951   // If the preprocessor has callbacks installed, notify them of the #line
952   // change.  This is used so that the line marker comes out in -E mode for
953   // example.
954   if (Callbacks) {
955     PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
956     if (IsFileEntry)
957       Reason = PPCallbacks::EnterFile;
958     else if (IsFileExit)
959       Reason = PPCallbacks::ExitFile;
960     SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
961     if (IsExternCHeader)
962       FileKind = SrcMgr::C_ExternCSystem;
963     else if (IsSystemHeader)
964       FileKind = SrcMgr::C_System;
965
966     Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
967   }
968 }
969
970
971 /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
972 ///
973 void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
974                                                  bool isWarning) {
975   // PTH doesn't emit #warning or #error directives.
976   if (CurPTHLexer)
977     return CurPTHLexer->DiscardToEndOfLine();
978
979   // Read the rest of the line raw.  We do this because we don't want macros
980   // to be expanded and we don't require that the tokens be valid preprocessing
981   // tokens.  For example, this is allowed: "#warning `   'foo".  GCC does
982   // collapse multiple consequtive white space between tokens, but this isn't
983   // specified by the standard.
984   std::string Message = CurLexer->ReadToEndOfLine();
985   if (isWarning)
986     Diag(Tok, diag::pp_hash_warning) << Message;
987   else
988     Diag(Tok, diag::err_pp_hash_error) << Message;
989 }
990
991 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
992 ///
993 void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
994   // Yes, this directive is an extension.
995   Diag(Tok, diag::ext_pp_ident_directive);
996
997   // Read the string argument.
998   Token StrTok;
999   Lex(StrTok);
1000
1001   // If the token kind isn't a string, it's a malformed directive.
1002   if (StrTok.isNot(tok::string_literal) &&
1003       StrTok.isNot(tok::wide_string_literal)) {
1004     Diag(StrTok, diag::err_pp_malformed_ident);
1005     if (StrTok.isNot(tok::eod))
1006       DiscardUntilEndOfDirective();
1007     return;
1008   }
1009
1010   // Verify that there is nothing after the string, other than EOD.
1011   CheckEndOfDirective("ident");
1012
1013   if (Callbacks) {
1014     bool Invalid = false;
1015     std::string Str = getSpelling(StrTok, &Invalid);
1016     if (!Invalid)
1017       Callbacks->Ident(Tok.getLocation(), Str);
1018   }
1019 }
1020
1021 /// \brief Handle a #__export_macro__ directive.
1022 void Preprocessor::HandleMacroExportDirective(Token &Tok) {
1023   Token MacroNameTok;
1024   ReadMacroName(MacroNameTok, 2);
1025   
1026   // Error reading macro name?  If so, diagnostic already issued.
1027   if (MacroNameTok.is(tok::eod))
1028     return;
1029
1030   // Check to see if this is the last token on the #__export_macro__ line.
1031   CheckEndOfDirective("__export_macro__");
1032
1033   // Okay, we finally have a valid identifier to undef.
1034   MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1035   
1036   // If the macro is not defined, this is an error.
1037   if (MI == 0) {
1038     Diag(MacroNameTok, diag::err_pp_export_non_macro)
1039       << MacroNameTok.getIdentifierInfo();
1040     return;
1041   }
1042   
1043   // Note that this macro has now been exported.
1044   MI->setExportLocation(MacroNameTok.getLocation());
1045   
1046   // If this macro definition came from a PCH file, mark it
1047   // as having changed since serialization.
1048   if (MI->isFromAST())
1049     MI->setChangedAfterLoad();
1050 }
1051
1052 //===----------------------------------------------------------------------===//
1053 // Preprocessor Include Directive Handling.
1054 //===----------------------------------------------------------------------===//
1055
1056 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1057 /// checked and spelled filename, e.g. as an operand of #include. This returns
1058 /// true if the input filename was in <>'s or false if it were in ""'s.  The
1059 /// caller is expected to provide a buffer that is large enough to hold the
1060 /// spelling of the filename, but is also expected to handle the case when
1061 /// this method decides to use a different buffer.
1062 bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
1063                                               StringRef &Buffer) {
1064   // Get the text form of the filename.
1065   assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1066
1067   // Make sure the filename is <x> or "x".
1068   bool isAngled;
1069   if (Buffer[0] == '<') {
1070     if (Buffer.back() != '>') {
1071       Diag(Loc, diag::err_pp_expects_filename);
1072       Buffer = StringRef();
1073       return true;
1074     }
1075     isAngled = true;
1076   } else if (Buffer[0] == '"') {
1077     if (Buffer.back() != '"') {
1078       Diag(Loc, diag::err_pp_expects_filename);
1079       Buffer = StringRef();
1080       return true;
1081     }
1082     isAngled = false;
1083   } else {
1084     Diag(Loc, diag::err_pp_expects_filename);
1085     Buffer = StringRef();
1086     return true;
1087   }
1088
1089   // Diagnose #include "" as invalid.
1090   if (Buffer.size() <= 2) {
1091     Diag(Loc, diag::err_pp_empty_filename);
1092     Buffer = StringRef();
1093     return true;
1094   }
1095
1096   // Skip the brackets.
1097   Buffer = Buffer.substr(1, Buffer.size()-2);
1098   return isAngled;
1099 }
1100
1101 /// ConcatenateIncludeName - Handle cases where the #include name is expanded
1102 /// from a macro as multiple tokens, which need to be glued together.  This
1103 /// occurs for code like:
1104 ///    #define FOO <a/b.h>
1105 ///    #include FOO
1106 /// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
1107 ///
1108 /// This code concatenates and consumes tokens up to the '>' token.  It returns
1109 /// false if the > was found, otherwise it returns true if it finds and consumes
1110 /// the EOD marker.
1111 bool Preprocessor::ConcatenateIncludeName(
1112                                         llvm::SmallString<128> &FilenameBuffer,
1113                                           SourceLocation &End) {
1114   Token CurTok;
1115
1116   Lex(CurTok);
1117   while (CurTok.isNot(tok::eod)) {
1118     End = CurTok.getLocation();
1119     
1120     // FIXME: Provide code completion for #includes.
1121     if (CurTok.is(tok::code_completion)) {
1122       setCodeCompletionReached();
1123       Lex(CurTok);
1124       continue;
1125     }
1126
1127     // Append the spelling of this token to the buffer. If there was a space
1128     // before it, add it now.
1129     if (CurTok.hasLeadingSpace())
1130       FilenameBuffer.push_back(' ');
1131
1132     // Get the spelling of the token, directly into FilenameBuffer if possible.
1133     unsigned PreAppendSize = FilenameBuffer.size();
1134     FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
1135
1136     const char *BufPtr = &FilenameBuffer[PreAppendSize];
1137     unsigned ActualLen = getSpelling(CurTok, BufPtr);
1138
1139     // If the token was spelled somewhere else, copy it into FilenameBuffer.
1140     if (BufPtr != &FilenameBuffer[PreAppendSize])
1141       memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
1142
1143     // Resize FilenameBuffer to the correct size.
1144     if (CurTok.getLength() != ActualLen)
1145       FilenameBuffer.resize(PreAppendSize+ActualLen);
1146
1147     // If we found the '>' marker, return success.
1148     if (CurTok.is(tok::greater))
1149       return false;
1150
1151     Lex(CurTok);
1152   }
1153
1154   // If we hit the eod marker, emit an error and return true so that the caller
1155   // knows the EOD has been read.
1156   Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
1157   return true;
1158 }
1159
1160 /// HandleIncludeDirective - The "#include" tokens have just been read, read the
1161 /// file to be included from the lexer, then include it!  This is a common
1162 /// routine with functionality shared between #include, #include_next and
1163 /// #import.  LookupFrom is set when this is a #include_next directive, it
1164 /// specifies the file to start searching from.
1165 void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc, 
1166                                           Token &IncludeTok,
1167                                           const DirectoryLookup *LookupFrom,
1168                                           bool isImport) {
1169
1170   Token FilenameTok;
1171   CurPPLexer->LexIncludeFilename(FilenameTok);
1172
1173   // Reserve a buffer to get the spelling.
1174   llvm::SmallString<128> FilenameBuffer;
1175   StringRef Filename;
1176   SourceLocation End;
1177   
1178   switch (FilenameTok.getKind()) {
1179   case tok::eod:
1180     // If the token kind is EOD, the error has already been diagnosed.
1181     return;
1182
1183   case tok::angle_string_literal:
1184   case tok::string_literal:
1185     Filename = getSpelling(FilenameTok, FilenameBuffer);
1186     End = FilenameTok.getLocation();
1187     break;
1188
1189   case tok::less:
1190     // This could be a <foo/bar.h> file coming from a macro expansion.  In this
1191     // case, glue the tokens together into FilenameBuffer and interpret those.
1192     FilenameBuffer.push_back('<');
1193     if (ConcatenateIncludeName(FilenameBuffer, End))
1194       return;   // Found <eod> but no ">"?  Diagnostic already emitted.
1195     Filename = FilenameBuffer.str();
1196     break;
1197   default:
1198     Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1199     DiscardUntilEndOfDirective();
1200     return;
1201   }
1202
1203   bool isAngled =
1204     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
1205   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1206   // error.
1207   if (Filename.empty()) {
1208     DiscardUntilEndOfDirective();
1209     return;
1210   }
1211
1212   // Verify that there is nothing after the filename, other than EOD.  Note that
1213   // we allow macros that expand to nothing after the filename, because this
1214   // falls into the category of "#include pp-tokens new-line" specified in
1215   // C99 6.10.2p4.
1216   CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1217
1218   // Check that we don't have infinite #include recursion.
1219   if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
1220     Diag(FilenameTok, diag::err_pp_include_too_deep);
1221     return;
1222   }
1223
1224   // Complain about attempts to #include files in an audit pragma.
1225   if (PragmaARCCFCodeAuditedLoc.isValid()) {
1226     Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
1227     Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
1228
1229     // Immediately leave the pragma.
1230     PragmaARCCFCodeAuditedLoc = SourceLocation();
1231   }
1232
1233   // Search include directories.
1234   const DirectoryLookup *CurDir;
1235   llvm::SmallString<1024> SearchPath;
1236   llvm::SmallString<1024> RelativePath;
1237   // We get the raw path only if we have 'Callbacks' to which we later pass
1238   // the path.
1239   StringRef SuggestedModule;
1240   const FileEntry *File = LookupFile(
1241       Filename, isAngled, LookupFrom, CurDir,
1242       Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
1243       AutoModuleImport? &SuggestedModule : 0);
1244
1245   // If we are supposed to import a module rather than including the header,
1246   // do so now.
1247   if (!SuggestedModule.empty()) {
1248     TheModuleLoader.loadModule(IncludeTok.getLocation(),
1249                                Identifiers.get(SuggestedModule),
1250                                FilenameTok.getLocation());
1251     return;
1252   }
1253   
1254   // Notify the callback object that we've seen an inclusion directive.
1255   if (Callbacks)
1256     Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
1257                                   End, SearchPath, RelativePath);
1258
1259   if (File == 0) {
1260     if (!SuppressIncludeNotFoundError)
1261       Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
1262     return;
1263   }
1264
1265   // The #included file will be considered to be a system header if either it is
1266   // in a system include directory, or if the #includer is a system include
1267   // header.
1268   SrcMgr::CharacteristicKind FileCharacter =
1269     std::max(HeaderInfo.getFileDirFlavor(File),
1270              SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
1271
1272   // Ask HeaderInfo if we should enter this #include file.  If not, #including
1273   // this file will have no effect.
1274   if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1275     if (Callbacks)
1276       Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
1277     return;
1278   }
1279
1280   // Look up the file, create a File ID for it.
1281   FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
1282                                       FileCharacter);
1283   assert(!FID.isInvalid() && "Expected valid file ID");
1284
1285   // Finally, if all is good, enter the new file!
1286   EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
1287 }
1288
1289 /// HandleIncludeNextDirective - Implements #include_next.
1290 ///
1291 void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
1292                                               Token &IncludeNextTok) {
1293   Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1294
1295   // #include_next is like #include, except that we start searching after
1296   // the current found directory.  If we can't do this, issue a
1297   // diagnostic.
1298   const DirectoryLookup *Lookup = CurDirLookup;
1299   if (isInPrimaryFile()) {
1300     Lookup = 0;
1301     Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1302   } else if (Lookup == 0) {
1303     Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1304   } else {
1305     // Start looking up in the next directory.
1306     ++Lookup;
1307   }
1308
1309   return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
1310 }
1311
1312 /// HandleImportDirective - Implements #import.
1313 ///
1314 void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
1315                                          Token &ImportTok) {
1316   if (!Features.ObjC1)  // #import is standard for ObjC.
1317     Diag(ImportTok, diag::ext_pp_import_directive);
1318
1319   return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
1320 }
1321
1322 /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
1323 /// pseudo directive in the predefines buffer.  This handles it by sucking all
1324 /// tokens through the preprocessor and discarding them (only keeping the side
1325 /// effects on the preprocessor).
1326 void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
1327                                                 Token &IncludeMacrosTok) {
1328   // This directive should only occur in the predefines buffer.  If not, emit an
1329   // error and reject it.
1330   SourceLocation Loc = IncludeMacrosTok.getLocation();
1331   if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
1332     Diag(IncludeMacrosTok.getLocation(),
1333          diag::pp_include_macros_out_of_predefines);
1334     DiscardUntilEndOfDirective();
1335     return;
1336   }
1337
1338   // Treat this as a normal #include for checking purposes.  If this is
1339   // successful, it will push a new lexer onto the include stack.
1340   HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
1341
1342   Token TmpTok;
1343   do {
1344     Lex(TmpTok);
1345     assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
1346   } while (TmpTok.isNot(tok::hashhash));
1347 }
1348
1349 //===----------------------------------------------------------------------===//
1350 // Preprocessor Macro Directive Handling.
1351 //===----------------------------------------------------------------------===//
1352
1353 /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1354 /// definition has just been read.  Lex the rest of the arguments and the
1355 /// closing ), updating MI with what we learn.  Return true if an error occurs
1356 /// parsing the arg list.
1357 bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
1358   SmallVector<IdentifierInfo*, 32> Arguments;
1359
1360   Token Tok;
1361   while (1) {
1362     LexUnexpandedToken(Tok);
1363     switch (Tok.getKind()) {
1364     case tok::r_paren:
1365       // Found the end of the argument list.
1366       if (Arguments.empty())  // #define FOO()
1367         return false;
1368       // Otherwise we have #define FOO(A,)
1369       Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1370       return true;
1371     case tok::ellipsis:  // #define X(... -> C99 varargs
1372       if (!Features.C99)
1373         Diag(Tok, Features.CPlusPlus0x ? 
1374              diag::warn_cxx98_compat_variadic_macro :
1375              diag::ext_variadic_macro);
1376
1377       // Lex the token after the identifier.
1378       LexUnexpandedToken(Tok);
1379       if (Tok.isNot(tok::r_paren)) {
1380         Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1381         return true;
1382       }
1383       // Add the __VA_ARGS__ identifier as an argument.
1384       Arguments.push_back(Ident__VA_ARGS__);
1385       MI->setIsC99Varargs();
1386       MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1387       return false;
1388     case tok::eod:  // #define X(
1389       Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1390       return true;
1391     default:
1392       // Handle keywords and identifiers here to accept things like
1393       // #define Foo(for) for.
1394       IdentifierInfo *II = Tok.getIdentifierInfo();
1395       if (II == 0) {
1396         // #define X(1
1397         Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1398         return true;
1399       }
1400
1401       // If this is already used as an argument, it is used multiple times (e.g.
1402       // #define X(A,A.
1403       if (std::find(Arguments.begin(), Arguments.end(), II) !=
1404           Arguments.end()) {  // C99 6.10.3p6
1405         Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
1406         return true;
1407       }
1408
1409       // Add the argument to the macro info.
1410       Arguments.push_back(II);
1411
1412       // Lex the token after the identifier.
1413       LexUnexpandedToken(Tok);
1414
1415       switch (Tok.getKind()) {
1416       default:          // #define X(A B
1417         Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1418         return true;
1419       case tok::r_paren: // #define X(A)
1420         MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1421         return false;
1422       case tok::comma:  // #define X(A,
1423         break;
1424       case tok::ellipsis:  // #define X(A... -> GCC extension
1425         // Diagnose extension.
1426         Diag(Tok, diag::ext_named_variadic_macro);
1427
1428         // Lex the token after the identifier.
1429         LexUnexpandedToken(Tok);
1430         if (Tok.isNot(tok::r_paren)) {
1431           Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1432           return true;
1433         }
1434
1435         MI->setIsGNUVarargs();
1436         MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
1437         return false;
1438       }
1439     }
1440   }
1441 }
1442
1443 /// HandleDefineDirective - Implements #define.  This consumes the entire macro
1444 /// line then lets the caller lex the next real token.
1445 void Preprocessor::HandleDefineDirective(Token &DefineTok) {
1446   ++NumDefined;
1447
1448   Token MacroNameTok;
1449   ReadMacroName(MacroNameTok, 1);
1450
1451   // Error reading macro name?  If so, diagnostic already issued.
1452   if (MacroNameTok.is(tok::eod))
1453     return;
1454
1455   Token LastTok = MacroNameTok;
1456
1457   // If we are supposed to keep comments in #defines, reenable comment saving
1458   // mode.
1459   if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
1460
1461   // Create the new macro.
1462   MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
1463
1464   Token Tok;
1465   LexUnexpandedToken(Tok);
1466
1467   // If this is a function-like macro definition, parse the argument list,
1468   // marking each of the identifiers as being used as macro arguments.  Also,
1469   // check other constraints on the first token of the macro body.
1470   if (Tok.is(tok::eod)) {
1471     // If there is no body to this macro, we have no special handling here.
1472   } else if (Tok.hasLeadingSpace()) {
1473     // This is a normal token with leading space.  Clear the leading space
1474     // marker on the first token to get proper expansion.
1475     Tok.clearFlag(Token::LeadingSpace);
1476   } else if (Tok.is(tok::l_paren)) {
1477     // This is a function-like macro definition.  Read the argument list.
1478     MI->setIsFunctionLike();
1479     if (ReadMacroDefinitionArgList(MI)) {
1480       // Forget about MI.
1481       ReleaseMacroInfo(MI);
1482       // Throw away the rest of the line.
1483       if (CurPPLexer->ParsingPreprocessorDirective)
1484         DiscardUntilEndOfDirective();
1485       return;
1486     }
1487
1488     // If this is a definition of a variadic C99 function-like macro, not using
1489     // the GNU named varargs extension, enabled __VA_ARGS__.
1490
1491     // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1492     // This gets unpoisoned where it is allowed.
1493     assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1494     if (MI->isC99Varargs())
1495       Ident__VA_ARGS__->setIsPoisoned(false);
1496
1497     // Read the first token after the arg list for down below.
1498     LexUnexpandedToken(Tok);
1499   } else if (Features.C99 || Features.CPlusPlus0x) {
1500     // C99 requires whitespace between the macro definition and the body.  Emit
1501     // a diagnostic for something like "#define X+".
1502     Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1503   } else {
1504     // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
1505     // first character of a replacement list is not a character required by
1506     // subclause 5.2.1, then there shall be white-space separation between the
1507     // identifier and the replacement list.".  5.2.1 lists this set:
1508     //   "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
1509     // is irrelevant here.
1510     bool isInvalid = false;
1511     if (Tok.is(tok::at)) // @ is not in the list above.
1512       isInvalid = true;
1513     else if (Tok.is(tok::unknown)) {
1514       // If we have an unknown token, it is something strange like "`".  Since
1515       // all of valid characters would have lexed into a single character
1516       // token of some sort, we know this is not a valid case.
1517       isInvalid = true;
1518     }
1519     if (isInvalid)
1520       Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
1521     else
1522       Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
1523   }
1524
1525   if (!Tok.is(tok::eod))
1526     LastTok = Tok;
1527
1528   // Read the rest of the macro body.
1529   if (MI->isObjectLike()) {
1530     // Object-like macros are very simple, just read their body.
1531     while (Tok.isNot(tok::eod)) {
1532       LastTok = Tok;
1533       MI->AddTokenToBody(Tok);
1534       // Get the next token of the macro.
1535       LexUnexpandedToken(Tok);
1536     }
1537
1538   } else {
1539     // Otherwise, read the body of a function-like macro.  While we are at it,
1540     // check C99 6.10.3.2p1: ensure that # operators are followed by macro
1541     // parameters in function-like macro expansions.
1542     while (Tok.isNot(tok::eod)) {
1543       LastTok = Tok;
1544
1545       if (Tok.isNot(tok::hash)) {
1546         MI->AddTokenToBody(Tok);
1547
1548         // Get the next token of the macro.
1549         LexUnexpandedToken(Tok);
1550         continue;
1551       }
1552
1553       // Get the next token of the macro.
1554       LexUnexpandedToken(Tok);
1555
1556       // Check for a valid macro arg identifier.
1557       if (Tok.getIdentifierInfo() == 0 ||
1558           MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1559
1560         // If this is assembler-with-cpp mode, we accept random gibberish after
1561         // the '#' because '#' is often a comment character.  However, change
1562         // the kind of the token to tok::unknown so that the preprocessor isn't
1563         // confused.
1564         if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
1565           LastTok.setKind(tok::unknown);
1566         } else {
1567           Diag(Tok, diag::err_pp_stringize_not_parameter);
1568           ReleaseMacroInfo(MI);
1569
1570           // Disable __VA_ARGS__ again.
1571           Ident__VA_ARGS__->setIsPoisoned(true);
1572           return;
1573         }
1574       }
1575
1576       // Things look ok, add the '#' and param name tokens to the macro.
1577       MI->AddTokenToBody(LastTok);
1578       MI->AddTokenToBody(Tok);
1579       LastTok = Tok;
1580
1581       // Get the next token of the macro.
1582       LexUnexpandedToken(Tok);
1583     }
1584   }
1585
1586
1587   // Disable __VA_ARGS__ again.
1588   Ident__VA_ARGS__->setIsPoisoned(true);
1589
1590   // Check that there is no paste (##) operator at the beginning or end of the
1591   // replacement list.
1592   unsigned NumTokens = MI->getNumTokens();
1593   if (NumTokens != 0) {
1594     if (MI->getReplacementToken(0).is(tok::hashhash)) {
1595       Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
1596       ReleaseMacroInfo(MI);
1597       return;
1598     }
1599     if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
1600       Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
1601       ReleaseMacroInfo(MI);
1602       return;
1603     }
1604   }
1605
1606   MI->setDefinitionEndLoc(LastTok.getLocation());
1607
1608   // Finally, if this identifier already had a macro defined for it, verify that
1609   // the macro bodies are identical and free the old definition.
1610   if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
1611     // It is very common for system headers to have tons of macro redefinitions
1612     // and for warnings to be disabled in system headers.  If this is the case,
1613     // then don't bother calling MacroInfo::isIdenticalTo.
1614     if (!getDiagnostics().getSuppressSystemWarnings() ||
1615         !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
1616       if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
1617         Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1618
1619       // Macros must be identical.  This means all tokens and whitespace
1620       // separation must be the same.  C99 6.10.3.2.
1621       if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
1622           !MI->isIdenticalTo(*OtherMI, *this)) {
1623         Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
1624           << MacroNameTok.getIdentifierInfo();
1625         Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
1626       }
1627     }
1628     if (OtherMI->isWarnIfUnused())
1629       WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
1630     ReleaseMacroInfo(OtherMI);
1631   }
1632
1633   setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
1634
1635   assert(!MI->isUsed());
1636   // If we need warning for not using the macro, add its location in the
1637   // warn-because-unused-macro set. If it gets used it will be removed from set.
1638   if (isInPrimaryFile() && // don't warn for include'd macros.
1639       Diags->getDiagnosticLevel(diag::pp_macro_not_used,
1640           MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
1641     MI->setIsWarnIfUnused(true);
1642     WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
1643   }
1644
1645   // If the callbacks want to know, tell them about the macro definition.
1646   if (Callbacks)
1647     Callbacks->MacroDefined(MacroNameTok, MI);
1648 }
1649
1650 /// HandleUndefDirective - Implements #undef.
1651 ///
1652 void Preprocessor::HandleUndefDirective(Token &UndefTok) {
1653   ++NumUndefined;
1654
1655   Token MacroNameTok;
1656   ReadMacroName(MacroNameTok, 2);
1657
1658   // Error reading macro name?  If so, diagnostic already issued.
1659   if (MacroNameTok.is(tok::eod))
1660     return;
1661
1662   // Check to see if this is the last token on the #undef line.
1663   CheckEndOfDirective("undef");
1664
1665   // Okay, we finally have a valid identifier to undef.
1666   MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
1667
1668   // If the macro is not defined, this is a noop undef, just return.
1669   if (MI == 0) return;
1670
1671   if (!MI->isUsed() && MI->isWarnIfUnused())
1672     Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1673
1674   // If the callbacks want to know, tell them about the macro #undef.
1675   if (Callbacks)
1676     Callbacks->MacroUndefined(MacroNameTok, MI);
1677
1678   if (MI->isWarnIfUnused())
1679     WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1680
1681   // Free macro definition.
1682   ReleaseMacroInfo(MI);
1683   setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
1684 }
1685
1686
1687 //===----------------------------------------------------------------------===//
1688 // Preprocessor Conditional Directive Handling.
1689 //===----------------------------------------------------------------------===//
1690
1691 /// HandleIfdefDirective - Implements the #ifdef/#ifndef directive.  isIfndef is
1692 /// true when this is a #ifndef directive.  ReadAnyTokensBeforeDirective is true
1693 /// if any tokens have been returned or pp-directives activated before this
1694 /// #ifndef has been lexed.
1695 ///
1696 void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
1697                                         bool ReadAnyTokensBeforeDirective) {
1698   ++NumIf;
1699   Token DirectiveTok = Result;
1700
1701   Token MacroNameTok;
1702   ReadMacroName(MacroNameTok);
1703
1704   // Error reading macro name?  If so, diagnostic already issued.
1705   if (MacroNameTok.is(tok::eod)) {
1706     // Skip code until we get to #endif.  This helps with recovery by not
1707     // emitting an error when the #endif is reached.
1708     SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1709                                  /*Foundnonskip*/false, /*FoundElse*/false);
1710     return;
1711   }
1712
1713   // Check to see if this is the last token on the #if[n]def line.
1714   CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
1715
1716   IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
1717   MacroInfo *MI = getMacroInfo(MII);
1718
1719   if (CurPPLexer->getConditionalStackDepth() == 0) {
1720     // If the start of a top-level #ifdef and if the macro is not defined,
1721     // inform MIOpt that this might be the start of a proper include guard.
1722     // Otherwise it is some other form of unknown conditional which we can't
1723     // handle.
1724     if (!ReadAnyTokensBeforeDirective && MI == 0) {
1725       assert(isIfndef && "#ifdef shouldn't reach here");
1726       CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
1727     } else
1728       CurPPLexer->MIOpt.EnterTopLevelConditional();
1729   }
1730
1731   // If there is a macro, process it.
1732   if (MI)  // Mark it used.
1733     markMacroAsUsed(MI);
1734
1735   // Should we include the stuff contained by this directive?
1736   if (!MI == isIfndef) {
1737     // Yes, remember that we are inside a conditional, then lex the next token.
1738     CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
1739                                      /*wasskip*/false, /*foundnonskip*/true,
1740                                      /*foundelse*/false);
1741   } else {
1742     // No, skip the contents of this block.
1743     SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
1744                                  /*Foundnonskip*/false,
1745                                  /*FoundElse*/false);
1746   }
1747
1748   if (Callbacks) {
1749     if (isIfndef)
1750       Callbacks->Ifndef(MacroNameTok);
1751     else
1752       Callbacks->Ifdef(MacroNameTok);
1753   }
1754 }
1755
1756 /// HandleIfDirective - Implements the #if directive.
1757 ///
1758 void Preprocessor::HandleIfDirective(Token &IfToken,
1759                                      bool ReadAnyTokensBeforeDirective) {
1760   ++NumIf;
1761
1762   // Parse and evaluate the conditional expression.
1763   IdentifierInfo *IfNDefMacro = 0;
1764   const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1765   const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
1766   const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
1767
1768   // If this condition is equivalent to #ifndef X, and if this is the first
1769   // directive seen, handle it for the multiple-include optimization.
1770   if (CurPPLexer->getConditionalStackDepth() == 0) {
1771     if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
1772       CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
1773     else
1774       CurPPLexer->MIOpt.EnterTopLevelConditional();
1775   }
1776
1777   // Should we include the stuff contained by this directive?
1778   if (ConditionalTrue) {
1779     // Yes, remember that we are inside a conditional, then lex the next token.
1780     CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
1781                                    /*foundnonskip*/true, /*foundelse*/false);
1782   } else {
1783     // No, skip the contents of this block.
1784     SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
1785                                  /*FoundElse*/false);
1786   }
1787
1788   if (Callbacks)
1789     Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
1790 }
1791
1792 /// HandleEndifDirective - Implements the #endif directive.
1793 ///
1794 void Preprocessor::HandleEndifDirective(Token &EndifToken) {
1795   ++NumEndif;
1796
1797   // Check that this is the whole directive.
1798   CheckEndOfDirective("endif");
1799
1800   PPConditionalInfo CondInfo;
1801   if (CurPPLexer->popConditionalLevel(CondInfo)) {
1802     // No conditionals on the stack: this is an #endif without an #if.
1803     Diag(EndifToken, diag::err_pp_endif_without_if);
1804     return;
1805   }
1806
1807   // If this the end of a top-level #endif, inform MIOpt.
1808   if (CurPPLexer->getConditionalStackDepth() == 0)
1809     CurPPLexer->MIOpt.ExitTopLevelConditional();
1810
1811   assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
1812          "This code should only be reachable in the non-skipping case!");
1813
1814   if (Callbacks)
1815     Callbacks->Endif();
1816 }
1817
1818 /// HandleElseDirective - Implements the #else directive.
1819 ///
1820 void Preprocessor::HandleElseDirective(Token &Result) {
1821   ++NumElse;
1822
1823   // #else directive in a non-skipping conditional... start skipping.
1824   CheckEndOfDirective("else");
1825
1826   PPConditionalInfo CI;
1827   if (CurPPLexer->popConditionalLevel(CI)) {
1828     Diag(Result, diag::pp_err_else_without_if);
1829     return;
1830   }
1831
1832   // If this is a top-level #else, inform the MIOpt.
1833   if (CurPPLexer->getConditionalStackDepth() == 0)
1834     CurPPLexer->MIOpt.EnterTopLevelConditional();
1835
1836   // If this is a #else with a #else before it, report the error.
1837   if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
1838
1839   // Finally, skip the rest of the contents of this block.
1840   SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1841                                /*FoundElse*/true, Result.getLocation());
1842
1843   if (Callbacks)
1844     Callbacks->Else();
1845 }
1846
1847 /// HandleElifDirective - Implements the #elif directive.
1848 ///
1849 void Preprocessor::HandleElifDirective(Token &ElifToken) {
1850   ++NumElse;
1851
1852   // #elif directive in a non-skipping conditional... start skipping.
1853   // We don't care what the condition is, because we will always skip it (since
1854   // the block immediately before it was included).
1855   const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
1856   DiscardUntilEndOfDirective();
1857   const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
1858
1859   PPConditionalInfo CI;
1860   if (CurPPLexer->popConditionalLevel(CI)) {
1861     Diag(ElifToken, diag::pp_err_elif_without_if);
1862     return;
1863   }
1864
1865   // If this is a top-level #elif, inform the MIOpt.
1866   if (CurPPLexer->getConditionalStackDepth() == 0)
1867     CurPPLexer->MIOpt.EnterTopLevelConditional();
1868
1869   // If this is a #elif with a #else before it, report the error.
1870   if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
1871
1872   // Finally, skip the rest of the contents of this block.
1873   SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
1874                                /*FoundElse*/CI.FoundElse,
1875                                ElifToken.getLocation());
1876
1877   if (Callbacks)
1878     Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
1879 }