blob: a594ad9c5d4187a1b53bb8182b45102b4fcd6c3b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner133db8a2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Chris Lattner4b009652007-07-25 00:24:17 +000017// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
26//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/MacroInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031#include "clang/Lex/Pragma.h"
32#include "clang/Lex/ScratchBuffer.h"
Chris Lattner545f39e2009-01-29 05:15:15 +000033#include "clang/Lex/LexDiagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000034#include "clang/Basic/SourceManager.h"
Ted Kremenek40003a72009-02-12 03:26:59 +000035#include "clang/Basic/FileManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000036#include "clang/Basic/TargetInfo.h"
Chris Lattnercbed2992008-10-05 20:40:30 +000037#include "llvm/ADT/APFloat.h"
Chris Lattner4b009652007-07-25 00:24:17 +000038#include "llvm/ADT/SmallVector.h"
39#include "llvm/Support/MemoryBuffer.h"
Ted Kremenekce4c64e2008-01-14 16:44:48 +000040#include "llvm/Support/Streams.h"
Chris Lattner7d6220c2009-03-02 22:20:04 +000041#include <cstdio>
Chris Lattner4b009652007-07-25 00:24:17 +000042using namespace clang;
43
44//===----------------------------------------------------------------------===//
45
Ted Kremenek5ab36b02008-04-17 21:23:07 +000046PreprocessorFactory::~PreprocessorFactory() {}
47
Douglas Gregorab1cef72009-04-10 03:52:48 +000048bool PreprocessorFactory::FinishInitialization(Preprocessor *PP) {
49 return false;
50}
51
Chris Lattner4b009652007-07-25 00:24:17 +000052Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
53 TargetInfo &target, SourceManager &SM,
Ted Kremenekd976c3d2009-01-15 18:47:46 +000054 HeaderSearch &Headers,
55 IdentifierInfoLookup* IILookup)
Chris Lattnerf1e7b792009-03-13 21:17:43 +000056 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
Ted Kremenekd976c3d2009-01-15 18:47:46 +000057 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts, IILookup),
Ted Kremenek94dcef72008-11-19 00:44:06 +000058 CurPPLexer(0), CurDirLookup(0), Callbacks(0) {
Chris Lattner4b009652007-07-25 00:24:17 +000059 ScratchBuf = new ScratchBuffer(SourceMgr);
60
61 // Clear stats.
62 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
63 NumIf = NumElse = NumEndif = 0;
64 NumEnteredSourceFiles = 0;
65 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
66 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
67 MaxIncludeStackDepth = 0;
68 NumSkipped = 0;
69
70 // Default to discarding comments.
71 KeepComments = false;
72 KeepMacroComments = false;
73
74 // Macro expansion is enabled.
75 DisableMacroExpansion = false;
76 InMacroArgs = false;
Chris Lattner5b54ed92008-03-09 02:26:03 +000077 NumCachedTokenLexers = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000078
Argiris Kirtzidisf55b1102008-08-10 13:15:22 +000079 CachedLexPos = 0;
80
Chris Lattner4b009652007-07-25 00:24:17 +000081 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
82 // This gets unpoisoned where it is allowed.
83 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
84
85 // Initialize the pragma handlers.
86 PragmaHandlers = new PragmaNamespace(0);
87 RegisterBuiltinPragmas();
88
89 // Initialize builtin macros like __LINE__ and friends.
90 RegisterBuiltinMacros();
91}
92
93Preprocessor::~Preprocessor() {
Argiris Kirtzidis1370cf12008-08-23 12:12:06 +000094 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
95
Chris Lattner4b009652007-07-25 00:24:17 +000096 while (!IncludeMacroStack.empty()) {
97 delete IncludeMacroStack.back().TheLexer;
Chris Lattner5b54ed92008-03-09 02:26:03 +000098 delete IncludeMacroStack.back().TheTokenLexer;
Chris Lattner4b009652007-07-25 00:24:17 +000099 IncludeMacroStack.pop_back();
100 }
Chris Lattner7a1b0882007-10-07 08:44:20 +0000101
102 // Free any macro definitions.
103 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
104 Macros.begin(), E = Macros.end(); I != E; ++I) {
Ted Kremenek5f9fb3f2008-12-15 19:56:42 +0000105 // We don't need to free the MacroInfo objects directly. These
106 // will be released when the BumpPtrAllocator 'BP' object gets
Ted Kremenek334035f2009-01-19 07:45:44 +0000107 // destroyed. We still need to run the dstor, however, to free
108 // memory alocated by MacroInfo.
Chris Lattner89188b22009-02-20 22:46:43 +0000109 I->second->Destroy(BP);
Chris Lattner7a1b0882007-10-07 08:44:20 +0000110 I->first->setHasMacroDefinition(false);
111 }
Chris Lattner4b009652007-07-25 00:24:17 +0000112
113 // Free any cached macro expanders.
Chris Lattner5b54ed92008-03-09 02:26:03 +0000114 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
115 delete TokenLexerCache[i];
Chris Lattner4b009652007-07-25 00:24:17 +0000116
117 // Release pragma information.
118 delete PragmaHandlers;
119
120 // Delete the scratch buffer info.
121 delete ScratchBuf;
Chris Lattner65829812008-03-14 06:07:05 +0000122
123 delete Callbacks;
Chris Lattner4b009652007-07-25 00:24:17 +0000124}
125
Ted Kremenek40003a72009-02-12 03:26:59 +0000126void Preprocessor::setPTHManager(PTHManager* pm) {
127 PTH.reset(pm);
128 FileMgr.setStatCache(PTH->createStatCache());
129}
130
Chris Lattner4b009652007-07-25 00:24:17 +0000131void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000132 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
133 << getSpelling(Tok) << "'";
Chris Lattner4b009652007-07-25 00:24:17 +0000134
135 if (!DumpFlags) return;
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000136
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000137 llvm::cerr << "\t";
Chris Lattner4b009652007-07-25 00:24:17 +0000138 if (Tok.isAtStartOfLine())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000139 llvm::cerr << " [StartOfLine]";
Chris Lattner4b009652007-07-25 00:24:17 +0000140 if (Tok.hasLeadingSpace())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000141 llvm::cerr << " [LeadingSpace]";
Chris Lattner4b009652007-07-25 00:24:17 +0000142 if (Tok.isExpandDisabled())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000143 llvm::cerr << " [ExpandDisabled]";
Chris Lattner4b009652007-07-25 00:24:17 +0000144 if (Tok.needsCleaning()) {
145 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000146 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
147 << "']";
Chris Lattner4b009652007-07-25 00:24:17 +0000148 }
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000149
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000150 llvm::cerr << "\tLoc=<";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000151 DumpLocation(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000152 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000153}
154
155void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattner836774b2009-01-27 07:57:44 +0000156 Loc.dump(SourceMgr);
Chris Lattner4b009652007-07-25 00:24:17 +0000157}
158
159void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000160 llvm::cerr << "MACRO: ";
Chris Lattner4b009652007-07-25 00:24:17 +0000161 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
162 DumpToken(MI.getReplacementToken(i));
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000163 llvm::cerr << " ";
Chris Lattner4b009652007-07-25 00:24:17 +0000164 }
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000165 llvm::cerr << "\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000166}
167
168void Preprocessor::PrintStats() {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000169 llvm::cerr << "\n*** Preprocessor Stats:\n";
170 llvm::cerr << NumDirectives << " directives found:\n";
171 llvm::cerr << " " << NumDefined << " #define.\n";
172 llvm::cerr << " " << NumUndefined << " #undef.\n";
173 llvm::cerr << " #include/#include_next/#import:\n";
174 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
175 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
176 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
177 llvm::cerr << " " << NumElse << " #else/#elif.\n";
178 llvm::cerr << " " << NumEndif << " #endif.\n";
179 llvm::cerr << " " << NumPragma << " #pragma.\n";
180 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000181
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000182 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
183 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
184 << NumFastMacroExpanded << " on the fast path.\n";
185 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
186 << " token paste (##) operations performed, "
187 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000188}
189
190//===----------------------------------------------------------------------===//
191// Token Spelling
192//===----------------------------------------------------------------------===//
193
194
195/// getSpelling() - Return the 'spelling' of this token. The spelling of a
196/// token are the characters used to represent the token in the source file
197/// after trigraph expansion and escaped-newline folding. In particular, this
198/// wants to get the true, uncanonicalized, spelling of things like digraphs
199/// UCNs, etc.
200std::string Preprocessor::getSpelling(const Token &Tok) const {
201 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Ted Kremenek562db7f2009-01-27 00:01:05 +0000202
Chris Lattner4b009652007-07-25 00:24:17 +0000203 // If this token contains nothing interesting, return it directly.
Ted Kremenek562db7f2009-01-27 00:01:05 +0000204 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000205 if (!Tok.needsCleaning())
206 return std::string(TokStart, TokStart+Tok.getLength());
207
208 std::string Result;
209 Result.reserve(Tok.getLength());
210
211 // Otherwise, hard case, relex the characters into the string.
212 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
213 Ptr != End; ) {
214 unsigned CharSize;
215 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
216 Ptr += CharSize;
217 }
218 assert(Result.size() != unsigned(Tok.getLength()) &&
219 "NeedsCleaning flag set on something that didn't need cleaning!");
220 return Result;
221}
222
223/// getSpelling - This method is used to get the spelling of a token into a
224/// preallocated buffer, instead of as an std::string. The caller is required
225/// to allocate enough space for the token, which is guaranteed to be at least
226/// Tok.getLength() bytes long. The actual length of the token is returned.
227///
228/// Note that this method may do two possible things: it may either fill in
229/// the buffer specified with characters, or it may *change the input pointer*
230/// to point to a constant buffer with the data already in it (avoiding a
231/// copy). The caller is not allowed to modify the returned buffer pointer
232/// if an internal buffer is returned.
233unsigned Preprocessor::getSpelling(const Token &Tok,
234 const char *&Buffer) const {
235 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
236
237 // If this token is an identifier, just return the string from the identifier
238 // table, which is very quick.
239 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
240 Buffer = II->getName();
Chris Lattner9c47fe62009-01-05 19:44:41 +0000241 return II->getLength();
Chris Lattner4b009652007-07-25 00:24:17 +0000242 }
Ted Kremenekd2c849d2009-01-08 02:47:16 +0000243
Chris Lattner4b009652007-07-25 00:24:17 +0000244 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner6ad1f502009-01-26 19:29:26 +0000245 const char *TokStart = 0;
246
247 if (Tok.isLiteral())
248 TokStart = Tok.getLiteralData();
249
250 if (TokStart == 0)
251 TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000252
253 // If this token contains nothing interesting, return it directly.
254 if (!Tok.needsCleaning()) {
255 Buffer = TokStart;
256 return Tok.getLength();
257 }
Chris Lattner6ad1f502009-01-26 19:29:26 +0000258
Chris Lattner4b009652007-07-25 00:24:17 +0000259 // Otherwise, hard case, relex the characters into the string.
260 char *OutBuf = const_cast<char*>(Buffer);
261 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
262 Ptr != End; ) {
263 unsigned CharSize;
264 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
265 Ptr += CharSize;
266 }
267 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
268 "NeedsCleaning flag set on something that didn't need cleaning!");
269
270 return OutBuf-Buffer;
271}
272
Chris Lattner4b009652007-07-25 00:24:17 +0000273/// CreateString - Plop the specified string into a scratch buffer and return a
274/// location for it. If specified, the source location provides a source
275/// location for the token.
Chris Lattner6ad1f502009-01-26 19:29:26 +0000276void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
277 SourceLocation InstantiationLoc) {
278 Tok.setLength(Len);
279
280 const char *DestPtr;
281 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
282
283 if (InstantiationLoc.isValid())
Chris Lattnerbc7a3cb2009-02-15 20:52:18 +0000284 Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
285 InstantiationLoc, Len);
Chris Lattner6ad1f502009-01-26 19:29:26 +0000286 Tok.setLocation(Loc);
287
288 // If this is a literal token, set the pointer data.
289 if (Tok.isLiteral())
290 Tok.setLiteralData(DestPtr);
Chris Lattner4b009652007-07-25 00:24:17 +0000291}
292
293
294/// AdvanceToTokenCharacter - Given a location that specifies the start of a
295/// token, return a new location that specifies a character within the token.
296SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
297 unsigned CharNo) {
Chris Lattner29e840e2009-02-18 18:56:29 +0000298 // If they request the first char of the token, we're trivially done.
Chris Lattner81df8462009-02-18 18:52:52 +0000299 if (CharNo == 0) return TokStart;
Chris Lattner4b009652007-07-25 00:24:17 +0000300
Chris Lattner18c8dc02009-01-16 07:36:28 +0000301 // Figure out how many physical characters away the specified instantiation
Chris Lattner4b009652007-07-25 00:24:17 +0000302 // character is. This needs to take into consideration newlines and
303 // trigraphs.
304 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
305 unsigned PhysOffset = 0;
306
307 // The usual case is that tokens don't contain anything interesting. Skip
308 // over the uninteresting characters. If a token only consists of simple
309 // chars, this method is extremely fast.
310 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
311 ++TokPtr, --CharNo, ++PhysOffset;
312
Chris Lattnerbed5ce72009-01-17 07:57:25 +0000313 // If we have a character that may be a trigraph or escaped newline, use a
Chris Lattner4b009652007-07-25 00:24:17 +0000314 // lexer to parse it correctly.
315 if (CharNo != 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000316 // Skip over characters the remaining characters.
Chris Lattnerbed5ce72009-01-17 07:57:25 +0000317 for (; CharNo; --CharNo) {
318 unsigned Size;
319 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
320 TokPtr += Size;
321 PhysOffset += Size;
322 }
Chris Lattner4b009652007-07-25 00:24:17 +0000323 }
324
325 return TokStart.getFileLocWithOffset(PhysOffset);
326}
327
Douglas Gregor61be3602009-02-27 17:53:17 +0000328/// \brief Computes the source location just past the end of the
329/// token at this source location.
330///
331/// This routine can be used to produce a source location that
332/// points just past the end of the token referenced by \p Loc, and
333/// is generally used when a diagnostic needs to point just after a
334/// token where it expected something different that it received. If
335/// the returned source location would not be meaningful (e.g., if
336/// it points into a macro), this routine returns an invalid
337/// source location.
338SourceLocation Preprocessor::getLocForEndOfToken(SourceLocation Loc) {
339 if (Loc.isInvalid() || !Loc.isFileID())
340 return SourceLocation();
341
342 unsigned Len = Lexer::MeasureTokenLength(Loc, getSourceManager());
343 return AdvanceToTokenCharacter(Loc, Len);
344}
345
346
Chris Lattner4b009652007-07-25 00:24:17 +0000347
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000348//===----------------------------------------------------------------------===//
349// Preprocessor Initialization Methods
350//===----------------------------------------------------------------------===//
351
352// Append a #define line to Buf for Macro. Macro should be of the form XXX,
353// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
354// "#define XXX Y z W". To get a #define with no value, use "XXX=".
355static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
356 const char *Command = "#define ") {
357 Buf.insert(Buf.end(), Command, Command+strlen(Command));
358 if (const char *Equal = strchr(Macro, '=')) {
359 // Turn the = into ' '.
360 Buf.insert(Buf.end(), Macro, Equal);
361 Buf.push_back(' ');
362 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
363 } else {
364 // Push "macroname 1".
365 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
366 Buf.push_back(' ');
367 Buf.push_back('1');
368 }
369 Buf.push_back('\n');
370}
371
Chris Lattnercbed2992008-10-05 20:40:30 +0000372/// PickFP - This is used to pick a value based on the FP semantics of the
373/// specified FP model.
374template <typename T>
375static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
376 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
377 if (Sem == &llvm::APFloat::IEEEsingle)
378 return IEEESingleVal;
379 if (Sem == &llvm::APFloat::IEEEdouble)
380 return IEEEDoubleVal;
381 if (Sem == &llvm::APFloat::x87DoubleExtended)
382 return X87DoubleExtendedVal;
383 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
384 return PPCDoubleDoubleVal;
385}
386
387static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
388 const llvm::fltSemantics *Sem) {
Chris Lattner5c8f64a2008-10-05 21:40:58 +0000389 const char *DenormMin, *Epsilon, *Max, *Min;
390 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
391 "3.64519953188247460253e-4951L",
392 "4.94065645841246544176568792868221e-324L");
393 int Digits = PickFP(Sem, 6, 15, 18, 31);
394 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
395 "1.08420217248550443401e-19L",
396 "4.94065645841246544176568792868221e-324L");
397 int HasInifinity = 1, HasQuietNaN = 1;
398 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
399 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
400 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
401 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
402 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
403 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
404 "3.36210314311209350626e-4932L",
405 "2.00416836000897277799610805135016e-292L");
406 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
407 "1.18973149535723176502e+4932L",
408 "1.79769313486231580793728971405301e+308L");
Chris Lattnercbed2992008-10-05 20:40:30 +0000409
410 char MacroBuf[60];
411 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
412 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner5c8f64a2008-10-05 21:40:58 +0000413 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
414 DefineBuiltinMacro(Buf, MacroBuf);
415 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
416 DefineBuiltinMacro(Buf, MacroBuf);
417 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
418 DefineBuiltinMacro(Buf, MacroBuf);
419 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
420 DefineBuiltinMacro(Buf, MacroBuf);
421 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
422 DefineBuiltinMacro(Buf, MacroBuf);
423 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
424 DefineBuiltinMacro(Buf, MacroBuf);
425 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
426 DefineBuiltinMacro(Buf, MacroBuf);
427 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
428 DefineBuiltinMacro(Buf, MacroBuf);
429 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
430 DefineBuiltinMacro(Buf, MacroBuf);
431 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
432 DefineBuiltinMacro(Buf, MacroBuf);
433 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
434 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner8405e092009-02-05 07:19:24 +0000435 sprintf(MacroBuf, "__%s_HAS_DENORM__=1", Prefix);
436 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattnercbed2992008-10-05 20:40:30 +0000437}
438
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000439
Chris Lattnerd8ed1cf2009-02-06 04:50:25 +0000440/// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
441/// named MacroName with the max value for a type with width 'TypeWidth' a
442/// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
443static void DefineTypeSize(const char *MacroName, unsigned TypeWidth,
444 const char *ValSuffix, bool isSigned,
445 std::vector<char> &Buf) {
446 char MacroBuf[60];
Mike Stump7d614302009-03-07 18:35:41 +0000447 long long MaxVal;
Chris Lattnerd8ed1cf2009-02-06 04:50:25 +0000448 if (isSigned)
449 MaxVal = (1LL << (TypeWidth - 1)) - 1;
450 else
451 MaxVal = ~0LL >> (64-TypeWidth);
452
453 sprintf(MacroBuf, "%s=%llu%s", MacroName, MaxVal, ValSuffix);
454 DefineBuiltinMacro(Buf, MacroBuf);
455}
456
Chris Lattner534234c2009-02-06 05:04:11 +0000457static void DefineType(const char *MacroName, TargetInfo::IntType Ty,
458 std::vector<char> &Buf) {
459 char MacroBuf[60];
460 sprintf(MacroBuf, "%s=%s", MacroName, TargetInfo::getTypeName(Ty));
461 DefineBuiltinMacro(Buf, MacroBuf);
462}
463
464
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000465static void InitializePredefinedMacros(Preprocessor &PP,
466 std::vector<char> &Buf) {
Chris Lattner2ac88e02009-02-06 22:59:26 +0000467 char MacroBuf[60];
Chris Lattnera023ec52008-10-05 19:32:22 +0000468 // Compiler version introspection macros.
469 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
470 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
471
472 // Currently claim to be compatible with GCC 4.2.1-5621.
473 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
474 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
475 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
476 DefineBuiltinMacro(Buf, "__GNUC__=4");
477 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
Chris Lattnere2e869d2009-03-24 16:09:18 +0000478 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 Compatible Clang Compiler\"");
Chris Lattnera023ec52008-10-05 19:32:22 +0000479
480
481 // Initialize language-specific preprocessor defines.
482
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000483 // These should all be defined in the preprocessor according to the
484 // current language configuration.
Steve Naroff19d04012008-12-18 22:37:25 +0000485 if (!PP.getLangOptions().Microsoft)
486 DefineBuiltinMacro(Buf, "__STDC__=1");
Daniel Dunbar20b88022008-12-01 18:55:22 +0000487 if (PP.getLangOptions().AsmPreprocessor)
488 DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000489 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
490 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
491 else if (0) // STDC94 ?
492 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000493
494 // Standard conforming mode?
495 if (!PP.getLangOptions().GNUMode)
496 DefineBuiltinMacro(Buf, "__STRICT_ANSI__=1");
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000497
Anders Carlsson149f2782009-03-15 20:12:13 +0000498 if (PP.getLangOptions().CPlusPlus0x)
499 DefineBuiltinMacro(Buf, "__GXX_EXPERIMENTAL_CXX0X__");
500
Chris Lattnerad30e572009-03-09 21:50:12 +0000501 if (PP.getLangOptions().Freestanding)
502 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=0");
503 else
504 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
505
Daniel Dunbar428e6762008-08-12 00:21:46 +0000506 if (PP.getLangOptions().ObjC1) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000507 DefineBuiltinMacro(Buf, "__OBJC__=1");
Daniel Dunbare079c712009-04-08 03:03:23 +0000508 if (PP.getLangOptions().ObjCNonFragileABI) {
Fariborz Jahanian09110502009-02-16 18:28:48 +0000509 DefineBuiltinMacro(Buf, "__OBJC2__=1");
Daniel Dunbare079c712009-04-08 03:03:23 +0000510 DefineBuiltinMacro(Buf, "OBJC_ZEROCOST_EXCEPTIONS=1");
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000511 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
Daniel Dunbare079c712009-04-08 03:03:23 +0000512 }
Daniel Dunbar428e6762008-08-12 00:21:46 +0000513
Chris Lattner33854aa2009-04-07 04:48:21 +0000514 if (PP.getLangOptions().getGCMode() != LangOptions::NonGC)
Daniel Dunbar428e6762008-08-12 00:21:46 +0000515 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
Chris Lattner33854aa2009-04-07 04:48:21 +0000516
Daniel Dunbar428e6762008-08-12 00:21:46 +0000517 if (PP.getLangOptions().NeXTRuntime)
518 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000519 }
Chris Lattner5edfe012008-10-05 19:44:25 +0000520
Chris Lattnerd5e60992008-10-06 07:43:09 +0000521 // darwin_constant_cfstrings controls this. This is also dependent
522 // on other things like the runtime I believe. This is set even for C code.
523 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
524
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000525 if (PP.getLangOptions().ObjC2)
526 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroffae84af82007-10-31 18:42:27 +0000527
Chris Lattner9b96b152008-09-30 00:48:48 +0000528 if (PP.getLangOptions().PascalStrings)
529 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
530
Chris Lattnera023ec52008-10-05 19:32:22 +0000531 if (PP.getLangOptions().Blocks) {
532 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
533 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
Chris Lattnerce296f82008-10-05 19:32:52 +0000534 }
Chris Lattnera023ec52008-10-05 19:32:22 +0000535
536 if (PP.getLangOptions().CPlusPlus) {
537 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
538 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
539 DefineBuiltinMacro(Buf, "__GNUG__=4");
540 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
541 DefineBuiltinMacro(Buf, "__cplusplus=1");
542 DefineBuiltinMacro(Buf, "__private_extern__=extern");
543 }
544
545 // Filter out some microsoft extensions when trying to parse in ms-compat
546 // mode.
547 if (PP.getLangOptions().Microsoft) {
Steve Naroffedd04d52008-12-25 14:16:32 +0000548 DefineBuiltinMacro(Buf, "_cdecl=__cdecl");
Chris Lattner2ac88e02009-02-06 22:59:26 +0000549 DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__");
550 DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__");
551 DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__");
552 DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__");
Chris Lattnera023ec52008-10-05 19:32:22 +0000553 }
554
Anders Carlssondfd77642009-04-06 17:37:10 +0000555 if (PP.getLangOptions().Optimize)
556 DefineBuiltinMacro(Buf, "__OPTIMIZE__=1");
557 if (PP.getLangOptions().OptimizeSize)
558 DefineBuiltinMacro(Buf, "__OPTIMIZE_SIZE__=1");
559
Chris Lattnera023ec52008-10-05 19:32:22 +0000560 // Initialize target-specific preprocessor defines.
Chris Lattner5edfe012008-10-05 19:44:25 +0000561 const TargetInfo &TI = PP.getTargetInfo();
562
563 // Define type sizing macros based on the target properties.
564 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
565 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
Chris Lattnercbed2992008-10-05 20:40:30 +0000566
Chris Lattnere9415232009-02-05 07:27:41 +0000567 unsigned IntMaxWidth;
568 const char *IntMaxSuffix;
569 if (TI.getIntMaxType() == TargetInfo::SignedLongLong) {
570 IntMaxWidth = TI.getLongLongWidth();
571 IntMaxSuffix = "LL";
572 } else if (TI.getIntMaxType() == TargetInfo::SignedLong) {
573 IntMaxWidth = TI.getLongWidth();
574 IntMaxSuffix = "L";
575 } else {
576 assert(TI.getIntMaxType() == TargetInfo::SignedInt);
577 IntMaxWidth = TI.getIntWidth();
578 IntMaxSuffix = "";
579 }
580
Chris Lattnerd5aa2e52009-02-06 04:55:18 +0000581 DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf);
582 DefineTypeSize("__SHRT_MAX__", TI.getShortWidth(), "", true, Buf);
583 DefineTypeSize("__INT_MAX__", TI.getIntWidth(), "", true, Buf);
584 DefineTypeSize("__LONG_MAX__", TI.getLongWidth(), "L", true, Buf);
585 DefineTypeSize("__LONG_LONG_MAX__", TI.getLongLongWidth(), "LL", true, Buf);
586 DefineTypeSize("__WCHAR_MAX__", TI.getWCharWidth(), "", true, Buf);
Chris Lattnerd8ed1cf2009-02-06 04:50:25 +0000587 DefineTypeSize("__INTMAX_MAX__", IntMaxWidth, IntMaxSuffix, true, Buf);
588
Chris Lattner534234c2009-02-06 05:04:11 +0000589 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf);
590 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf);
591 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf);
Chris Lattnerd9ef7242009-02-13 22:28:55 +0000592 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Buf);
Chris Lattner534234c2009-02-06 05:04:11 +0000593 DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf);
Chris Lattner31bd8502009-02-06 05:06:07 +0000594 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf);
595 // FIXME: TargetInfo hookize __WINT_TYPE__.
596 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
597
Chris Lattnercbed2992008-10-05 20:40:30 +0000598 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
599 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
600 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
Chris Lattner2ac88e02009-02-06 22:59:26 +0000601
602 // Define a __POINTER_WIDTH__ macro for stdint.h.
603 sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0));
604 DefineBuiltinMacro(Buf, MacroBuf);
605
606 if (!TI.isCharSigned())
607 DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__");
608
609 // Define fixed-sized integer types for stdint.h
610 assert(TI.getCharWidth() == 8 && "unsupported target types");
611 assert(TI.getShortWidth() == 16 && "unsupported target types");
612 DefineBuiltinMacro(Buf, "__INT8_TYPE__=char");
613 DefineBuiltinMacro(Buf, "__INT16_TYPE__=short");
614
615 if (TI.getIntWidth() == 32)
616 DefineBuiltinMacro(Buf, "__INT32_TYPE__=int");
617 else {
618 assert(TI.getLongLongWidth() == 32 && "unsupported target types");
619 DefineBuiltinMacro(Buf, "__INT32_TYPE__=long long");
620 }
621
622 // 16-bit targets doesn't necessarily have a 64-bit type.
623 if (TI.getLongLongWidth() == 64)
624 DefineBuiltinMacro(Buf, "__INT64_TYPE__=long long");
Chris Lattner1be8bb92008-10-05 20:06:37 +0000625
Chris Lattner77cec472007-10-10 17:48:53 +0000626 // Add __builtin_va_list typedef.
627 {
Chris Lattner5edfe012008-10-05 19:44:25 +0000628 const char *VAList = TI.getVAListDeclaration();
Chris Lattner77cec472007-10-10 17:48:53 +0000629 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
630 Buf.push_back('\n');
631 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000632
Chris Lattner5edfe012008-10-05 19:44:25 +0000633 if (const char *Prefix = TI.getUserLabelPrefix()) {
Chris Lattner3da35682008-10-05 21:49:27 +0000634 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
635 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner3f6d8cf2008-10-05 19:22:37 +0000636 }
637
Chris Lattner5edfe012008-10-05 19:44:25 +0000638 // Build configuration options. FIXME: these should be controlled by
639 // command line options or something.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000640 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
Daniel Dunbarcdd3c762009-04-08 18:03:55 +0000641
642 if (PP.getLangOptions().Static)
643 DefineBuiltinMacro(Buf, "__STATIC__=1");
644 else
645 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
646
647 if (PP.getLangOptions().GNUInline)
648 DefineBuiltinMacro(Buf, "__GNUC_GNU_INLINE__=1");
649 else
650 DefineBuiltinMacro(Buf, "__GNUC_STDC_INLINE__=1");
651
652 if (PP.getLangOptions().NoInline)
653 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
Daniel Dunbare079c712009-04-08 03:03:23 +0000654
655 if (unsigned PICLevel = PP.getLangOptions().PICLevel) {
656 sprintf(MacroBuf, "__PIC__=%d", PICLevel);
657 DefineBuiltinMacro(Buf, MacroBuf);
658
659 sprintf(MacroBuf, "__pic__=%d", PICLevel);
660 DefineBuiltinMacro(Buf, MacroBuf);
661 }
Chris Lattner5edfe012008-10-05 19:44:25 +0000662
Chris Lattner3da35682008-10-05 21:49:27 +0000663 // Macros to control C99 numerics and <float.h>
664 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
665 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
666 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
667 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
668 DefineBuiltinMacro(Buf, MacroBuf);
669
Chris Lattner5edfe012008-10-05 19:44:25 +0000670 // Get other target #defines.
Chris Lattner79682402009-03-20 15:52:06 +0000671 TI.getTargetDefines(PP.getLangOptions(), Buf);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000672}
673
674
675/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman886bf132008-01-07 04:01:26 +0000676/// which implicitly adds the builtin defines etc.
Ted Kremenek17861c52007-12-19 22:51:13 +0000677void Preprocessor::EnterMainSourceFile() {
Chris Lattner5a0d2272009-02-13 19:33:24 +0000678 // We do not allow the preprocessor to reenter the main file. Doing so will
679 // cause FileID's to accumulate information from both runs (e.g. #line
680 // information) and predefined macros aren't guaranteed to be set properly.
681 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000682 FileID MainFileID = SourceMgr.getMainFileID();
Ted Kremenek17861c52007-12-19 22:51:13 +0000683
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000684 // Enter the main file source buffer.
685 EnterSourceFile(MainFileID, 0);
686
Chris Lattnerb45f05c2007-11-15 19:07:47 +0000687 // Tell the header info that the main file was entered. If the file is later
688 // #imported, it won't be re-entered.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000689 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattnerb45f05c2007-11-15 19:07:47 +0000690 HeaderInfo.IncrementIncludeCount(FE);
691
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000692 std::vector<char> PrologFile;
693 PrologFile.reserve(4080);
694
695 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
696 InitializePredefinedMacros(*this, PrologFile);
697
Chris Lattner0112bdf2009-03-20 20:16:10 +0000698 // Add on the predefines from the driver. Wrap in a #line directive to report
699 // that they come from the command line.
700 const char *LineDirective = "# 1 \"<command line>\" 1\n";
701 PrologFile.insert(PrologFile.end(),
702 LineDirective, LineDirective+strlen(LineDirective));
703
Chris Lattner47b6a162008-04-19 23:09:31 +0000704 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000705
Chris Lattner0112bdf2009-03-20 20:16:10 +0000706 LineDirective = "# 2 \"<built-in>\" 2\n";
707 PrologFile.insert(PrologFile.end(),
708 LineDirective, LineDirective+strlen(LineDirective));
709
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000710 // Memory buffer must end with a null byte!
711 PrologFile.push_back(0);
712
713 // Now that we have emitted the predefined macros, #includes, etc into
714 // PrologFile, preprocess it to populate the initial preprocessor state.
715 llvm::MemoryBuffer *SB =
716 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
Chris Lattner0112bdf2009-03-20 20:16:10 +0000717 "<built-in>");
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000718 assert(SB && "Cannot fail to create predefined source buffer");
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000719 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
720 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000721
722 // Start parsing the predefines.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000723 EnterSourceFile(FID, 0);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000724}
Chris Lattner4b009652007-07-25 00:24:17 +0000725
Chris Lattner4b009652007-07-25 00:24:17 +0000726
727//===----------------------------------------------------------------------===//
728// Lexer Event Handling.
729//===----------------------------------------------------------------------===//
730
731/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
732/// identifier information for the token and install it into the token.
733IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
734 const char *BufPtr) {
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000735 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattner4b009652007-07-25 00:24:17 +0000736 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
737
738 // Look up this token, see if it is a macro, or if it is a language keyword.
739 IdentifierInfo *II;
740 if (BufPtr && !Identifier.needsCleaning()) {
741 // No cleaning needed, just use the characters from the lexed buffer.
742 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
743 } else {
744 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
745 llvm::SmallVector<char, 64> IdentifierBuffer;
746 IdentifierBuffer.resize(Identifier.getLength());
747 const char *TmpBuf = &IdentifierBuffer[0];
748 unsigned Size = getSpelling(Identifier, TmpBuf);
749 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
750 }
751 Identifier.setIdentifierInfo(II);
752 return II;
753}
754
755
756/// HandleIdentifier - This callback is invoked when the lexer reads an
757/// identifier. This callback looks up the identifier in the map and/or
758/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner5b747d02009-01-21 07:43:11 +0000759///
760/// Note that callers of this method are guarded by checking the
761/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
762/// IdentifierInfo methods that compute these properties will need to change to
763/// match.
Chris Lattner4b009652007-07-25 00:24:17 +0000764void Preprocessor::HandleIdentifier(Token &Identifier) {
765 assert(Identifier.getIdentifierInfo() &&
766 "Can't handle identifiers without identifier info!");
767
768 IdentifierInfo &II = *Identifier.getIdentifierInfo();
769
770 // If this identifier was poisoned, and if it was not produced from a macro
771 // expansion, emit an error.
Ted Kremenek3acf6702008-11-19 22:43:49 +0000772 if (II.isPoisoned() && CurPPLexer) {
Chris Lattner4b009652007-07-25 00:24:17 +0000773 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
774 Diag(Identifier, diag::err_pp_used_poisoned_id);
775 else
776 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
777 }
778
779 // If this is a macro to be expanded, do it.
Chris Lattner7a1b0882007-10-07 08:44:20 +0000780 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000781 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
782 if (MI->isEnabled()) {
783 if (!HandleMacroExpandedIdentifier(Identifier, MI))
784 return;
785 } else {
786 // C99 6.10.3.4p2 says that a disabled macro may never again be
787 // expanded, even if it's in a context where it could be expanded in the
788 // future.
789 Identifier.setFlag(Token::DisableExpand);
790 }
791 }
Chris Lattner4b009652007-07-25 00:24:17 +0000792 }
793
794 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
795 // then we act as if it is the actual operator and not the textual
796 // representation of it.
797 if (II.isCPlusPlusOperatorKeyword())
798 Identifier.setIdentifierInfo(0);
799
Chris Lattner4b009652007-07-25 00:24:17 +0000800 // If this is an extension token, diagnose its use.
Steve Naroff892bc0e2008-09-02 18:50:17 +0000801 // We avoid diagnosing tokens that originate from macro definitions.
802 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion)
Chris Lattner4b009652007-07-25 00:24:17 +0000803 Diag(Identifier, diag::ext_token_used);
804}