blob: 984cf1aab82923e3bdbcf8f9694f14e97850aaa7 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerf73903a2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Reid Spencer5f016e22007-07-11 17:01:13 +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"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Lex/Pragma.h"
32#include "clang/Lex/ScratchBuffer.h"
Chris Lattner500d3292009-01-29 05:15:15 +000033#include "clang/Lex/LexDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
Chris Lattner2db78dd2008-10-05 20:40:30 +000036#include "llvm/ADT/APFloat.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000037#include "llvm/ADT/SmallVector.h"
Chris Lattner97ba77c2007-07-16 06:48:38 +000038#include "llvm/Support/MemoryBuffer.h"
Ted Kremenekbdd30c22008-01-14 16:44:48 +000039#include "llvm/Support/Streams.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
Ted Kremenekec6c5742008-04-17 21:23:07 +000044PreprocessorFactory::~PreprocessorFactory() {}
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
47 TargetInfo &target, SourceManager &SM,
Ted Kremenek72b1b152009-01-15 18:47:46 +000048 HeaderSearch &Headers,
49 IdentifierInfoLookup* IILookup)
Reid Spencer5f016e22007-07-11 17:01:13 +000050 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
Ted Kremenek72b1b152009-01-15 18:47:46 +000051 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts, IILookup),
Ted Kremenek4b71e3e2008-11-19 00:44:06 +000052 CurPPLexer(0), CurDirLookup(0), Callbacks(0) {
Reid Spencer5f016e22007-07-11 17:01:13 +000053 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattner9594acf2007-07-15 00:25:26 +000054
Reid Spencer5f016e22007-07-11 17:01:13 +000055 // Clear stats.
56 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
57 NumIf = NumElse = NumEndif = 0;
58 NumEnteredSourceFiles = 0;
59 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
60 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
61 MaxIncludeStackDepth = 0;
62 NumSkipped = 0;
63
64 // Default to discarding comments.
65 KeepComments = false;
66 KeepMacroComments = false;
67
68 // Macro expansion is enabled.
69 DisableMacroExpansion = false;
70 InMacroArgs = false;
Chris Lattner6cfe7592008-03-09 02:26:03 +000071 NumCachedTokenLexers = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000072
Argyrios Kyrtzidis03db1b32008-08-10 13:15:22 +000073 CachedLexPos = 0;
74
Reid Spencer5f016e22007-07-11 17:01:13 +000075 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
76 // This gets unpoisoned where it is allowed.
77 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
78
79 // Initialize the pragma handlers.
80 PragmaHandlers = new PragmaNamespace(0);
81 RegisterBuiltinPragmas();
82
83 // Initialize builtin macros like __LINE__ and friends.
84 RegisterBuiltinMacros();
85}
86
87Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +000088 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
89
Reid Spencer5f016e22007-07-11 17:01:13 +000090 while (!IncludeMacroStack.empty()) {
91 delete IncludeMacroStack.back().TheLexer;
Chris Lattner6cfe7592008-03-09 02:26:03 +000092 delete IncludeMacroStack.back().TheTokenLexer;
Reid Spencer5f016e22007-07-11 17:01:13 +000093 IncludeMacroStack.pop_back();
94 }
Chris Lattnercc1a8752007-10-07 08:44:20 +000095
96 // Free any macro definitions.
97 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
98 Macros.begin(), E = Macros.end(); I != E; ++I) {
Ted Kremenek0ea76722008-12-15 19:56:42 +000099 // We don't need to free the MacroInfo objects directly. These
100 // will be released when the BumpPtrAllocator 'BP' object gets
Ted Kremenek9ee7d452009-01-19 07:45:44 +0000101 // destroyed. We still need to run the dstor, however, to free
102 // memory alocated by MacroInfo.
103 I->second->~MacroInfo();
Chris Lattnercc1a8752007-10-07 08:44:20 +0000104 I->first->setHasMacroDefinition(false);
105 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000106
Chris Lattner9594acf2007-07-15 00:25:26 +0000107 // Free any cached macro expanders.
Chris Lattner6cfe7592008-03-09 02:26:03 +0000108 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
109 delete TokenLexerCache[i];
Chris Lattner9594acf2007-07-15 00:25:26 +0000110
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 // Release pragma information.
112 delete PragmaHandlers;
113
114 // Delete the scratch buffer info.
115 delete ScratchBuf;
Chris Lattnereb50ed82008-03-14 06:07:05 +0000116
117 delete Callbacks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000118}
119
Chris Lattnerd2177732007-07-20 16:59:19 +0000120void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000121 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
122 << getSpelling(Tok) << "'";
Reid Spencer5f016e22007-07-11 17:01:13 +0000123
124 if (!DumpFlags) return;
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000125
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000126 llvm::cerr << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 if (Tok.isAtStartOfLine())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000128 llvm::cerr << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 if (Tok.hasLeadingSpace())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000130 llvm::cerr << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 if (Tok.isExpandDisabled())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000132 llvm::cerr << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 if (Tok.needsCleaning()) {
134 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000135 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
136 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000137 }
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000138
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000139 llvm::cerr << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000140 DumpLocation(Tok.getLocation());
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000141 llvm::cerr << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000142}
143
144void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000145 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000146}
147
148void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000149 llvm::cerr << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
151 DumpToken(MI.getReplacementToken(i));
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000152 llvm::cerr << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 }
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000154 llvm::cerr << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000155}
156
157void Preprocessor::PrintStats() {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000158 llvm::cerr << "\n*** Preprocessor Stats:\n";
159 llvm::cerr << NumDirectives << " directives found:\n";
160 llvm::cerr << " " << NumDefined << " #define.\n";
161 llvm::cerr << " " << NumUndefined << " #undef.\n";
162 llvm::cerr << " #include/#include_next/#import:\n";
163 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
164 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
165 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
166 llvm::cerr << " " << NumElse << " #else/#elif.\n";
167 llvm::cerr << " " << NumEndif << " #endif.\n";
168 llvm::cerr << " " << NumPragma << " #pragma.\n";
169 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000170
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000171 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
172 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
173 << NumFastMacroExpanded << " on the fast path.\n";
174 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
175 << " token paste (##) operations performed, "
176 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000177}
178
179//===----------------------------------------------------------------------===//
180// Token Spelling
181//===----------------------------------------------------------------------===//
182
183
184/// getSpelling() - Return the 'spelling' of this token. The spelling of a
185/// token are the characters used to represent the token in the source file
186/// after trigraph expansion and escaped-newline folding. In particular, this
187/// wants to get the true, uncanonicalized, spelling of things like digraphs
188/// UCNs, etc.
Chris Lattnerd2177732007-07-20 16:59:19 +0000189std::string Preprocessor::getSpelling(const Token &Tok) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Ted Kremenek277faca2009-01-27 00:01:05 +0000191
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 // If this token contains nothing interesting, return it directly.
Ted Kremenek277faca2009-01-27 00:01:05 +0000193 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 if (!Tok.needsCleaning())
195 return std::string(TokStart, TokStart+Tok.getLength());
196
197 std::string Result;
198 Result.reserve(Tok.getLength());
199
200 // Otherwise, hard case, relex the characters into the string.
201 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
202 Ptr != End; ) {
203 unsigned CharSize;
204 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
205 Ptr += CharSize;
206 }
207 assert(Result.size() != unsigned(Tok.getLength()) &&
208 "NeedsCleaning flag set on something that didn't need cleaning!");
209 return Result;
210}
211
212/// getSpelling - This method is used to get the spelling of a token into a
213/// preallocated buffer, instead of as an std::string. The caller is required
214/// to allocate enough space for the token, which is guaranteed to be at least
215/// Tok.getLength() bytes long. The actual length of the token is returned.
216///
217/// Note that this method may do two possible things: it may either fill in
218/// the buffer specified with characters, or it may *change the input pointer*
219/// to point to a constant buffer with the data already in it (avoiding a
220/// copy). The caller is not allowed to modify the returned buffer pointer
221/// if an internal buffer is returned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000222unsigned Preprocessor::getSpelling(const Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 const char *&Buffer) const {
224 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
225
226 // If this token is an identifier, just return the string from the identifier
227 // table, which is very quick.
228 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
229 Buffer = II->getName();
Chris Lattnere1dccae2009-01-05 19:44:41 +0000230 return II->getLength();
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 }
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000232
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner47246be2009-01-26 19:29:26 +0000234 const char *TokStart = 0;
235
236 if (Tok.isLiteral())
237 TokStart = Tok.getLiteralData();
238
239 if (TokStart == 0)
240 TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000241
242 // If this token contains nothing interesting, return it directly.
243 if (!Tok.needsCleaning()) {
244 Buffer = TokStart;
245 return Tok.getLength();
246 }
Chris Lattner47246be2009-01-26 19:29:26 +0000247
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 // Otherwise, hard case, relex the characters into the string.
249 char *OutBuf = const_cast<char*>(Buffer);
250 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
251 Ptr != End; ) {
252 unsigned CharSize;
253 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
254 Ptr += CharSize;
255 }
256 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
257 "NeedsCleaning flag set on something that didn't need cleaning!");
258
259 return OutBuf-Buffer;
260}
261
262
263/// CreateString - Plop the specified string into a scratch buffer and return a
264/// location for it. If specified, the source location provides a source
265/// location for the token.
Chris Lattner47246be2009-01-26 19:29:26 +0000266void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
267 SourceLocation InstantiationLoc) {
268 Tok.setLength(Len);
269
270 const char *DestPtr;
271 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
272
273 if (InstantiationLoc.isValid())
274 Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc, Len);
275 Tok.setLocation(Loc);
276
277 // If this is a literal token, set the pointer data.
278 if (Tok.isLiteral())
279 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000280}
281
282
Chris Lattner97ba77c2007-07-16 06:48:38 +0000283/// AdvanceToTokenCharacter - Given a location that specifies the start of a
284/// token, return a new location that specifies a character within the token.
285SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
286 unsigned CharNo) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000287 // If they request the first char of the token, we're trivially done. If this
288 // is a macro expansion, it doesn't make sense to point to a character within
289 // the instantiation point (the name). We could point to the source
290 // character, but without also pointing to instantiation info, this is
291 // confusing.
292 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000293
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000294 // Figure out how many physical characters away the specified instantiation
Chris Lattner97ba77c2007-07-16 06:48:38 +0000295 // character is. This needs to take into consideration newlines and
296 // trigraphs.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000297 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
298 unsigned PhysOffset = 0;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000299
300 // The usual case is that tokens don't contain anything interesting. Skip
301 // over the uninteresting characters. If a token only consists of simple
302 // chars, this method is extremely fast.
303 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattner9dc1f532007-07-20 16:37:10 +0000304 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000305
Chris Lattner28c90ad2009-01-17 07:57:25 +0000306 // If we have a character that may be a trigraph or escaped newline, use a
Chris Lattner97ba77c2007-07-16 06:48:38 +0000307 // lexer to parse it correctly.
Chris Lattner97ba77c2007-07-16 06:48:38 +0000308 if (CharNo != 0) {
Chris Lattner97ba77c2007-07-16 06:48:38 +0000309 // Skip over characters the remaining characters.
Chris Lattner28c90ad2009-01-17 07:57:25 +0000310 for (; CharNo; --CharNo) {
311 unsigned Size;
312 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
313 TokPtr += Size;
314 PhysOffset += Size;
315 }
Chris Lattner97ba77c2007-07-16 06:48:38 +0000316 }
Chris Lattner9dc1f532007-07-20 16:37:10 +0000317
318 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner97ba77c2007-07-16 06:48:38 +0000319}
320
321
Chris Lattner53b0dab2007-10-09 22:10:18 +0000322//===----------------------------------------------------------------------===//
323// Preprocessor Initialization Methods
324//===----------------------------------------------------------------------===//
325
326// Append a #define line to Buf for Macro. Macro should be of the form XXX,
327// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
328// "#define XXX Y z W". To get a #define with no value, use "XXX=".
329static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
330 const char *Command = "#define ") {
331 Buf.insert(Buf.end(), Command, Command+strlen(Command));
332 if (const char *Equal = strchr(Macro, '=')) {
333 // Turn the = into ' '.
334 Buf.insert(Buf.end(), Macro, Equal);
335 Buf.push_back(' ');
336 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
337 } else {
338 // Push "macroname 1".
339 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
340 Buf.push_back(' ');
341 Buf.push_back('1');
342 }
343 Buf.push_back('\n');
344}
345
Chris Lattner2db78dd2008-10-05 20:40:30 +0000346/// PickFP - This is used to pick a value based on the FP semantics of the
347/// specified FP model.
348template <typename T>
349static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
350 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
351 if (Sem == &llvm::APFloat::IEEEsingle)
352 return IEEESingleVal;
353 if (Sem == &llvm::APFloat::IEEEdouble)
354 return IEEEDoubleVal;
355 if (Sem == &llvm::APFloat::x87DoubleExtended)
356 return X87DoubleExtendedVal;
357 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
358 return PPCDoubleDoubleVal;
359}
360
361static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
362 const llvm::fltSemantics *Sem) {
Chris Lattnere9863ca2008-10-05 21:40:58 +0000363 const char *DenormMin, *Epsilon, *Max, *Min;
364 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
365 "3.64519953188247460253e-4951L",
366 "4.94065645841246544176568792868221e-324L");
367 int Digits = PickFP(Sem, 6, 15, 18, 31);
368 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
369 "1.08420217248550443401e-19L",
370 "4.94065645841246544176568792868221e-324L");
371 int HasInifinity = 1, HasQuietNaN = 1;
372 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
373 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
374 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
375 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
376 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
377 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
378 "3.36210314311209350626e-4932L",
379 "2.00416836000897277799610805135016e-292L");
380 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
381 "1.18973149535723176502e+4932L",
382 "1.79769313486231580793728971405301e+308L");
Chris Lattner2db78dd2008-10-05 20:40:30 +0000383
384 char MacroBuf[60];
385 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
386 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattnere9863ca2008-10-05 21:40:58 +0000387 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
388 DefineBuiltinMacro(Buf, MacroBuf);
389 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
390 DefineBuiltinMacro(Buf, MacroBuf);
391 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
392 DefineBuiltinMacro(Buf, MacroBuf);
393 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
394 DefineBuiltinMacro(Buf, MacroBuf);
395 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
396 DefineBuiltinMacro(Buf, MacroBuf);
397 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
398 DefineBuiltinMacro(Buf, MacroBuf);
399 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
400 DefineBuiltinMacro(Buf, MacroBuf);
401 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
402 DefineBuiltinMacro(Buf, MacroBuf);
403 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
404 DefineBuiltinMacro(Buf, MacroBuf);
405 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
406 DefineBuiltinMacro(Buf, MacroBuf);
407 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
408 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattnerd427ad42009-02-05 07:19:24 +0000409 sprintf(MacroBuf, "__%s_HAS_DENORM__=1", Prefix);
410 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner2db78dd2008-10-05 20:40:30 +0000411}
412
Chris Lattner53b0dab2007-10-09 22:10:18 +0000413
Chris Lattner996fecc2009-02-06 04:50:25 +0000414/// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
415/// named MacroName with the max value for a type with width 'TypeWidth' a
416/// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
417static void DefineTypeSize(const char *MacroName, unsigned TypeWidth,
418 const char *ValSuffix, bool isSigned,
419 std::vector<char> &Buf) {
420 char MacroBuf[60];
421 uint64_t MaxVal;
422 if (isSigned)
423 MaxVal = (1LL << (TypeWidth - 1)) - 1;
424 else
425 MaxVal = ~0LL >> (64-TypeWidth);
426
427 sprintf(MacroBuf, "%s=%llu%s", MacroName, MaxVal, ValSuffix);
428 DefineBuiltinMacro(Buf, MacroBuf);
429}
430
Chris Lattner2b5abf52009-02-06 05:04:11 +0000431static void DefineType(const char *MacroName, TargetInfo::IntType Ty,
432 std::vector<char> &Buf) {
433 char MacroBuf[60];
434 sprintf(MacroBuf, "%s=%s", MacroName, TargetInfo::getTypeName(Ty));
435 DefineBuiltinMacro(Buf, MacroBuf);
436}
437
438
Chris Lattner53b0dab2007-10-09 22:10:18 +0000439static void InitializePredefinedMacros(Preprocessor &PP,
440 std::vector<char> &Buf) {
Chris Lattner62213d92008-10-05 19:32:22 +0000441 // Compiler version introspection macros.
442 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
443 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
444
445 // Currently claim to be compatible with GCC 4.2.1-5621.
446 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
447 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
448 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
449 DefineBuiltinMacro(Buf, "__GNUC__=4");
450 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
451 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. "
452 "build 5621) (dot 3)\"");
453
454
455 // Initialize language-specific preprocessor defines.
456
Chris Lattner53b0dab2007-10-09 22:10:18 +0000457 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
458 // and __DATE__ etc.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000459 // These should all be defined in the preprocessor according to the
460 // current language configuration.
Steve Naroff7e0fbb22008-12-18 22:37:25 +0000461 if (!PP.getLangOptions().Microsoft)
462 DefineBuiltinMacro(Buf, "__STDC__=1");
Daniel Dunbarc1571452008-12-01 18:55:22 +0000463 if (PP.getLangOptions().AsmPreprocessor)
464 DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
Chris Lattner53b0dab2007-10-09 22:10:18 +0000465 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
466 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
467 else if (0) // STDC94 ?
468 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
469
470 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
Daniel Dunbarfba5cb12008-08-12 00:21:46 +0000471 if (PP.getLangOptions().ObjC1) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000472 DefineBuiltinMacro(Buf, "__OBJC__=1");
Daniel Dunbarfba5cb12008-08-12 00:21:46 +0000473
474 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) {
475 DefineBuiltinMacro(Buf, "__weak=");
476 DefineBuiltinMacro(Buf, "__strong=");
477 } else {
478 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))");
479 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))");
480 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
481 }
482
483 if (PP.getLangOptions().NeXTRuntime)
484 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
Daniel Dunbarfba5cb12008-08-12 00:21:46 +0000485 }
Chris Lattner9b533162008-10-05 19:44:25 +0000486
Chris Lattnereb52b442008-10-06 07:43:09 +0000487 // darwin_constant_cfstrings controls this. This is also dependent
488 // on other things like the runtime I believe. This is set even for C code.
489 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
490
Steve Naroff73b17cd2008-05-15 21:12:10 +0000491 if (PP.getLangOptions().ObjC2)
492 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroff8ee529b2007-10-31 18:42:27 +0000493
Chris Lattner048dd942008-09-30 00:48:48 +0000494 if (PP.getLangOptions().PascalStrings)
495 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
496
Chris Lattner62213d92008-10-05 19:32:22 +0000497 if (PP.getLangOptions().Blocks) {
498 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
499 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
Chris Lattner2b43ad92008-10-05 19:32:52 +0000500 }
Chris Lattner62213d92008-10-05 19:32:22 +0000501
502 if (PP.getLangOptions().CPlusPlus) {
503 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
504 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
505 DefineBuiltinMacro(Buf, "__GNUG__=4");
506 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
507 DefineBuiltinMacro(Buf, "__cplusplus=1");
508 DefineBuiltinMacro(Buf, "__private_extern__=extern");
509 }
510
511 // Filter out some microsoft extensions when trying to parse in ms-compat
512 // mode.
513 if (PP.getLangOptions().Microsoft) {
Steve Naroff239f0732008-12-25 14:16:32 +0000514 DefineBuiltinMacro(Buf, "_cdecl=__cdecl");
Chris Lattner62213d92008-10-05 19:32:22 +0000515 DefineBuiltinMacro(Buf, "__int8=char");
516 DefineBuiltinMacro(Buf, "__int16=short");
517 DefineBuiltinMacro(Buf, "__int32=int");
518 DefineBuiltinMacro(Buf, "__int64=long long");
Chris Lattner62213d92008-10-05 19:32:22 +0000519 }
520
Chris Lattner62213d92008-10-05 19:32:22 +0000521 // Initialize target-specific preprocessor defines.
Chris Lattner9b533162008-10-05 19:44:25 +0000522 const TargetInfo &TI = PP.getTargetInfo();
523
524 // Define type sizing macros based on the target properties.
525 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
526 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
Chris Lattner2db78dd2008-10-05 20:40:30 +0000527
Chris Lattner659dc142009-02-05 07:27:41 +0000528 unsigned IntMaxWidth;
529 const char *IntMaxSuffix;
530 if (TI.getIntMaxType() == TargetInfo::SignedLongLong) {
531 IntMaxWidth = TI.getLongLongWidth();
532 IntMaxSuffix = "LL";
533 } else if (TI.getIntMaxType() == TargetInfo::SignedLong) {
534 IntMaxWidth = TI.getLongWidth();
535 IntMaxSuffix = "L";
536 } else {
537 assert(TI.getIntMaxType() == TargetInfo::SignedInt);
538 IntMaxWidth = TI.getIntWidth();
539 IntMaxSuffix = "";
540 }
541
Chris Lattner86d85b82009-02-06 04:55:18 +0000542 DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf);
543 DefineTypeSize("__SHRT_MAX__", TI.getShortWidth(), "", true, Buf);
544 DefineTypeSize("__INT_MAX__", TI.getIntWidth(), "", true, Buf);
545 DefineTypeSize("__LONG_MAX__", TI.getLongWidth(), "L", true, Buf);
546 DefineTypeSize("__LONG_LONG_MAX__", TI.getLongLongWidth(), "LL", true, Buf);
547 DefineTypeSize("__WCHAR_MAX__", TI.getWCharWidth(), "", true, Buf);
Chris Lattner996fecc2009-02-06 04:50:25 +0000548 DefineTypeSize("__INTMAX_MAX__", IntMaxWidth, IntMaxSuffix, true, Buf);
549
Chris Lattner2b5abf52009-02-06 05:04:11 +0000550 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf);
551 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf);
552 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf);
553 DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf);
Chris Lattner3c3b1552009-02-06 05:06:07 +0000554 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf);
555 // FIXME: TargetInfo hookize __WINT_TYPE__.
556 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
557
Chris Lattner2db78dd2008-10-05 20:40:30 +0000558 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
559 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
560 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000561
Chris Lattnerd19144b2007-10-10 17:48:53 +0000562 // Add __builtin_va_list typedef.
563 {
Chris Lattner9b533162008-10-05 19:44:25 +0000564 const char *VAList = TI.getVAListDeclaration();
Chris Lattnerd19144b2007-10-10 17:48:53 +0000565 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
566 Buf.push_back('\n');
567 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000568
Chris Lattner996fecc2009-02-06 04:50:25 +0000569 char MacroBuf[60];
Chris Lattner9b533162008-10-05 19:44:25 +0000570 if (const char *Prefix = TI.getUserLabelPrefix()) {
Chris Lattner12f09262008-10-05 21:49:27 +0000571 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
572 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner3fdf4672008-10-05 19:22:37 +0000573 }
574
Chris Lattner9b533162008-10-05 19:44:25 +0000575 // Build configuration options. FIXME: these should be controlled by
576 // command line options or something.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000577 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
578 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
579 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
580 DefineBuiltinMacro(Buf, "__PIC__=1");
Chris Lattner9b533162008-10-05 19:44:25 +0000581
Chris Lattner12f09262008-10-05 21:49:27 +0000582 // Macros to control C99 numerics and <float.h>
583 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
584 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
585 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
586 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
587 DefineBuiltinMacro(Buf, MacroBuf);
588
Chris Lattner9b533162008-10-05 19:44:25 +0000589 // Get other target #defines.
590 TI.getTargetDefines(Buf);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000591
Chris Lattner53b0dab2007-10-09 22:10:18 +0000592 // FIXME: Should emit a #line directive here.
593}
594
595
596/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000597/// which implicitly adds the builtin defines etc.
Ted Kremenek95041a22007-12-19 22:51:13 +0000598void Preprocessor::EnterMainSourceFile() {
599
Chris Lattner2b2453a2009-01-17 06:22:33 +0000600 FileID MainFileID = SourceMgr.getMainFileID();
Ted Kremenek95041a22007-12-19 22:51:13 +0000601
Chris Lattner53b0dab2007-10-09 22:10:18 +0000602 // Enter the main file source buffer.
603 EnterSourceFile(MainFileID, 0);
604
Chris Lattnerb2832982007-11-15 19:07:47 +0000605 // Tell the header info that the main file was entered. If the file is later
606 // #imported, it won't be re-entered.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000607 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattnerb2832982007-11-15 19:07:47 +0000608 HeaderInfo.IncrementIncludeCount(FE);
609
Chris Lattner53b0dab2007-10-09 22:10:18 +0000610 std::vector<char> PrologFile;
611 PrologFile.reserve(4080);
612
613 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
614 InitializePredefinedMacros(*this, PrologFile);
615
616 // Add on the predefines from the driver.
Chris Lattneraa391972008-04-19 23:09:31 +0000617 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000618
619 // Memory buffer must end with a null byte!
620 PrologFile.push_back(0);
621
622 // Now that we have emitted the predefined macros, #includes, etc into
623 // PrologFile, preprocess it to populate the initial preprocessor state.
624 llvm::MemoryBuffer *SB =
625 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
626 "<predefines>");
627 assert(SB && "Cannot fail to create predefined source buffer");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000628 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
629 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Chris Lattner53b0dab2007-10-09 22:10:18 +0000630
631 // Start parsing the predefines.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000632 EnterSourceFile(FID, 0);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000633}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000634
Reid Spencer5f016e22007-07-11 17:01:13 +0000635
636//===----------------------------------------------------------------------===//
637// Lexer Event Handling.
638//===----------------------------------------------------------------------===//
639
640/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
641/// identifier information for the token and install it into the token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000642IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 const char *BufPtr) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000644 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
646
647 // Look up this token, see if it is a macro, or if it is a language keyword.
648 IdentifierInfo *II;
649 if (BufPtr && !Identifier.needsCleaning()) {
650 // No cleaning needed, just use the characters from the lexed buffer.
651 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
652 } else {
653 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerc35717a2007-07-13 17:10:38 +0000654 llvm::SmallVector<char, 64> IdentifierBuffer;
655 IdentifierBuffer.resize(Identifier.getLength());
656 const char *TmpBuf = &IdentifierBuffer[0];
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 unsigned Size = getSpelling(Identifier, TmpBuf);
658 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
659 }
660 Identifier.setIdentifierInfo(II);
661 return II;
662}
663
664
665/// HandleIdentifier - This callback is invoked when the lexer reads an
666/// identifier. This callback looks up the identifier in the map and/or
667/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000668///
669/// Note that callers of this method are guarded by checking the
670/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
671/// IdentifierInfo methods that compute these properties will need to change to
672/// match.
Chris Lattnerd2177732007-07-20 16:59:19 +0000673void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 assert(Identifier.getIdentifierInfo() &&
675 "Can't handle identifiers without identifier info!");
676
677 IdentifierInfo &II = *Identifier.getIdentifierInfo();
678
679 // If this identifier was poisoned, and if it was not produced from a macro
680 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000681 if (II.isPoisoned() && CurPPLexer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
683 Diag(Identifier, diag::err_pp_used_poisoned_id);
684 else
685 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
686 }
687
688 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000689 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
691 if (MI->isEnabled()) {
692 if (!HandleMacroExpandedIdentifier(Identifier, MI))
693 return;
694 } else {
695 // C99 6.10.3.4p2 says that a disabled macro may never again be
696 // expanded, even if it's in a context where it could be expanded in the
697 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000698 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 }
700 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 }
702
703 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
704 // then we act as if it is the actual operator and not the textual
705 // representation of it.
706 if (II.isCPlusPlusOperatorKeyword())
707 Identifier.setIdentifierInfo(0);
708
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000710 // We avoid diagnosing tokens that originate from macro definitions.
711 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 Diag(Identifier, diag::ext_token_used);
713}