blob: c65b5462098987f71926ff1522b61df485e3cb3c [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.
16// -d[MDNI] - Dump various things.
17// -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"
33#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000034#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
Chris Lattnercbed2992008-10-05 20:40:30 +000036#include "llvm/ADT/APFloat.h"
Chris Lattner4b009652007-07-25 00:24:17 +000037#include "llvm/ADT/SmallVector.h"
38#include "llvm/Support/MemoryBuffer.h"
Ted Kremenekce4c64e2008-01-14 16:44:48 +000039#include "llvm/Support/Streams.h"
Chris Lattner4b009652007-07-25 00:24:17 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
Ted Kremenek5ab36b02008-04-17 21:23:07 +000044PreprocessorFactory::~PreprocessorFactory() {}
45
Chris Lattner4b009652007-07-25 00:24:17 +000046Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
47 TargetInfo &target, SourceManager &SM,
48 HeaderSearch &Headers)
49 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattner5b54ed92008-03-09 02:26:03 +000051 CurLexer(0), CurDirLookup(0), CurTokenLexer(0), Callbacks(0) {
Chris Lattner4b009652007-07-25 00:24:17 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
53
54 // Clear stats.
55 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
56 NumIf = NumElse = NumEndif = 0;
57 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
59 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
60 MaxIncludeStackDepth = 0;
61 NumSkipped = 0;
62
63 // Default to discarding comments.
64 KeepComments = false;
65 KeepMacroComments = false;
66
67 // Macro expansion is enabled.
68 DisableMacroExpansion = false;
69 InMacroArgs = false;
Chris Lattner5b54ed92008-03-09 02:26:03 +000070 NumCachedTokenLexers = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000071
Argiris Kirtzidisf55b1102008-08-10 13:15:22 +000072 CacheTokens = false;
73 CachedLexPos = 0;
74
Chris Lattner4b009652007-07-25 00:24:17 +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() {
Argiris Kirtzidis1370cf12008-08-23 12:12:06 +000088 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
89
Chris Lattner4b009652007-07-25 00:24:17 +000090 while (!IncludeMacroStack.empty()) {
91 delete IncludeMacroStack.back().TheLexer;
Chris Lattner5b54ed92008-03-09 02:26:03 +000092 delete IncludeMacroStack.back().TheTokenLexer;
Chris Lattner4b009652007-07-25 00:24:17 +000093 IncludeMacroStack.pop_back();
94 }
Chris Lattner7a1b0882007-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) {
99 // Free the macro definition.
100 delete I->second;
101 I->second = 0;
102 I->first->setHasMacroDefinition(false);
103 }
Chris Lattner4b009652007-07-25 00:24:17 +0000104
105 // Free any cached macro expanders.
Chris Lattner5b54ed92008-03-09 02:26:03 +0000106 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
107 delete TokenLexerCache[i];
Chris Lattner4b009652007-07-25 00:24:17 +0000108
109 // Release pragma information.
110 delete PragmaHandlers;
111
112 // Delete the scratch buffer info.
113 delete ScratchBuf;
Chris Lattner65829812008-03-14 06:07:05 +0000114
115 delete Callbacks;
Chris Lattner4b009652007-07-25 00:24:17 +0000116}
117
Chris Lattner4b009652007-07-25 00:24:17 +0000118/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
119/// the specified Token's location, translating the token's start
120/// position in the current buffer into a SourcePosition object for rendering.
121void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000122 Diags.Report(getFullLoc(Loc), DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +0000123}
124
125void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
126 const std::string &Msg) {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000127 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000128}
129
Chris Lattnerbef45c52008-05-05 06:45:50 +0000130void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
131 const std::string &Msg,
132 const SourceRange &R1, const SourceRange &R2) {
133 SourceRange R[] = {R1, R2};
134 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1, R, 2);
135}
136
137
138void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
139 const SourceRange &R) {
140 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, &R, 1);
141}
142
143void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
144 const SourceRange &R1, const SourceRange &R2) {
145 SourceRange R[] = {R1, R2};
146 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, R, 2);
147}
148
149
Chris Lattner4b009652007-07-25 00:24:17 +0000150void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000151 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
152 << getSpelling(Tok) << "'";
Chris Lattner4b009652007-07-25 00:24:17 +0000153
154 if (!DumpFlags) return;
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000155
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000156 llvm::cerr << "\t";
Chris Lattner4b009652007-07-25 00:24:17 +0000157 if (Tok.isAtStartOfLine())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000158 llvm::cerr << " [StartOfLine]";
Chris Lattner4b009652007-07-25 00:24:17 +0000159 if (Tok.hasLeadingSpace())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000160 llvm::cerr << " [LeadingSpace]";
Chris Lattner4b009652007-07-25 00:24:17 +0000161 if (Tok.isExpandDisabled())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000162 llvm::cerr << " [ExpandDisabled]";
Chris Lattner4b009652007-07-25 00:24:17 +0000163 if (Tok.needsCleaning()) {
164 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000165 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
166 << "']";
Chris Lattner4b009652007-07-25 00:24:17 +0000167 }
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000168
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000169 llvm::cerr << "\tLoc=<";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000170 DumpLocation(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000171 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000172}
173
174void Preprocessor::DumpLocation(SourceLocation Loc) const {
175 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000176 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
177 << SourceMgr.getLineNumber(LogLoc) << ':'
Ted Kremenek79882742008-07-19 19:10:04 +0000178 << SourceMgr.getColumnNumber(LogLoc);
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000179
180 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
181 if (PhysLoc != LogLoc) {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000182 llvm::cerr << " <PhysLoc=";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000183 DumpLocation(PhysLoc);
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000184 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000185 }
Chris Lattner4b009652007-07-25 00:24:17 +0000186}
187
188void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000189 llvm::cerr << "MACRO: ";
Chris Lattner4b009652007-07-25 00:24:17 +0000190 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
191 DumpToken(MI.getReplacementToken(i));
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000192 llvm::cerr << " ";
Chris Lattner4b009652007-07-25 00:24:17 +0000193 }
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000194 llvm::cerr << "\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000195}
196
197void Preprocessor::PrintStats() {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000198 llvm::cerr << "\n*** Preprocessor Stats:\n";
199 llvm::cerr << NumDirectives << " directives found:\n";
200 llvm::cerr << " " << NumDefined << " #define.\n";
201 llvm::cerr << " " << NumUndefined << " #undef.\n";
202 llvm::cerr << " #include/#include_next/#import:\n";
203 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
204 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
205 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
206 llvm::cerr << " " << NumElse << " #else/#elif.\n";
207 llvm::cerr << " " << NumEndif << " #endif.\n";
208 llvm::cerr << " " << NumPragma << " #pragma.\n";
209 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000210
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000211 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
212 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
213 << NumFastMacroExpanded << " on the fast path.\n";
214 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
215 << " token paste (##) operations performed, "
216 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000217}
218
219//===----------------------------------------------------------------------===//
220// Token Spelling
221//===----------------------------------------------------------------------===//
222
223
224/// getSpelling() - Return the 'spelling' of this token. The spelling of a
225/// token are the characters used to represent the token in the source file
226/// after trigraph expansion and escaped-newline folding. In particular, this
227/// wants to get the true, uncanonicalized, spelling of things like digraphs
228/// UCNs, etc.
229std::string Preprocessor::getSpelling(const Token &Tok) const {
230 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
231
232 // If this token contains nothing interesting, return it directly.
233 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
234 if (!Tok.needsCleaning())
235 return std::string(TokStart, TokStart+Tok.getLength());
236
237 std::string Result;
238 Result.reserve(Tok.getLength());
239
240 // Otherwise, hard case, relex the characters into the string.
241 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
242 Ptr != End; ) {
243 unsigned CharSize;
244 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
245 Ptr += CharSize;
246 }
247 assert(Result.size() != unsigned(Tok.getLength()) &&
248 "NeedsCleaning flag set on something that didn't need cleaning!");
249 return Result;
250}
251
252/// getSpelling - This method is used to get the spelling of a token into a
253/// preallocated buffer, instead of as an std::string. The caller is required
254/// to allocate enough space for the token, which is guaranteed to be at least
255/// Tok.getLength() bytes long. The actual length of the token is returned.
256///
257/// Note that this method may do two possible things: it may either fill in
258/// the buffer specified with characters, or it may *change the input pointer*
259/// to point to a constant buffer with the data already in it (avoiding a
260/// copy). The caller is not allowed to modify the returned buffer pointer
261/// if an internal buffer is returned.
262unsigned Preprocessor::getSpelling(const Token &Tok,
263 const char *&Buffer) const {
264 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
265
266 // If this token is an identifier, just return the string from the identifier
267 // table, which is very quick.
268 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
269 Buffer = II->getName();
270
271 // Return the length of the token. If the token needed cleaning, don't
272 // include the size of the newlines or trigraphs in it.
273 if (!Tok.needsCleaning())
274 return Tok.getLength();
275 else
276 return strlen(Buffer);
277 }
278
279 // Otherwise, compute the start of the token in the input lexer buffer.
280 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
281
282 // If this token contains nothing interesting, return it directly.
283 if (!Tok.needsCleaning()) {
284 Buffer = TokStart;
285 return Tok.getLength();
286 }
287 // Otherwise, hard case, relex the characters into the string.
288 char *OutBuf = const_cast<char*>(Buffer);
289 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
290 Ptr != End; ) {
291 unsigned CharSize;
292 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
293 Ptr += CharSize;
294 }
295 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
296 "NeedsCleaning flag set on something that didn't need cleaning!");
297
298 return OutBuf-Buffer;
299}
300
301
302/// CreateString - Plop the specified string into a scratch buffer and return a
303/// location for it. If specified, the source location provides a source
304/// location for the token.
305SourceLocation Preprocessor::
306CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
307 if (SLoc.isValid())
308 return ScratchBuf->getToken(Buf, Len, SLoc);
309 return ScratchBuf->getToken(Buf, Len);
310}
311
312
313/// AdvanceToTokenCharacter - Given a location that specifies the start of a
314/// token, return a new location that specifies a character within the token.
315SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
316 unsigned CharNo) {
317 // If they request the first char of the token, we're trivially done. If this
318 // is a macro expansion, it doesn't make sense to point to a character within
319 // the instantiation point (the name). We could point to the source
320 // character, but without also pointing to instantiation info, this is
321 // confusing.
322 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
323
324 // Figure out how many physical characters away the specified logical
325 // character is. This needs to take into consideration newlines and
326 // trigraphs.
327 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
328 unsigned PhysOffset = 0;
329
330 // The usual case is that tokens don't contain anything interesting. Skip
331 // over the uninteresting characters. If a token only consists of simple
332 // chars, this method is extremely fast.
333 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
334 ++TokPtr, --CharNo, ++PhysOffset;
335
336 // If we have a character that may be a trigraph or escaped newline, create a
337 // lexer to parse it correctly.
338 if (CharNo != 0) {
339 // Create a lexer starting at this token position.
340 Lexer TheLexer(TokStart, *this, TokPtr);
341 Token Tok;
342 // Skip over characters the remaining characters.
343 const char *TokStartPtr = TokPtr;
344 for (; CharNo; --CharNo)
345 TheLexer.getAndAdvanceChar(TokPtr, Tok);
346
347 PhysOffset += TokPtr-TokStartPtr;
348 }
349
350 return TokStart.getFileLocWithOffset(PhysOffset);
351}
352
353
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000354//===----------------------------------------------------------------------===//
355// Preprocessor Initialization Methods
356//===----------------------------------------------------------------------===//
357
358// Append a #define line to Buf for Macro. Macro should be of the form XXX,
359// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
360// "#define XXX Y z W". To get a #define with no value, use "XXX=".
361static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
362 const char *Command = "#define ") {
363 Buf.insert(Buf.end(), Command, Command+strlen(Command));
364 if (const char *Equal = strchr(Macro, '=')) {
365 // Turn the = into ' '.
366 Buf.insert(Buf.end(), Macro, Equal);
367 Buf.push_back(' ');
368 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
369 } else {
370 // Push "macroname 1".
371 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
372 Buf.push_back(' ');
373 Buf.push_back('1');
374 }
375 Buf.push_back('\n');
376}
377
Chris Lattnercbed2992008-10-05 20:40:30 +0000378/// PickFP - This is used to pick a value based on the FP semantics of the
379/// specified FP model.
380template <typename T>
381static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
382 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
383 if (Sem == &llvm::APFloat::IEEEsingle)
384 return IEEESingleVal;
385 if (Sem == &llvm::APFloat::IEEEdouble)
386 return IEEEDoubleVal;
387 if (Sem == &llvm::APFloat::x87DoubleExtended)
388 return X87DoubleExtendedVal;
389 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
390 return PPCDoubleDoubleVal;
391}
392
393static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
394 const llvm::fltSemantics *Sem) {
Chris Lattner5c8f64a2008-10-05 21:40:58 +0000395 const char *DenormMin, *Epsilon, *Max, *Min;
396 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
397 "3.64519953188247460253e-4951L",
398 "4.94065645841246544176568792868221e-324L");
399 int Digits = PickFP(Sem, 6, 15, 18, 31);
400 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
401 "1.08420217248550443401e-19L",
402 "4.94065645841246544176568792868221e-324L");
403 int HasInifinity = 1, HasQuietNaN = 1;
404 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
405 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
406 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
407 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
408 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
409 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
410 "3.36210314311209350626e-4932L",
411 "2.00416836000897277799610805135016e-292L");
412 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
413 "1.18973149535723176502e+4932L",
414 "1.79769313486231580793728971405301e+308L");
Chris Lattnercbed2992008-10-05 20:40:30 +0000415
416 char MacroBuf[60];
417 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
418 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner5c8f64a2008-10-05 21:40:58 +0000419 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
420 DefineBuiltinMacro(Buf, MacroBuf);
421 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
422 DefineBuiltinMacro(Buf, MacroBuf);
423 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
424 DefineBuiltinMacro(Buf, MacroBuf);
425 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
426 DefineBuiltinMacro(Buf, MacroBuf);
427 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
428 DefineBuiltinMacro(Buf, MacroBuf);
429 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
430 DefineBuiltinMacro(Buf, MacroBuf);
431 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
432 DefineBuiltinMacro(Buf, MacroBuf);
433 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
434 DefineBuiltinMacro(Buf, MacroBuf);
435 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
436 DefineBuiltinMacro(Buf, MacroBuf);
437 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
438 DefineBuiltinMacro(Buf, MacroBuf);
439 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
440 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattnercbed2992008-10-05 20:40:30 +0000441}
442
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000443
444static void InitializePredefinedMacros(Preprocessor &PP,
445 std::vector<char> &Buf) {
Chris Lattnera023ec52008-10-05 19:32:22 +0000446 // Compiler version introspection macros.
447 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
448 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
449
450 // Currently claim to be compatible with GCC 4.2.1-5621.
451 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
452 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
453 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
454 DefineBuiltinMacro(Buf, "__GNUC__=4");
455 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
456 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. "
457 "build 5621) (dot 3)\"");
458
459
460 // Initialize language-specific preprocessor defines.
461
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000462 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
463 // and __DATE__ etc.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000464 // These should all be defined in the preprocessor according to the
465 // current language configuration.
466 DefineBuiltinMacro(Buf, "__STDC__=1");
467 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
468 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
469 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
470 else if (0) // STDC94 ?
471 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
472
473 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000474 if (PP.getLangOptions().ObjC1) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000475 DefineBuiltinMacro(Buf, "__OBJC__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000476
477 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) {
478 DefineBuiltinMacro(Buf, "__weak=");
479 DefineBuiltinMacro(Buf, "__strong=");
480 } else {
481 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))");
482 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))");
483 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
484 }
485
486 if (PP.getLangOptions().NeXTRuntime)
487 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000488 }
Chris Lattner5edfe012008-10-05 19:44:25 +0000489
Chris Lattnerd5e60992008-10-06 07:43:09 +0000490 // darwin_constant_cfstrings controls this. This is also dependent
491 // on other things like the runtime I believe. This is set even for C code.
492 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
493
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000494 if (PP.getLangOptions().ObjC2)
495 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroffae84af82007-10-31 18:42:27 +0000496
Chris Lattner9b96b152008-09-30 00:48:48 +0000497 if (PP.getLangOptions().PascalStrings)
498 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
499
Chris Lattnera023ec52008-10-05 19:32:22 +0000500 if (PP.getLangOptions().Blocks) {
501 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
502 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
Chris Lattnerce296f82008-10-05 19:32:52 +0000503 }
Chris Lattnera023ec52008-10-05 19:32:22 +0000504
505 if (PP.getLangOptions().CPlusPlus) {
506 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
507 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
508 DefineBuiltinMacro(Buf, "__GNUG__=4");
509 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
510 DefineBuiltinMacro(Buf, "__cplusplus=1");
511 DefineBuiltinMacro(Buf, "__private_extern__=extern");
512 }
513
514 // Filter out some microsoft extensions when trying to parse in ms-compat
515 // mode.
516 if (PP.getLangOptions().Microsoft) {
517 DefineBuiltinMacro(Buf, "__stdcall=");
518 DefineBuiltinMacro(Buf, "__cdecl=");
519 DefineBuiltinMacro(Buf, "_cdecl=");
520 DefineBuiltinMacro(Buf, "__ptr64=");
521 DefineBuiltinMacro(Buf, "__w64=");
522 DefineBuiltinMacro(Buf, "__forceinline=");
523 DefineBuiltinMacro(Buf, "__int8=char");
524 DefineBuiltinMacro(Buf, "__int16=short");
525 DefineBuiltinMacro(Buf, "__int32=int");
526 DefineBuiltinMacro(Buf, "__int64=long long");
527 DefineBuiltinMacro(Buf, "__declspec(X)=");
528 }
529
530
531 // Initialize target-specific preprocessor defines.
Chris Lattner5edfe012008-10-05 19:44:25 +0000532 const TargetInfo &TI = PP.getTargetInfo();
533
534 // Define type sizing macros based on the target properties.
535 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
536 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
537 DefineBuiltinMacro(Buf, "__SCHAR_MAX__=127");
Chris Lattnercbed2992008-10-05 20:40:30 +0000538
539 assert(TI.getWCharWidth() == 32 && "Only support 32-bit wchar so far");
540 DefineBuiltinMacro(Buf, "__WCHAR_MAX__=2147483647");
541 DefineBuiltinMacro(Buf, "__WCHAR_TYPE__=int");
542 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
Chris Lattner5edfe012008-10-05 19:44:25 +0000543
544 assert(TI.getShortWidth() == 16 && "Only support 16-bit short so far");
Chris Lattner5edfe012008-10-05 19:44:25 +0000545 DefineBuiltinMacro(Buf, "__SHRT_MAX__=32767");
546
Chris Lattner1be8bb92008-10-05 20:06:37 +0000547 if (TI.getIntWidth() == 32)
548 DefineBuiltinMacro(Buf, "__INT_MAX__=2147483647");
549 else if (TI.getIntWidth() == 16)
550 DefineBuiltinMacro(Buf, "__INT_MAX__=32767");
551 else
552 assert(0 && "Unknown integer size");
Sanjiv Guptafa451432008-10-31 09:52:39 +0000553
554 if (TI.getLongLongWidth() == 64)
555 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=9223372036854775807LL");
556 else if (TI.getLongLongWidth() == 32)
557 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=2147483647L");
Chris Lattner5edfe012008-10-05 19:44:25 +0000558
Chris Lattner1be8bb92008-10-05 20:06:37 +0000559 if (TI.getLongWidth() == 32)
560 DefineBuiltinMacro(Buf, "__LONG_MAX__=2147483647L");
561 else if (TI.getLongWidth() == 64)
562 DefineBuiltinMacro(Buf, "__LONG_MAX__=9223372036854775807L");
563 else if (TI.getLongWidth() == 16)
564 DefineBuiltinMacro(Buf, "__LONG_MAX__=32767L");
565 else
566 assert(0 && "Unknown long size");
Sanjiv Guptafa451432008-10-31 09:52:39 +0000567 char MacroBuf[60];
568 sprintf(MacroBuf, "__INTMAX_MAX__=%lld",
569 (TI.getIntMaxType() == TargetInfo::UnsignedLongLong?
Sanjiv Guptaf9bfd002008-10-31 10:24:31 +0000570 (1LL << (TI.getLongLongWidth() - 1)) :
571 ((1LL << (TI.getLongLongWidth() - 2)) - 1)));
Sanjiv Guptafa451432008-10-31 09:52:39 +0000572 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner1be8bb92008-10-05 20:06:37 +0000573
Sanjiv Guptafa451432008-10-31 09:52:39 +0000574 if (TI.getIntMaxType() == TargetInfo::UnsignedLongLong)
575 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long long int");
576 else if (TI.getIntMaxType() == TargetInfo::SignedLongLong)
Chris Lattner1be8bb92008-10-05 20:06:37 +0000577 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long long int");
Sanjiv Guptafa451432008-10-31 09:52:39 +0000578 else if (TI.getIntMaxType() == TargetInfo::UnsignedLong)
579 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long int");
580 else if (TI.getIntMaxType() == TargetInfo::SignedLong)
581 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long int");
582 else if (TI.getIntMaxType() == TargetInfo::UnsignedInt)
583 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned int");
584 else
585 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=int");
Chris Lattner1be8bb92008-10-05 20:06:37 +0000586
Sanjiv Guptafa451432008-10-31 09:52:39 +0000587 if (TI.getUIntMaxType() == TargetInfo::UnsignedLongLong)
588 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long long int");
589 else if (TI.getUIntMaxType() == TargetInfo::SignedLongLong)
590 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long long int");
591 else if (TI.getUIntMaxType() == TargetInfo::UnsignedLong)
592 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long int");
593 else if (TI.getUIntMaxType() == TargetInfo::SignedLong)
594 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long int");
595 else if (TI.getUIntMaxType() == TargetInfo::UnsignedInt)
596 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned int");
597 else
598 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=int");
599
600 if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLongLong)
601 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long long int");
602 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLongLong)
603 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long long int");
604 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLong)
605 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long int");
606 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLong)
607 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long int");
608 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedInt)
609 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned int");
610 else
611 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=int");
612
613 if (TI.getSizeType() == TargetInfo::UnsignedLongLong)
614 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long long int");
615 else if (TI.getSizeType() == TargetInfo::SignedLongLong)
616 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long long int");
617 else if (TI.getSizeType() == TargetInfo::UnsignedLong)
618 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long int");
619 else if (TI.getSizeType() == TargetInfo::SignedLong)
620 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long int");
621 else if (TI.getSizeType() == TargetInfo::UnsignedInt)
622 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned int");
623 else if (TI.getSizeType() == TargetInfo::SignedInt)
624 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=int");
625 else
626 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned short");
627
Chris Lattnercbed2992008-10-05 20:40:30 +0000628 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
629 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
630 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
Chris Lattner1be8bb92008-10-05 20:06:37 +0000631
Chris Lattner9b96b152008-09-30 00:48:48 +0000632
Chris Lattner77cec472007-10-10 17:48:53 +0000633 // Add __builtin_va_list typedef.
634 {
Chris Lattner5edfe012008-10-05 19:44:25 +0000635 const char *VAList = TI.getVAListDeclaration();
Chris Lattner77cec472007-10-10 17:48:53 +0000636 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
637 Buf.push_back('\n');
638 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000639
Chris Lattner5edfe012008-10-05 19:44:25 +0000640 if (const char *Prefix = TI.getUserLabelPrefix()) {
Chris Lattner3da35682008-10-05 21:49:27 +0000641 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
642 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner3f6d8cf2008-10-05 19:22:37 +0000643 }
644
Chris Lattner5edfe012008-10-05 19:44:25 +0000645 // Build configuration options. FIXME: these should be controlled by
646 // command line options or something.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000647 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
648 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
649 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
650 DefineBuiltinMacro(Buf, "__PIC__=1");
Chris Lattner5edfe012008-10-05 19:44:25 +0000651
Chris Lattner3da35682008-10-05 21:49:27 +0000652 // Macros to control C99 numerics and <float.h>
653 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
654 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
655 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
656 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
657 DefineBuiltinMacro(Buf, MacroBuf);
658
Chris Lattner5edfe012008-10-05 19:44:25 +0000659 // Get other target #defines.
660 TI.getTargetDefines(Buf);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000661
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000662 // FIXME: Should emit a #line directive here.
663}
664
665
666/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman886bf132008-01-07 04:01:26 +0000667/// which implicitly adds the builtin defines etc.
Ted Kremenek17861c52007-12-19 22:51:13 +0000668void Preprocessor::EnterMainSourceFile() {
669
670 unsigned MainFileID = SourceMgr.getMainFileID();
671
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000672 // Enter the main file source buffer.
673 EnterSourceFile(MainFileID, 0);
674
Chris Lattnerb45f05c2007-11-15 19:07:47 +0000675 // Tell the header info that the main file was entered. If the file is later
676 // #imported, it won't be re-entered.
677 if (const FileEntry *FE =
678 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
679 HeaderInfo.IncrementIncludeCount(FE);
680
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000681 std::vector<char> PrologFile;
682 PrologFile.reserve(4080);
683
684 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
685 InitializePredefinedMacros(*this, PrologFile);
686
687 // Add on the predefines from the driver.
Chris Lattner47b6a162008-04-19 23:09:31 +0000688 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000689
690 // Memory buffer must end with a null byte!
691 PrologFile.push_back(0);
692
693 // Now that we have emitted the predefined macros, #includes, etc into
694 // PrologFile, preprocess it to populate the initial preprocessor state.
695 llvm::MemoryBuffer *SB =
696 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
697 "<predefines>");
698 assert(SB && "Cannot fail to create predefined source buffer");
699 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
700 assert(FileID && "Could not create FileID for predefines?");
701
702 // Start parsing the predefines.
703 EnterSourceFile(FileID, 0);
704}
Chris Lattner4b009652007-07-25 00:24:17 +0000705
Chris Lattner4b009652007-07-25 00:24:17 +0000706
707//===----------------------------------------------------------------------===//
708// Lexer Event Handling.
709//===----------------------------------------------------------------------===//
710
711/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
712/// identifier information for the token and install it into the token.
713IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
714 const char *BufPtr) {
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000715 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattner4b009652007-07-25 00:24:17 +0000716 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
717
718 // Look up this token, see if it is a macro, or if it is a language keyword.
719 IdentifierInfo *II;
720 if (BufPtr && !Identifier.needsCleaning()) {
721 // No cleaning needed, just use the characters from the lexed buffer.
722 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
723 } else {
724 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
725 llvm::SmallVector<char, 64> IdentifierBuffer;
726 IdentifierBuffer.resize(Identifier.getLength());
727 const char *TmpBuf = &IdentifierBuffer[0];
728 unsigned Size = getSpelling(Identifier, TmpBuf);
729 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
730 }
731 Identifier.setIdentifierInfo(II);
732 return II;
733}
734
735
736/// HandleIdentifier - This callback is invoked when the lexer reads an
737/// identifier. This callback looks up the identifier in the map and/or
738/// potentially macro expands it or turns it into a named token (like 'for').
739void Preprocessor::HandleIdentifier(Token &Identifier) {
740 assert(Identifier.getIdentifierInfo() &&
741 "Can't handle identifiers without identifier info!");
742
743 IdentifierInfo &II = *Identifier.getIdentifierInfo();
744
745 // If this identifier was poisoned, and if it was not produced from a macro
746 // expansion, emit an error.
747 if (II.isPoisoned() && CurLexer) {
748 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
749 Diag(Identifier, diag::err_pp_used_poisoned_id);
750 else
751 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
752 }
753
754 // If this is a macro to be expanded, do it.
Chris Lattner7a1b0882007-10-07 08:44:20 +0000755 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000756 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
757 if (MI->isEnabled()) {
758 if (!HandleMacroExpandedIdentifier(Identifier, MI))
759 return;
760 } else {
761 // C99 6.10.3.4p2 says that a disabled macro may never again be
762 // expanded, even if it's in a context where it could be expanded in the
763 // future.
764 Identifier.setFlag(Token::DisableExpand);
765 }
766 }
Chris Lattner4b009652007-07-25 00:24:17 +0000767 }
768
769 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
770 // then we act as if it is the actual operator and not the textual
771 // representation of it.
772 if (II.isCPlusPlusOperatorKeyword())
773 Identifier.setIdentifierInfo(0);
774
775 // Change the kind of this identifier to the appropriate token kind, e.g.
776 // turning "for" into a keyword.
777 Identifier.setKind(II.getTokenID());
778
779 // If this is an extension token, diagnose its use.
Steve Naroff892bc0e2008-09-02 18:50:17 +0000780 // We avoid diagnosing tokens that originate from macro definitions.
781 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion)
Chris Lattner4b009652007-07-25 00:24:17 +0000782 Diag(Identifier, diag::ext_token_used);
783}