blob: a9e7dcbe5483a584db94f11201eb1f7622670e9b [file] [log] [blame]
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
James Dennett32740042013-12-02 17:39:27 +000010// This file implements the top level handling of macro expansion for the
Joao Matosc0d4c1b2012-08-31 21:34:27 +000011// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
Aaron Ballman2fbf9942014-03-31 13:14:44 +000015#include "clang/Basic/Attributes.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/LLVM.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/ObjCRuntime.h"
21#include "clang/Basic/SourceLocation.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000022#include "clang/Basic/TargetInfo.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000023#include "clang/Lex/CodeCompletionHandler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000024#include "clang/Lex/DirectoryLookup.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000025#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000027#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Lex/MacroInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000029#include "clang/Lex/Preprocessor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include "clang/Lex/PreprocessorLexer.h"
31#include "clang/Lex/PTHLexer.h"
32#include "clang/Lex/Token.h"
33#include "llvm/ADT/ArrayRef.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/DenseSet.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
Andy Gibbs58905d22012-11-17 19:15:38 +000039#include "llvm/ADT/SmallString.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringRef.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000043#include "llvm/ADT/StringSwitch.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000044#include "llvm/Config/llvm-config.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "llvm/Support/Casting.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000046#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkoae07f722012-09-24 20:56:28 +000047#include "llvm/Support/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000049#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstring>
Joao Matosc0d4c1b2012-08-31 21:34:27 +000053#include <ctime>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include <string>
55#include <tuple>
56#include <utility>
57
Joao Matosc0d4c1b2012-08-31 21:34:27 +000058using namespace clang;
59
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000060MacroDirective *
Richard Smith20e883e2015-04-29 23:20:19 +000061Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const {
62 if (!II->hadMacroDefinition())
63 return nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +000064 auto Pos = CurSubmoduleState->Macros.find(II);
65 return Pos == CurSubmoduleState->Macros.end() ? nullptr
66 : Pos->second.getLatest();
Joao Matosc0d4c1b2012-08-31 21:34:27 +000067}
68
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000069void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000070 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000071 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor5a4649b2012-10-11 00:46:49 +000072
Richard Smith04765ae2015-05-21 01:20:10 +000073 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Richard Smithb8b2ed62015-04-23 18:18:26 +000074 auto *OldMD = StoredMD.getLatest();
75 MD->setPrevious(OldMD);
76 StoredMD.setLatest(MD);
Richard Smith753e0072015-04-27 23:21:38 +000077 StoredMD.overrideActiveModuleMacros(*this, II);
Richard Smithb8b2ed62015-04-23 18:18:26 +000078
Richard Smith802182f2016-02-23 23:20:51 +000079 if (needModuleMacros()) {
80 // Track that we created a new macro directive, so we know we should
81 // consider building a ModuleMacro for it when we get to the end of
82 // the module.
83 PendingModuleMacroNames.push_back(II);
84 }
85
Richard Smithb8b2ed62015-04-23 18:18:26 +000086 // Set up the identifier as having associated macro history.
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000087 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000088 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000089 II->setHasMacroDefinition(false);
Richard Smith3981b172015-04-30 02:16:23 +000090 if (II->isFromAST())
Joao Matosc0d4c1b2012-08-31 21:34:27 +000091 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000092}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000093
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000094void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
95 MacroDirective *MD) {
96 assert(II && MD);
Richard Smith04765ae2015-05-21 01:20:10 +000097 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Richard Smithb8b2ed62015-04-23 18:18:26 +000098 assert(!StoredMD.getLatest() &&
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000099 "the macro history was modified before initializing it from a pch");
100 StoredMD = MD;
101 // Setup the identifier as having associated macro history.
102 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +0000103 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000104 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000105}
106
Richard Smithb8b2ed62015-04-23 18:18:26 +0000107ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
Richard Smithe56c8bc2015-04-22 00:26:11 +0000108 MacroInfo *Macro,
109 ArrayRef<ModuleMacro *> Overrides,
110 bool &New) {
111 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000112 ModuleMacro::Profile(ID, Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000113
114 void *InsertPos;
115 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
116 New = false;
117 return MM;
118 }
119
Richard Smithb8b2ed62015-04-23 18:18:26 +0000120 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000121 ModuleMacros.InsertNode(MM, InsertPos);
122
123 // Each overridden macro is now overridden by one more macro.
124 bool HidAny = false;
125 for (auto *O : Overrides) {
126 HidAny |= (O->NumOverriddenBy == 0);
127 ++O->NumOverriddenBy;
128 }
129
130 // If we were the first overrider for any macro, it's no longer a leaf.
131 auto &LeafMacros = LeafModuleMacros[II];
132 if (HidAny) {
133 LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(),
134 [](ModuleMacro *MM) {
135 return MM->NumOverriddenBy != 0;
136 }),
137 LeafMacros.end());
138 }
139
140 // The new macro is always a leaf macro.
141 LeafMacros.push_back(MM);
Richard Smith20e883e2015-04-29 23:20:19 +0000142 // The identifier now has defined macros (that may or may not be visible).
143 II->setHasMacroDefinition(true);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000144
145 New = true;
146 return MM;
147}
148
Richard Smithb8b2ed62015-04-23 18:18:26 +0000149ModuleMacro *Preprocessor::getModuleMacro(Module *Mod, IdentifierInfo *II) {
Richard Smith5dbef922015-04-22 02:09:43 +0000150 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000151 ModuleMacro::Profile(ID, Mod, II);
Richard Smith5dbef922015-04-22 02:09:43 +0000152
153 void *InsertPos;
154 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
155}
156
Richard Smith20e883e2015-04-29 23:20:19 +0000157void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
Richard Smith753e0072015-04-27 23:21:38 +0000158 ModuleMacroInfo &Info) {
Richard Smith04765ae2015-05-21 01:20:10 +0000159 assert(Info.ActiveModuleMacrosGeneration !=
160 CurSubmoduleState->VisibleModules.getGeneration() &&
Richard Smith753e0072015-04-27 23:21:38 +0000161 "don't need to update this macro name info");
Richard Smith04765ae2015-05-21 01:20:10 +0000162 Info.ActiveModuleMacrosGeneration =
163 CurSubmoduleState->VisibleModules.getGeneration();
Richard Smith753e0072015-04-27 23:21:38 +0000164
165 auto Leaf = LeafModuleMacros.find(II);
166 if (Leaf == LeafModuleMacros.end()) {
167 // No imported macros at all: nothing to do.
168 return;
169 }
170
171 Info.ActiveModuleMacros.clear();
172
173 // Every macro that's locally overridden is overridden by a visible macro.
174 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
175 for (auto *O : Info.OverriddenMacros)
176 NumHiddenOverrides[O] = -1;
177
178 // Collect all macros that are not overridden by a visible macro.
Richard Smith938d7012015-09-16 00:55:50 +0000179 llvm::SmallVector<ModuleMacro *, 16> Worklist;
180 for (auto *LeafMM : Leaf->second) {
181 assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
182 if (NumHiddenOverrides.lookup(LeafMM) == 0)
183 Worklist.push_back(LeafMM);
184 }
Richard Smith753e0072015-04-27 23:21:38 +0000185 while (!Worklist.empty()) {
186 auto *MM = Worklist.pop_back_val();
Richard Smith04765ae2015-05-21 01:20:10 +0000187 if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
Richard Smith753e0072015-04-27 23:21:38 +0000188 // We only care about collecting definitions; undefinitions only act
189 // to override other definitions.
190 if (MM->getMacroInfo())
191 Info.ActiveModuleMacros.push_back(MM);
192 } else {
193 for (auto *O : MM->overrides())
194 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
195 Worklist.push_back(O);
196 }
197 }
Richard Smith20e883e2015-04-29 23:20:19 +0000198 // Our reverse postorder walk found the macros in reverse order.
199 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
Richard Smith753e0072015-04-27 23:21:38 +0000200
201 // Determine whether the macro name is ambiguous.
Richard Smith753e0072015-04-27 23:21:38 +0000202 MacroInfo *MI = nullptr;
Richard Smith20e883e2015-04-29 23:20:19 +0000203 bool IsSystemMacro = true;
204 bool IsAmbiguous = false;
205 if (auto *MD = Info.MD) {
206 while (MD && isa<VisibilityMacroDirective>(MD))
207 MD = MD->getPrevious();
208 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
209 MI = DMD->getInfo();
210 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
211 }
Richard Smith753e0072015-04-27 23:21:38 +0000212 }
213 for (auto *Active : Info.ActiveModuleMacros) {
214 auto *NewMI = Active->getMacroInfo();
215
216 // Before marking the macro as ambiguous, check if this is a case where
217 // both macros are in system headers. If so, we trust that the system
218 // did not get it wrong. This also handles cases where Clang's own
219 // headers have a different spelling of certain system macros:
220 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
221 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
222 //
223 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
224 // overrides the system limits.h's macros, so there's no conflict here.
Richard Smith20e883e2015-04-29 23:20:19 +0000225 if (MI && NewMI != MI &&
226 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
227 IsAmbiguous = true;
228 IsSystemMacro &= Active->getOwningModule()->IsSystem ||
229 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
230 MI = NewMI;
Richard Smith753e0072015-04-27 23:21:38 +0000231 }
Richard Smith20e883e2015-04-29 23:20:19 +0000232 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
Richard Smith753e0072015-04-27 23:21:38 +0000233}
234
Richard Smith3ffa61d2015-04-30 23:10:40 +0000235void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
236 ArrayRef<ModuleMacro*> Leaf;
237 auto LeafIt = LeafModuleMacros.find(II);
238 if (LeafIt != LeafModuleMacros.end())
239 Leaf = LeafIt->second;
240 const MacroState *State = nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +0000241 auto Pos = CurSubmoduleState->Macros.find(II);
242 if (Pos != CurSubmoduleState->Macros.end())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000243 State = &Pos->second;
244
245 llvm::errs() << "MacroState " << State << " " << II->getNameStart();
246 if (State && State->isAmbiguous(*this, II))
247 llvm::errs() << " ambiguous";
Richard Smithd0014bf2015-04-30 23:42:10 +0000248 if (State && !State->getOverriddenMacros().empty()) {
Richard Smith3ffa61d2015-04-30 23:10:40 +0000249 llvm::errs() << " overrides";
250 for (auto *O : State->getOverriddenMacros())
251 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
252 }
253 llvm::errs() << "\n";
254
255 // Dump local macro directives.
256 for (auto *MD = State ? State->getLatest() : nullptr; MD;
257 MD = MD->getPrevious()) {
258 llvm::errs() << " ";
259 MD->dump();
260 }
261
262 // Dump module macros.
263 llvm::DenseSet<ModuleMacro*> Active;
264 for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
265 Active.insert(MM);
266 llvm::DenseSet<ModuleMacro*> Visited;
267 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
268 while (!Worklist.empty()) {
269 auto *MM = Worklist.pop_back_val();
270 llvm::errs() << " ModuleMacro " << MM << " "
271 << MM->getOwningModule()->getFullModuleName();
272 if (!MM->getMacroInfo())
273 llvm::errs() << " undef";
274
275 if (Active.count(MM))
276 llvm::errs() << " active";
Richard Smith04765ae2015-05-21 01:20:10 +0000277 else if (!CurSubmoduleState->VisibleModules.isVisible(
278 MM->getOwningModule()))
Richard Smith3ffa61d2015-04-30 23:10:40 +0000279 llvm::errs() << " hidden";
Richard Smith42413142015-05-15 20:05:43 +0000280 else if (MM->getMacroInfo())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000281 llvm::errs() << " overridden";
282
283 if (!MM->overrides().empty()) {
284 llvm::errs() << " overrides";
285 for (auto *O : MM->overrides()) {
286 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
287 if (Visited.insert(O).second)
288 Worklist.push_back(O);
289 }
290 }
291 llvm::errs() << "\n";
292 if (auto *MI = MM->getMacroInfo()) {
293 llvm::errs() << " ";
294 MI->dump();
295 llvm::errs() << "\n";
296 }
297 }
298}
299
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000300/// RegisterBuiltinMacro - Register the specified identifier in the identifier
301/// table and mark it as a builtin macro to be expanded.
302static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
303 // Get the identifier.
304 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
305
306 // Mark it as being a macro that is builtin.
307 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
308 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000309 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000310 return Id;
311}
312
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000313/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
314/// identifier table.
315void Preprocessor::RegisterBuiltinMacros() {
316 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
317 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
318 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
319 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
320 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
321 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
322
Aaron Ballmana0344c52014-11-14 13:44:02 +0000323 // C++ Standing Document Extensions.
Aaron Ballman416b1272015-05-11 14:09:50 +0000324 if (LangOpts.CPlusPlus)
325 Ident__has_cpp_attribute =
326 RegisterBuiltinMacro(*this, "__has_cpp_attribute");
327 else
328 Ident__has_cpp_attribute = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +0000329
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000330 // GCC Extensions.
331 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
332 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
333 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
334
Richard Smithae385082014-03-15 00:06:08 +0000335 // Microsoft Extensions.
336 if (LangOpts.MicrosoftExt) {
337 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
338 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
339 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000340 Ident__identifier = nullptr;
341 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000342 }
343
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000344 // Clang Extensions.
345 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
346 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
347 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
348 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000349 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000350 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
351 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
352 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000353 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000354
Douglas Gregorc83de302012-09-25 15:44:52 +0000355 // Modules.
Richard Smithe0fa4c82016-04-21 01:46:37 +0000356 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
357 if (!LangOpts.CurrentModule.empty())
358 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
359 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000360 Ident__MODULE__ = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000361}
362
363/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
364/// in its expansion, currently expands to that token literally.
365static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
366 const IdentifierInfo *MacroIdent,
367 Preprocessor &PP) {
368 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
369
370 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000371 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000372
373 // If the information about this identifier is out of date, update it from
374 // the external source.
375 if (II->isOutOfDate())
376 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
377
378 // If the identifier is a macro, and if that macro is enabled, it may be
379 // expanded so it's not a trivial expansion.
Richard Smith20e883e2015-04-29 23:20:19 +0000380 if (auto *ExpansionMI = PP.getMacroInfo(II))
Richard Smith3d5925b2015-04-29 23:26:13 +0000381 if (ExpansionMI->isEnabled() &&
Richard Smith20e883e2015-04-29 23:20:19 +0000382 // Fast expanding "#define X X" is ok, because X would be disabled.
383 II != MacroIdent)
384 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000385
386 // If this is an object-like macro invocation, it is safe to trivially expand
387 // it.
388 if (MI->isObjectLike()) return true;
389
390 // If this is a function-like macro invocation, it's safe to trivially expand
391 // as long as the identifier is not a macro argument.
Daniel Marjamakie4770da2015-05-29 09:15:24 +0000392 return std::find(MI->arg_begin(), MI->arg_end(), II) == MI->arg_end();
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000393}
394
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000395/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
396/// lexed is a '('. If so, consume the token and return true, if not, this
397/// method should have no observable side-effect on the lexed tokens.
398bool Preprocessor::isNextPPTokenLParen() {
399 // Do some quick tests for rejection cases.
400 unsigned Val;
401 if (CurLexer)
402 Val = CurLexer->isNextPPTokenLParen();
403 else if (CurPTHLexer)
404 Val = CurPTHLexer->isNextPPTokenLParen();
405 else
406 Val = CurTokenLexer->isNextTokenLParen();
407
408 if (Val == 2) {
409 // We have run off the end. If it's a source file we don't
410 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
411 // macro stack.
412 if (CurPPLexer)
413 return false;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000414 for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000415 if (Entry.TheLexer)
416 Val = Entry.TheLexer->isNextPPTokenLParen();
417 else if (Entry.ThePTHLexer)
418 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
419 else
420 Val = Entry.TheTokenLexer->isNextTokenLParen();
421
422 if (Val != 2)
423 break;
424
425 // Ran off the end of a source file?
426 if (Entry.ThePPLexer)
427 return false;
428 }
429 }
430
431 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
432 // have found something that isn't a '(' or we found the end of the
433 // translation unit. In either case, return false.
434 return Val == 1;
435}
436
437/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
438/// expanded as a macro, handle it and return the next token as 'Identifier'.
439bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Richard Smith20e883e2015-04-29 23:20:19 +0000440 const MacroDefinition &M) {
441 MacroInfo *MI = M.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000442
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000443 // If this is a macro expansion in the "#if !defined(x)" line for the file,
444 // then the macro could expand to different things in other contexts, we need
445 // to disable the optimization in this case.
446 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
447
448 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
449 if (MI->isBuiltinMacro()) {
Richard Smith36bd40d2015-05-04 03:15:40 +0000450 if (Callbacks)
451 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
452 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000453 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000454 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000455 }
456
457 /// Args - If this is a function-like macro expansion, this contains,
458 /// for each macro argument, the list of tokens that were provided to the
459 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000460 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000461
462 // Remember where the end of the expansion occurred. For an object-like
463 // macro, this is the identifier. For a function-like macro, this is the ')'.
464 SourceLocation ExpansionEnd = Identifier.getLocation();
465
466 // If this is a function-like macro, read the arguments.
467 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000468 // Remember that we are now parsing the arguments to a macro invocation.
469 // Preprocessor directives used inside macro arguments are not portable, and
470 // this enables the warning.
471 InMacroArgs = true;
472 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
473
474 // Finished parsing args.
475 InMacroArgs = false;
476
477 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000478 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000479
480 ++NumFnMacroExpanded;
481 } else {
482 ++NumMacroExpanded;
483 }
484
485 // Notice that this macro has been used.
486 markMacroAsUsed(MI);
487
488 // Remember where the token is expanded.
489 SourceLocation ExpandLoc = Identifier.getLocation();
490 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
491
492 if (Callbacks) {
493 if (InMacroArgs) {
494 // We can have macro expansion inside a conditional directive while
495 // reading the function macro arguments. To ensure, in that case, that
496 // MacroExpands callbacks still happen in source order, queue this
497 // callback to have it happen after the function macro callback.
498 DelayedMacroExpandsCallbacks.push_back(
Richard Smith36bd40d2015-05-04 03:15:40 +0000499 MacroExpandsInfo(Identifier, M, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000500 } else {
Richard Smith36bd40d2015-05-04 03:15:40 +0000501 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000502 if (!DelayedMacroExpandsCallbacks.empty()) {
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000503 for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000504 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000505 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
506 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000507 }
508 DelayedMacroExpandsCallbacks.clear();
509 }
510 }
511 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000512
513 // If the macro definition is ambiguous, complain.
Richard Smith20e883e2015-04-29 23:20:19 +0000514 if (M.isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000515 Diag(Identifier, diag::warn_pp_ambiguous_macro)
516 << Identifier.getIdentifierInfo();
517 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
518 << Identifier.getIdentifierInfo();
Richard Smith20e883e2015-04-29 23:20:19 +0000519 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
520 if (OtherMI != MI)
521 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
522 << Identifier.getIdentifierInfo();
523 });
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000524 }
525
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000526 // If we started lexing a macro, enter the macro expansion body.
527
528 // If this macro expands to no tokens, don't bother to push it onto the
529 // expansion stack, only to take it right back off.
530 if (MI->getNumTokens() == 0) {
531 // No need for arg info.
532 if (Args) Args->destroy(*this);
533
Eli Friedman0834a4b2013-09-19 00:41:32 +0000534 // Propagate whitespace info as if we had pushed, then popped,
535 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000536 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000537 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000538 ++NumFastMacroExpanded;
539 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000540 } else if (MI->getNumTokens() == 1 &&
541 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
542 *this)) {
543 // Otherwise, if this macro expands into a single trivially-expanded
544 // token: expand it now. This handles common cases like
545 // "#define VAL 42".
546
547 // No need for arg info.
548 if (Args) Args->destroy(*this);
549
550 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
551 // identifier to the expanded token.
552 bool isAtStartOfLine = Identifier.isAtStartOfLine();
553 bool hasLeadingSpace = Identifier.hasLeadingSpace();
554
555 // Replace the result token.
556 Identifier = MI->getReplacementToken(0);
557
558 // Restore the StartOfLine/LeadingSpace markers.
559 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
560 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
561
562 // Update the tokens location to include both its expansion and physical
563 // locations.
564 SourceLocation Loc =
565 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
566 ExpansionEnd,Identifier.getLength());
567 Identifier.setLocation(Loc);
568
569 // If this is a disabled macro or #define X X, we must mark the result as
570 // unexpandable.
571 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
572 if (MacroInfo *NewMI = getMacroInfo(NewII))
573 if (!NewMI->isEnabled() || NewMI == MI) {
574 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000575 // Don't warn for "#define X X" like "#define bool bool" from
576 // stdbool.h.
577 if (NewMI != MI || MI->isFunctionLike())
578 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000579 }
580 }
581
582 // Since this is not an identifier token, it can't be macro expanded, so
583 // we're done.
584 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000585 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000586 }
587
588 // Start expanding the macro.
589 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000590 return false;
591}
592
Richard Trieu79b45382013-07-23 18:01:49 +0000593enum Bracket {
594 Brace,
595 Paren
596};
597
598/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
599/// token vector are properly nested.
600static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
601 SmallVector<Bracket, 8> Brackets;
602 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
603 E = Tokens.end();
604 I != E; ++I) {
605 if (I->is(tok::l_paren)) {
606 Brackets.push_back(Paren);
607 } else if (I->is(tok::r_paren)) {
608 if (Brackets.empty() || Brackets.back() == Brace)
609 return false;
610 Brackets.pop_back();
611 } else if (I->is(tok::l_brace)) {
612 Brackets.push_back(Brace);
613 } else if (I->is(tok::r_brace)) {
614 if (Brackets.empty() || Brackets.back() == Paren)
615 return false;
616 Brackets.pop_back();
617 }
618 }
Alexander Kornienkoa26c4952015-12-28 15:30:42 +0000619 return Brackets.empty();
Richard Trieu79b45382013-07-23 18:01:49 +0000620}
621
622/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
623/// vector of tokens in NewTokens. The new number of arguments will be placed
624/// in NumArgs and the ranges which need to surrounded in parentheses will be
625/// in ParenHints.
626/// Returns false if the token stream cannot be changed. If this is because
627/// of an initializer list starting a macro argument, the range of those
628/// initializer lists will be place in InitLists.
629static bool GenerateNewArgTokens(Preprocessor &PP,
630 SmallVectorImpl<Token> &OldTokens,
631 SmallVectorImpl<Token> &NewTokens,
632 unsigned &NumArgs,
633 SmallVectorImpl<SourceRange> &ParenHints,
634 SmallVectorImpl<SourceRange> &InitLists) {
635 if (!CheckMatchedBrackets(OldTokens))
636 return false;
637
638 // Once it is known that the brackets are matched, only a simple count of the
639 // braces is needed.
640 unsigned Braces = 0;
641
642 // First token of a new macro argument.
643 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
644
645 // First closing brace in a new macro argument. Used to generate
646 // SourceRanges for InitLists.
647 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
648 NumArgs = 0;
649 Token TempToken;
650 // Set to true when a macro separator token is found inside a braced list.
651 // If true, the fixed argument spans multiple old arguments and ParenHints
652 // will be updated.
653 bool FoundSeparatorToken = false;
654 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
655 E = OldTokens.end();
656 I != E; ++I) {
657 if (I->is(tok::l_brace)) {
658 ++Braces;
659 } else if (I->is(tok::r_brace)) {
660 --Braces;
661 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
662 ClosingBrace = I;
663 } else if (I->is(tok::eof)) {
664 // EOF token is used to separate macro arguments
665 if (Braces != 0) {
666 // Assume comma separator is actually braced list separator and change
667 // it back to a comma.
668 FoundSeparatorToken = true;
669 I->setKind(tok::comma);
670 I->setLength(1);
671 } else { // Braces == 0
672 // Separator token still separates arguments.
673 ++NumArgs;
674
675 // If the argument starts with a brace, it can't be fixed with
676 // parentheses. A different diagnostic will be given.
677 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
678 InitLists.push_back(
679 SourceRange(ArgStartIterator->getLocation(),
680 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
681 ClosingBrace = E;
682 }
683
684 // Add left paren
685 if (FoundSeparatorToken) {
686 TempToken.startToken();
687 TempToken.setKind(tok::l_paren);
688 TempToken.setLocation(ArgStartIterator->getLocation());
689 TempToken.setLength(0);
690 NewTokens.push_back(TempToken);
691 }
692
693 // Copy over argument tokens
694 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
695
696 // Add right paren and store the paren locations in ParenHints
697 if (FoundSeparatorToken) {
698 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
699 TempToken.startToken();
700 TempToken.setKind(tok::r_paren);
701 TempToken.setLocation(Loc);
702 TempToken.setLength(0);
703 NewTokens.push_back(TempToken);
704 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
705 Loc));
706 }
707
708 // Copy separator token
709 NewTokens.push_back(*I);
710
711 // Reset values
712 ArgStartIterator = I + 1;
713 FoundSeparatorToken = false;
714 }
715 }
716 }
717
718 return !ParenHints.empty() && InitLists.empty();
719}
720
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000721/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
722/// token is the '(' of the macro, this method is invoked to read all of the
723/// actual arguments specified for the macro invocation. This returns null on
724/// error.
725MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
726 MacroInfo *MI,
727 SourceLocation &MacroEnd) {
728 // The number of fixed arguments to parse.
729 unsigned NumFixedArgsLeft = MI->getNumArgs();
730 bool isVariadic = MI->isVariadic();
731
732 // Outer loop, while there are more arguments, keep reading them.
733 Token Tok;
734
735 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
736 // an argument value in a macro could expand to ',' or '(' or ')'.
737 LexUnexpandedToken(Tok);
738 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
739
740 // ArgTokens - Build up a list of tokens that make up each argument. Each
741 // argument is separated by an EOF token. Use a SmallVector so we can avoid
742 // heap allocations in the common case.
743 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000744 bool ContainsCodeCompletionTok = false;
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000745 bool FoundElidedComma = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000746
Richard Trieu79b45382013-07-23 18:01:49 +0000747 SourceLocation TooManyArgsLoc;
748
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000749 unsigned NumActuals = 0;
750 while (Tok.isNot(tok::r_paren)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000751 if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000752 break;
753
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000754 assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000755 "only expect argument separators here");
756
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000757 size_t ArgTokenStart = ArgTokens.size();
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000758 SourceLocation ArgStartLoc = Tok.getLocation();
759
760 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
761 // that we already consumed the first one.
762 unsigned NumParens = 0;
763
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000764 while (true) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000765 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
766 // an argument value in a macro could expand to ',' or '(' or ')'.
767 LexUnexpandedToken(Tok);
768
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000769 if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000770 if (!ContainsCodeCompletionTok) {
771 Diag(MacroName, diag::err_unterm_macro_invoc);
772 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
773 << MacroName.getIdentifierInfo();
774 // Do not lose the EOF/EOD. Return it to the client.
775 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000776 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000777 }
David Blaikie2eabcc92016-02-09 18:52:09 +0000778 // Do not lose the EOF/EOD.
779 auto Toks = llvm::make_unique<Token[]>(1);
780 Toks[0] = Tok;
781 EnterTokenStream(std::move(Toks), 1, true);
782 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000783 } else if (Tok.is(tok::r_paren)) {
784 // If we found the ) token, the macro arg list is done.
785 if (NumParens-- == 0) {
786 MacroEnd = Tok.getLocation();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000787 if (!ArgTokens.empty() &&
788 ArgTokens.back().commaAfterElided()) {
789 FoundElidedComma = true;
790 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000791 break;
792 }
793 } else if (Tok.is(tok::l_paren)) {
794 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000795 } else if (Tok.is(tok::comma) && NumParens == 0 &&
796 !(Tok.getFlags() & Token::IgnoredComma)) {
797 // In Microsoft-compatibility mode, single commas from nested macro
798 // expansions should not be considered as argument separators. We test
799 // for this with the IgnoredComma token flag above.
800
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000801 // Comma ends this argument if there are more fixed arguments expected.
802 // However, if this is a variadic macro, and this is part of the
803 // variadic part, then the comma is just an argument token.
804 if (!isVariadic) break;
805 if (NumFixedArgsLeft > 1)
806 break;
807 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
808 // If this is a comment token in the argument list and we're just in
809 // -C mode (not -CC mode), discard the comment.
810 continue;
David Majnemerd8dee1f2015-03-18 07:53:20 +0000811 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000812 // Reading macro arguments can cause macros that we are currently
813 // expanding from to be popped off the expansion stack. Doing so causes
814 // them to be reenabled for expansion. Here we record whether any
815 // identifiers we lex as macro arguments correspond to disabled macros.
816 // If so, we mark the token as noexpand. This is a subtle aspect of
817 // C99 6.10.3.4p2.
818 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
819 if (!MI->isEnabled())
820 Tok.setFlag(Token::DisableExpand);
821 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000822 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000823 if (CodeComplete)
824 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
825 MI, NumActuals);
826 // Don't mark that we reached the code-completion point because the
827 // parser is going to handle the token and there will be another
828 // code-completion callback.
829 }
830
831 ArgTokens.push_back(Tok);
832 }
833
834 // If this was an empty argument list foo(), don't add this as an empty
835 // argument.
836 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
837 break;
838
839 // If this is not a variadic macro, and too many args were specified, emit
840 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000841 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000842 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000843 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
844 else
845 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000846 }
847
Richard Trieu79b45382013-07-23 18:01:49 +0000848 // Empty arguments are standard in C99 and C++0x, and are supported as an
849 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000850 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000851 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000852 diag::warn_cxx98_compat_empty_fnmacro_arg :
853 diag::ext_empty_fnmacro_arg);
854
855 // Add a marker EOF token to the end of the token list for this argument.
856 Token EOFTok;
857 EOFTok.startToken();
858 EOFTok.setKind(tok::eof);
859 EOFTok.setLocation(Tok.getLocation());
860 EOFTok.setLength(0);
861 ArgTokens.push_back(EOFTok);
862 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000863 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000864 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000865 }
866
867 // Okay, we either found the r_paren. Check to see if we parsed too few
868 // arguments.
869 unsigned MinArgsExpected = MI->getNumArgs();
870
Richard Trieu79b45382013-07-23 18:01:49 +0000871 // If this is not a variadic macro, and too many args were specified, emit
872 // an error.
873 if (!isVariadic && NumActuals > MinArgsExpected &&
874 !ContainsCodeCompletionTok) {
875 // Emit the diagnostic at the macro name in case there is a missing ).
876 // Emitting it at the , could be far away from the macro name.
877 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
878 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
879 << MacroName.getIdentifierInfo();
880
881 // Commas from braced initializer lists will be treated as argument
882 // separators inside macros. Attempt to correct for this with parentheses.
883 // TODO: See if this can be generalized to angle brackets for templates
884 // inside macro arguments.
885
Bob Wilson57217352013-07-27 21:59:57 +0000886 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000887 unsigned FixedNumArgs = 0;
888 SmallVector<SourceRange, 4> ParenHints, InitLists;
889 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
890 ParenHints, InitLists)) {
891 if (!InitLists.empty()) {
892 DiagnosticBuilder DB =
893 Diag(MacroName,
894 diag::note_init_list_at_beginning_of_macro_argument);
Craig Toppere335f252015-10-04 04:53:55 +0000895 for (SourceRange Range : InitLists)
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000896 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000897 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000898 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000899 }
900 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000901 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000902
903 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Craig Toppere335f252015-10-04 04:53:55 +0000904 for (SourceRange ParenLocation : ParenHints) {
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000905 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
906 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000907 }
908 ArgTokens.swap(FixedArgTokens);
909 NumActuals = FixedNumArgs;
910 }
911
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000912 // See MacroArgs instance var for description of this.
913 bool isVarargsElided = false;
914
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000915 if (ContainsCodeCompletionTok) {
916 // Recover from not-fully-formed macro invocation during code-completion.
917 Token EOFTok;
918 EOFTok.startToken();
919 EOFTok.setKind(tok::eof);
920 EOFTok.setLocation(Tok.getLocation());
921 EOFTok.setLength(0);
922 for (; NumActuals < MinArgsExpected; ++NumActuals)
923 ArgTokens.push_back(EOFTok);
924 }
925
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000926 if (NumActuals < MinArgsExpected) {
927 // There are several cases where too few arguments is ok, handle them now.
928 if (NumActuals == 0 && MinArgsExpected == 1) {
929 // #define A(X) or #define A(...) ---> A()
930
931 // If there is exactly one argument, and that argument is missing,
932 // then we have an empty "()" argument empty list. This is fine, even if
933 // the macro expects one argument (the argument is just empty).
934 isVarargsElided = MI->isVariadic();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000935 } else if ((FoundElidedComma || MI->isVariadic()) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000936 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
937 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
938 // Varargs where the named vararg parameter is missing: OK as extension.
939 // #define A(x, ...)
940 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000941 //
942 // If the macro contains the comma pasting extension, the diagnostic
943 // is suppressed; we know we'll get another diagnostic later.
944 if (!MI->hasCommaPasting()) {
945 Diag(Tok, diag::ext_missing_varargs_arg);
946 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
947 << MacroName.getIdentifierInfo();
948 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000949
950 // Remember this occurred, allowing us to elide the comma when used for
951 // cases like:
952 // #define A(x, foo...) blah(a, ## foo)
953 // #define B(x, ...) blah(a, ## __VA_ARGS__)
954 // #define C(...) blah(a, ## __VA_ARGS__)
955 // A(x) B(x) C()
956 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000957 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000958 // Otherwise, emit the error.
959 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000960 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
961 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000962 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000963 }
964
965 // Add a marker EOF token to the end of the token list for this argument.
966 SourceLocation EndLoc = Tok.getLocation();
967 Tok.startToken();
968 Tok.setKind(tok::eof);
969 Tok.setLocation(EndLoc);
970 Tok.setLength(0);
971 ArgTokens.push_back(Tok);
972
973 // If we expect two arguments, add both as empty.
974 if (NumActuals == 0 && MinArgsExpected == 2)
975 ArgTokens.push_back(Tok);
976
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000977 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
978 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000979 // Emit the diagnostic at the macro name in case there is a missing ).
980 // Emitting it at the , could be far away from the macro name.
981 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000982 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
983 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000984 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000985 }
986
987 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
988}
989
990/// \brief Keeps macro expanded tokens for TokenLexers.
991//
992/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
993/// going to lex in the cache and when it finishes the tokens are removed
994/// from the end of the cache.
995Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
996 ArrayRef<Token> tokens) {
997 assert(tokLexer);
998 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000999 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001000
1001 size_t newIndex = MacroExpandedTokens.size();
1002 bool cacheNeedsToGrow = tokens.size() >
1003 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
1004 MacroExpandedTokens.append(tokens.begin(), tokens.end());
1005
1006 if (cacheNeedsToGrow) {
1007 // Go through all the TokenLexers whose 'Tokens' pointer points in the
1008 // buffer and update the pointers to the (potential) new buffer array.
Erik Verbruggene4fd6522016-10-26 13:06:13 +00001009 for (const auto &Lexer : MacroExpandingLexersStack) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001010 TokenLexer *prevLexer;
1011 size_t tokIndex;
Erik Verbruggene4fd6522016-10-26 13:06:13 +00001012 std::tie(prevLexer, tokIndex) = Lexer;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001013 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
1014 }
1015 }
1016
1017 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1018 return MacroExpandedTokens.data() + newIndex;
1019}
1020
1021void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1022 assert(!MacroExpandingLexersStack.empty());
1023 size_t tokIndex = MacroExpandingLexersStack.back().second;
1024 assert(tokIndex < MacroExpandedTokens.size());
1025 // Pop the cached macro expanded tokens from the end.
1026 MacroExpandedTokens.resize(tokIndex);
1027 MacroExpandingLexersStack.pop_back();
1028}
1029
1030/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1031/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1032/// the identifier tokens inserted.
1033static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1034 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001035 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001036 struct tm *TM = localtime(&TT);
1037
1038 static const char * const Months[] = {
1039 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1040 };
1041
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001042 {
1043 SmallString<32> TmpBuffer;
1044 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1045 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1046 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001047 Token TmpTok;
1048 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001049 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001050 DATELoc = TmpTok.getLocation();
1051 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001052
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001053 {
1054 SmallString<32> TmpBuffer;
1055 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1056 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1057 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001058 Token TmpTok;
1059 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001060 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001061 TIMELoc = TmpTok.getLocation();
1062 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001063}
1064
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001065/// HasFeature - Return true if we recognize and implement the feature
1066/// specified by the identifier as a standard language feature.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001067static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001068 const LangOptions &LangOpts = PP.getLangOpts();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001069
1070 // Normalize the feature name, __foo__ becomes foo.
1071 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
1072 Feature = Feature.substr(2, Feature.size() - 4);
1073
1074 return llvm::StringSwitch<bool>(Feature)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001075 .Case("address_sanitizer",
1076 LangOpts.Sanitize.hasOneOf(SanitizerKind::Address |
1077 SanitizerKind::KernelAddress))
Douglas Gregor4c27d102015-06-29 18:11:42 +00001078 .Case("assume_nonnull", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001079 .Case("attribute_analyzer_noreturn", true)
1080 .Case("attribute_availability", true)
1081 .Case("attribute_availability_with_message", true)
Bob Wilsonb111ec92015-03-02 19:01:14 +00001082 .Case("attribute_availability_app_extension", true)
Jordan Rose7e5de9c2015-07-16 22:30:10 +00001083 .Case("attribute_availability_with_version_underscores", true)
Tim Northover7a73cc72015-10-30 16:30:49 +00001084 .Case("attribute_availability_tvos", true)
1085 .Case("attribute_availability_watchos", true)
Manman Ren6731d732016-02-22 18:24:30 +00001086 .Case("attribute_availability_with_strict", true)
Manman Ren75bc6762016-03-21 17:30:55 +00001087 .Case("attribute_availability_with_replacement", true)
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +00001088 .Case("attribute_availability_in_templates", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001089 .Case("attribute_cf_returns_not_retained", true)
1090 .Case("attribute_cf_returns_retained", true)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00001091 .Case("attribute_cf_returns_on_parameters", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001092 .Case("attribute_deprecated_with_message", true)
Manman Renc7890fe2016-03-16 18:50:49 +00001093 .Case("attribute_deprecated_with_replacement", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001094 .Case("attribute_ext_vector_type", true)
1095 .Case("attribute_ns_returns_not_retained", true)
1096 .Case("attribute_ns_returns_retained", true)
1097 .Case("attribute_ns_consumes_self", true)
1098 .Case("attribute_ns_consumed", true)
1099 .Case("attribute_cf_consumed", true)
1100 .Case("attribute_objc_ivar_unused", true)
1101 .Case("attribute_objc_method_family", true)
1102 .Case("attribute_overloadable", true)
1103 .Case("attribute_unavailable_with_message", true)
1104 .Case("attribute_unused_on_fields", true)
1105 .Case("blocks", LangOpts.Blocks)
1106 .Case("c_thread_safety_attributes", true)
1107 .Case("cxx_exceptions", LangOpts.CXXExceptions)
Reid Kleckner6cf4a6b2015-08-13 17:56:49 +00001108 .Case("cxx_rtti", LangOpts.RTTI && LangOpts.RTTIData)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001109 .Case("enumerator_attributes", true)
Douglas Gregor4c27d102015-06-29 18:11:42 +00001110 .Case("nullability", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001111 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
1112 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
1113 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
Derek Bruening256c2e12016-04-21 21:32:04 +00001114 .Case("efficiency_sanitizer",
1115 LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency))
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001116 // Objective-C features
1117 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
1118 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00001119 .Case("objc_arc_weak", LangOpts.ObjCWeak)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001120 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
1121 .Case("objc_fixed_enum", LangOpts.ObjC2)
1122 .Case("objc_instancetype", LangOpts.ObjC2)
Douglas Gregorab209d82015-07-07 03:58:42 +00001123 .Case("objc_kindof", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001124 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
1125 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
1126 .Case("objc_property_explicit_atomic",
1127 true) // Does clang support explicit "atomic" keyword?
1128 .Case("objc_protocol_qualifier_mangling", true)
1129 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
1130 .Case("ownership_holds", true)
1131 .Case("ownership_returns", true)
1132 .Case("ownership_takes", true)
1133 .Case("objc_bool", true)
1134 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
1135 .Case("objc_array_literals", LangOpts.ObjC2)
1136 .Case("objc_dictionary_literals", LangOpts.ObjC2)
1137 .Case("objc_boxed_expressions", LangOpts.ObjC2)
Alex Denisovfde64952015-06-26 05:28:36 +00001138 .Case("objc_boxed_nsvalue_expressions", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001139 .Case("arc_cf_code_audited", true)
John McCall28592582015-02-01 22:34:06 +00001140 .Case("objc_bridge_id", true)
1141 .Case("objc_bridge_id_on_typedefs", true)
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001142 .Case("objc_generics", LangOpts.ObjC2)
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001143 .Case("objc_generics_variance", LangOpts.ObjC2)
Manman Ren515758e2016-03-10 23:51:03 +00001144 .Case("objc_class_property", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001145 // C11 features
1146 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +00001147 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001148 .Case("c_atomic", LangOpts.C11)
1149 .Case("c_generic_selections", LangOpts.C11)
1150 .Case("c_static_assert", LangOpts.C11)
1151 .Case("c_thread_local",
1152 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
1153 // C++11 features
1154 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
1155 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
1156 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +00001157 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001158 .Case("cxx_atomic", LangOpts.CPlusPlus11)
1159 .Case("cxx_attributes", LangOpts.CPlusPlus11)
1160 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
1161 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
1162 .Case("cxx_decltype", LangOpts.CPlusPlus11)
1163 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
1164 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
1165 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
1166 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
1167 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
1168 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
1169 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
1170 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
1171 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
1172 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
1173 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
1174 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
1175 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
1176 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
1177 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
1178 .Case("cxx_override_control", LangOpts.CPlusPlus11)
1179 .Case("cxx_range_for", LangOpts.CPlusPlus11)
1180 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
1181 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
1182 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
1183 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
1184 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
1185 .Case("cxx_thread_local",
1186 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
1187 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
1188 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
1189 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
1190 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
1191 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Richard Smith27143d82016-09-29 00:08:05 +00001192 // C++14 features
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001193 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
1194 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
1195 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
1196 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
1197 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
1198 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
1199 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
1200 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
1201 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
Richard Smith27143d82016-09-29 00:08:05 +00001202 // NOTE: For features covered by SD-6, it is preferable to provide *only*
1203 // the SD-6 macro and not a __has_feature check.
1204
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001205 // C++ TSes
1206 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
1207 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
1208 // FIXME: Should this be __has_feature or __has_extension?
1209 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
1210 // Type traits
David Majnemer3e5e05a2016-05-24 17:21:42 +00001211 // N.B. Additional type traits should not be added to the following list.
1212 // Instead, they should be detected by has_extension.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001213 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
1214 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
1215 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
1216 .Case("has_trivial_assign", LangOpts.CPlusPlus)
1217 .Case("has_trivial_copy", LangOpts.CPlusPlus)
1218 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
1219 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
1220 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
1221 .Case("is_abstract", LangOpts.CPlusPlus)
1222 .Case("is_base_of", LangOpts.CPlusPlus)
1223 .Case("is_class", LangOpts.CPlusPlus)
1224 .Case("is_constructible", LangOpts.CPlusPlus)
1225 .Case("is_convertible_to", LangOpts.CPlusPlus)
1226 .Case("is_empty", LangOpts.CPlusPlus)
1227 .Case("is_enum", LangOpts.CPlusPlus)
1228 .Case("is_final", LangOpts.CPlusPlus)
1229 .Case("is_literal", LangOpts.CPlusPlus)
David Majnemer3e5e05a2016-05-24 17:21:42 +00001230 .Case("is_standard_layout", LangOpts.CPlusPlus)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001231 .Case("is_pod", LangOpts.CPlusPlus)
1232 .Case("is_polymorphic", LangOpts.CPlusPlus)
David Majnemer3e5e05a2016-05-24 17:21:42 +00001233 .Case("is_sealed", LangOpts.CPlusPlus && LangOpts.MicrosoftExt)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001234 .Case("is_trivial", LangOpts.CPlusPlus)
1235 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1236 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1237 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1238 .Case("is_union", LangOpts.CPlusPlus)
1239 .Case("modules", LangOpts.Modules)
Peter Collingbournec4122c12015-06-15 21:08:13 +00001240 .Case("safe_stack", LangOpts.Sanitize.has(SanitizerKind::SafeStack))
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001241 .Case("tls", PP.getTargetInfo().isTLSSupported())
1242 .Case("underlying_type", LangOpts.CPlusPlus)
1243 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001244}
1245
1246/// HasExtension - Return true if we recognize and implement the feature
1247/// specified by the identifier, either as an extension or a standard language
1248/// feature.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001249static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
1250 if (HasFeature(PP, Extension))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001251 return true;
1252
1253 // If the use of an extension results in an error diagnostic, extensions are
1254 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001255 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1256 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001257 return false;
1258
1259 const LangOptions &LangOpts = PP.getLangOpts();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001260
1261 // Normalize the extension name, __foo__ becomes foo.
1262 if (Extension.startswith("__") && Extension.endswith("__") &&
1263 Extension.size() >= 4)
1264 Extension = Extension.substr(2, Extension.size() - 4);
1265
1266 // Because we inherit the feature list from HasFeature, this string switch
1267 // must be less restrictive than HasFeature's.
1268 return llvm::StringSwitch<bool>(Extension)
1269 // C11 features supported by other languages as extensions.
1270 .Case("c_alignas", true)
Nico Weber736a9932014-12-03 01:25:49 +00001271 .Case("c_alignof", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001272 .Case("c_atomic", true)
1273 .Case("c_generic_selections", true)
1274 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001275 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001276 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001277 .Case("cxx_atomic", LangOpts.CPlusPlus)
1278 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1279 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1280 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1281 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1282 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1283 .Case("cxx_override_control", LangOpts.CPlusPlus)
1284 .Case("cxx_range_for", LangOpts.CPlusPlus)
1285 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1286 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Eric Fiselier7aa0d4a2015-05-12 22:37:23 +00001287 .Case("cxx_variadic_templates", LangOpts.CPlusPlus)
Richard Smith27143d82016-09-29 00:08:05 +00001288 // C++14 features supported by other languages as extensions.
Richard Smith0a715422013-05-07 19:32:56 +00001289 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001290 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001291 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001292 .Default(false);
1293}
1294
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001295/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1296/// or '__has_include_next("path")' expression.
1297/// Returns true if successful.
1298static bool EvaluateHasIncludeCommon(Token &Tok,
1299 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001300 const DirectoryLookup *LookupFrom,
1301 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001302 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001303 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001304 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001305
Aaron Ballman6ce00002013-01-16 19:32:21 +00001306 // These expressions are only allowed within a preprocessor directive.
1307 if (!PP.isParsingIfOrElifDirective()) {
1308 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
Benjamin Kramer0a126ad2015-03-29 19:05:27 +00001309 // Return a valid identifier token.
1310 assert(Tok.is(tok::identifier));
1311 Tok.setIdentifierInfo(II);
Aaron Ballman6ce00002013-01-16 19:32:21 +00001312 return false;
1313 }
1314
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001315 // Get '('.
1316 PP.LexNonComment(Tok);
1317
1318 // Ensure we have a '('.
1319 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001320 // No '(', use end of last token.
1321 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001322 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001323 // If the next token looks like a filename or the start of one,
1324 // assume it is and process it as such.
1325 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1326 !Tok.is(tok::less))
1327 return false;
1328 } else {
1329 // Save '(' location for possible missing ')' message.
1330 LParenLoc = Tok.getLocation();
1331
Eli Friedmanec94b612013-01-09 02:20:00 +00001332 if (PP.getCurrentLexer()) {
1333 // Get the file name.
1334 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1335 } else {
1336 // We're in a macro, so we can't use LexIncludeFilename; just
1337 // grab the next token.
1338 PP.Lex(Tok);
1339 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001340 }
1341
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001342 // Reserve a buffer to get the spelling.
1343 SmallString<128> FilenameBuffer;
1344 StringRef Filename;
1345 SourceLocation EndLoc;
1346
1347 switch (Tok.getKind()) {
1348 case tok::eod:
1349 // If the token kind is EOD, the error has already been diagnosed.
1350 return false;
1351
1352 case tok::angle_string_literal:
1353 case tok::string_literal: {
1354 bool Invalid = false;
1355 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1356 if (Invalid)
1357 return false;
1358 break;
1359 }
1360
1361 case tok::less:
1362 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1363 // case, glue the tokens together into FilenameBuffer and interpret those.
1364 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001365 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1366 // Let the caller know a <eod> was found by changing the Token kind.
1367 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001368 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001369 }
Yaron Keren92e1b622015-03-18 10:17:07 +00001370 Filename = FilenameBuffer;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001371 break;
1372 default:
1373 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1374 return false;
1375 }
1376
Richard Trieuda031982012-10-22 20:28:48 +00001377 SourceLocation FilenameLoc = Tok.getLocation();
1378
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001379 // Get ')'.
1380 PP.LexNonComment(Tok);
1381
1382 // Ensure we have a trailing ).
1383 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001384 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1385 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001386 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001387 return false;
1388 }
1389
1390 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1391 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1392 // error.
1393 if (Filename.empty())
1394 return false;
1395
1396 // Search include directories.
1397 const DirectoryLookup *CurDir;
1398 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001399 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1400 CurDir, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001401
1402 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001403 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001404}
1405
1406/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1407/// Returns true if successful.
1408static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1409 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001410 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001411}
1412
1413/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1414/// Returns true if successful.
1415static bool EvaluateHasIncludeNext(Token &Tok,
1416 IdentifierInfo *II, Preprocessor &PP) {
1417 // __has_include_next is like __has_include, except that we start
1418 // searching after the current found directory. If we can't do this,
1419 // issue a diagnostic.
Yaron Kerenbc5986f2015-02-19 11:21:11 +00001420 // FIXME: Factor out duplication with
Richard Smith25d50752014-10-20 00:15:49 +00001421 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001422 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001423 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00001424 if (PP.isInPrimaryFile() && PP.getLangOpts().IsHeaderFile) {
1425 // If the main file is a header, then it's either for PCH/AST generation,
1426 // or libclang opened it. Either way, handle it as a normal include below
1427 // and do not complain about __has_include_next.
1428 } else if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001429 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001430 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001431 } else if (PP.getCurrentSubmodule()) {
1432 // Start looking up in the directory *after* the one in which the current
1433 // file would be found, if any.
1434 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1435 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1436 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001437 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001438 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1439 } else {
1440 // Start looking up in the next directory.
1441 ++Lookup;
1442 }
1443
Richard Smith25d50752014-10-20 00:15:49 +00001444 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001445}
1446
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001447/// \brief Process single-argument builtin feature-like macros that return
1448/// integer values.
1449static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1450 Token &Tok, IdentifierInfo *II,
1451 Preprocessor &PP,
1452 llvm::function_ref<
1453 int(Token &Tok,
1454 bool &HasLexedNextTok)> Op) {
1455 // Parse the initial '('.
1456 PP.LexUnexpandedToken(Tok);
Douglas Gregorc83de302012-09-25 15:44:52 +00001457 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001458 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1459 << tok::l_paren;
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001460
1461 // Provide a dummy '0' value on output stream to elide further errors.
1462 if (!Tok.isOneOf(tok::eof, tok::eod)) {
1463 OS << 0;
1464 Tok.setKind(tok::numeric_constant);
1465 }
1466 return;
Douglas Gregorc83de302012-09-25 15:44:52 +00001467 }
1468
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001469 unsigned ParenDepth = 1;
Douglas Gregorc83de302012-09-25 15:44:52 +00001470 SourceLocation LParenLoc = Tok.getLocation();
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001471 llvm::Optional<int> Result;
Douglas Gregorc83de302012-09-25 15:44:52 +00001472
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001473 Token ResultTok;
1474 bool SuppressDiagnostic = false;
1475 while (true) {
1476 // Parse next token.
1477 PP.LexUnexpandedToken(Tok);
Douglas Gregorc83de302012-09-25 15:44:52 +00001478
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001479already_lexed:
1480 switch (Tok.getKind()) {
1481 case tok::eof:
1482 case tok::eod:
1483 // Don't provide even a dummy value if the eod or eof marker is
1484 // reached. Simply provide a diagnostic.
1485 PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1486 return;
1487
1488 case tok::comma:
1489 if (!SuppressDiagnostic) {
1490 PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1491 SuppressDiagnostic = true;
1492 }
1493 continue;
1494
1495 case tok::l_paren:
1496 ++ParenDepth;
1497 if (Result.hasValue())
1498 break;
1499 if (!SuppressDiagnostic) {
1500 PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1501 SuppressDiagnostic = true;
1502 }
1503 continue;
1504
1505 case tok::r_paren:
1506 if (--ParenDepth > 0)
1507 continue;
1508
1509 // The last ')' has been reached; return the value if one found or
1510 // a diagnostic and a dummy value.
1511 if (Result.hasValue())
1512 OS << Result.getValue();
1513 else {
1514 OS << 0;
1515 if (!SuppressDiagnostic)
1516 PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1517 }
1518 Tok.setKind(tok::numeric_constant);
1519 return;
1520
1521 default: {
1522 // Parse the macro argument, if one not found so far.
1523 if (Result.hasValue())
1524 break;
1525
1526 bool HasLexedNextToken = false;
1527 Result = Op(Tok, HasLexedNextToken);
1528 ResultTok = Tok;
1529 if (HasLexedNextToken)
1530 goto already_lexed;
1531 continue;
1532 }
1533 }
1534
1535 // Diagnose missing ')'.
1536 if (!SuppressDiagnostic) {
1537 if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1538 if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1539 Diag << LastII;
1540 else
1541 Diag << ResultTok.getKind();
1542 Diag << tok::r_paren << ResultTok.getLocation();
1543 }
1544 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1545 SuppressDiagnostic = true;
1546 }
Douglas Gregorc83de302012-09-25 15:44:52 +00001547 }
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001548}
Douglas Gregorc83de302012-09-25 15:44:52 +00001549
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001550/// \brief Helper function to return the IdentifierInfo structure of a Token
1551/// or generate a diagnostic if none available.
1552static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok,
1553 Preprocessor &PP,
1554 signed DiagID) {
1555 IdentifierInfo *II;
1556 if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1557 return II;
Douglas Gregorc83de302012-09-25 15:44:52 +00001558
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001559 PP.Diag(Tok.getLocation(), DiagID);
1560 return nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +00001561}
1562
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001563/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1564/// as a builtin macro, handle it and return the next token as 'Tok'.
1565void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1566 // Figure out which token this is.
1567 IdentifierInfo *II = Tok.getIdentifierInfo();
1568 assert(II && "Can't be a macro without id info!");
1569
1570 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1571 // invoke the pragma handler, then lex the token after it.
1572 if (II == Ident_Pragma)
1573 return Handle_Pragma(Tok);
1574 else if (II == Ident__pragma) // in non-MS mode this is null
1575 return HandleMicrosoft__pragma(Tok);
1576
1577 ++NumBuiltinMacroExpanded;
1578
1579 SmallString<128> TmpBuffer;
1580 llvm::raw_svector_ostream OS(TmpBuffer);
1581
1582 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001583 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001584 Tok.clearFlag(Token::NeedsCleaning);
1585
1586 if (II == Ident__LINE__) {
1587 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1588 // source file) of the current source line (an integer constant)". This can
1589 // be affected by #line.
1590 SourceLocation Loc = Tok.getLocation();
1591
1592 // Advance to the location of the first _, this might not be the first byte
1593 // of the token if it starts with an escaped newline.
1594 Loc = AdvanceToTokenCharacter(Loc, 0);
1595
1596 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1597 // a macro expansion. This doesn't matter for object-like macros, but
1598 // can matter for a function-like macro that expands to contain __LINE__.
1599 // Skip down through expansion points until we find a file loc for the
1600 // end of the expansion history.
1601 Loc = SourceMgr.getExpansionRange(Loc).second;
1602 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1603
1604 // __LINE__ expands to a simple numeric value.
1605 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1606 Tok.setKind(tok::numeric_constant);
1607 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1608 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1609 // character string literal)". This can be affected by #line.
1610 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1611
1612 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1613 // #include stack instead of the current file.
1614 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1615 SourceLocation NextLoc = PLoc.getIncludeLoc();
1616 while (NextLoc.isValid()) {
1617 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1618 if (PLoc.isInvalid())
1619 break;
1620
1621 NextLoc = PLoc.getIncludeLoc();
1622 }
1623 }
1624
1625 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1626 SmallString<128> FN;
1627 if (PLoc.isValid()) {
1628 FN += PLoc.getFilename();
1629 Lexer::Stringify(FN);
Yaron Keren09fb7c62015-03-10 07:33:23 +00001630 OS << '"' << FN << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001631 }
1632 Tok.setKind(tok::string_literal);
1633 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001634 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001635 if (!DATELoc.isValid())
1636 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1637 Tok.setKind(tok::string_literal);
1638 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1639 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1640 Tok.getLocation(),
1641 Tok.getLength()));
1642 return;
1643 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001644 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001645 if (!TIMELoc.isValid())
1646 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1647 Tok.setKind(tok::string_literal);
1648 Tok.setLength(strlen("\"hh:mm:ss\""));
1649 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1650 Tok.getLocation(),
1651 Tok.getLength()));
1652 return;
1653 } else if (II == Ident__INCLUDE_LEVEL__) {
1654 // Compute the presumed include depth of this token. This can be affected
1655 // by GNU line markers.
1656 unsigned Depth = 0;
1657
1658 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1659 if (PLoc.isValid()) {
1660 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1661 for (; PLoc.isValid(); ++Depth)
1662 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1663 }
1664
1665 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1666 OS << Depth;
1667 Tok.setKind(tok::numeric_constant);
1668 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001669 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001670 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1671 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1672
1673 // Get the file that we are lexing out of. If we're currently lexing from
1674 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001675 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001676 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1677
1678 if (TheLexer)
1679 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1680
1681 const char *Result;
1682 if (CurFile) {
1683 time_t TT = CurFile->getModificationTime();
1684 struct tm *TM = localtime(&TT);
1685 Result = asctime(TM);
1686 } else {
1687 Result = "??? ??? ?? ??:??:?? ????\n";
1688 }
1689 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001690 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001691 Tok.setKind(tok::string_literal);
1692 } else if (II == Ident__COUNTER__) {
1693 // __COUNTER__ expands to a simple numeric value.
1694 OS << CounterValue++;
1695 Tok.setKind(tok::numeric_constant);
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001696 } else if (II == Ident__has_feature) {
1697 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1698 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1699 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1700 diag::err_feature_check_malformed);
1701 return II && HasFeature(*this, II->getName());
1702 });
1703 } else if (II == Ident__has_extension) {
1704 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1705 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1706 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1707 diag::err_feature_check_malformed);
1708 return II && HasExtension(*this, II->getName());
1709 });
1710 } else if (II == Ident__has_builtin) {
1711 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1712 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1713 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1714 diag::err_feature_check_malformed);
1715 if (!II)
1716 return false;
1717 else if (II->getBuiltinID() != 0)
1718 return true;
1719 else {
1720 const LangOptions &LangOpts = getLangOpts();
1721 return llvm::StringSwitch<bool>(II->getName())
1722 .Case("__make_integer_seq", LangOpts.CPlusPlus)
Eric Fiselier6ad68552016-07-01 01:24:09 +00001723 .Case("__type_pack_element", LangOpts.CPlusPlus)
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001724 .Default(false);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001725 }
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001726 });
1727 } else if (II == Ident__is_identifier) {
1728 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1729 [](Token &Tok, bool &HasLexedNextToken) -> int {
1730 return Tok.is(tok::identifier);
1731 });
1732 } else if (II == Ident__has_attribute) {
1733 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1734 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1735 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1736 diag::err_feature_check_malformed);
1737 return II ? hasAttribute(AttrSyntax::GNU, nullptr, II,
1738 getTargetInfo(), getLangOpts()) : 0;
1739 });
1740 } else if (II == Ident__has_declspec) {
1741 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1742 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1743 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1744 diag::err_feature_check_malformed);
1745 return II ? hasAttribute(AttrSyntax::Declspec, nullptr, II,
1746 getTargetInfo(), getLangOpts()) : 0;
1747 });
1748 } else if (II == Ident__has_cpp_attribute) {
1749 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1750 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1751 IdentifierInfo *ScopeII = nullptr;
1752 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1753 diag::err_feature_check_malformed);
1754 if (!II)
1755 return false;
1756
1757 // It is possible to receive a scope token. Read the "::", if it is
1758 // available, and the subsequent identifier.
David Majnemerd6163622014-12-15 09:03:58 +00001759 LexUnexpandedToken(Tok);
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001760 if (Tok.isNot(tok::coloncolon))
1761 HasLexedNextToken = true;
1762 else {
1763 ScopeII = II;
1764 LexUnexpandedToken(Tok);
1765 II = ExpectFeatureIdentifierInfo(Tok, *this,
1766 diag::err_feature_check_malformed);
1767 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001768
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001769 return II ? hasAttribute(AttrSyntax::CXX, ScopeII, II,
1770 getTargetInfo(), getLangOpts()) : 0;
1771 });
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001772 } else if (II == Ident__has_include ||
1773 II == Ident__has_include_next) {
1774 // The argument to these two builtins should be a parenthesized
1775 // file name string literal using angle brackets (<>) or
1776 // double-quotes ("").
1777 bool Value;
1778 if (II == Ident__has_include)
1779 Value = EvaluateHasInclude(Tok, II, *this);
1780 else
1781 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001782
1783 if (Tok.isNot(tok::r_paren))
1784 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001785 OS << (int)Value;
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001786 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001787 } else if (II == Ident__has_warning) {
1788 // The argument should be a parenthesized string literal.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001789 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1790 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1791 std::string WarningName;
1792 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs58905d22012-11-17 19:15:38 +00001793
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001794 HasLexedNextToken = Tok.is(tok::string_literal);
1795 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1796 /*MacroExpansion=*/false))
1797 return false;
Andy Gibbs58905d22012-11-17 19:15:38 +00001798
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001799 // FIXME: Should we accept "-R..." flags here, or should that be
1800 // handled by a separate __has_remark?
1801 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1802 WarningName[1] != 'W') {
1803 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1804 return false;
1805 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001806
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001807 // Finally, check if the warning flags maps to a diagnostic group.
1808 // We construct a SmallVector here to talk to getDiagnosticIDs().
1809 // Although we don't use the result, this isn't a hot path, and not
1810 // worth special casing.
1811 SmallVector<diag::kind, 10> Diags;
1812 return !getDiagnostics().getDiagnosticIDs()->
1813 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1814 WarningName.substr(2), Diags);
1815 });
Douglas Gregorc83de302012-09-25 15:44:52 +00001816 } else if (II == Ident__building_module) {
1817 // The argument to this builtin should be an identifier. The
1818 // builtin evaluates to 1 when that identifier names the module we are
1819 // currently building.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001820 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1821 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1822 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1823 diag::err_expected_id_building_module);
Richard Smithbbcc9f02016-08-26 00:14:38 +00001824 return getLangOpts().isCompilingModule() && II &&
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001825 (II->getName() == getLangOpts().CurrentModule);
1826 });
Douglas Gregorc83de302012-09-25 15:44:52 +00001827 } else if (II == Ident__MODULE__) {
1828 // The current module as an identifier.
1829 OS << getLangOpts().CurrentModule;
1830 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1831 Tok.setIdentifierInfo(ModuleII);
1832 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001833 } else if (II == Ident__identifier) {
1834 SourceLocation Loc = Tok.getLocation();
1835
1836 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1837 // if the parens are missing.
1838 LexNonComment(Tok);
1839 if (Tok.isNot(tok::l_paren)) {
1840 // No '(', use end of last token.
1841 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1842 << II << tok::l_paren;
1843 // If the next token isn't valid as our argument, we can't recover.
1844 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1845 Tok.setKind(tok::identifier);
1846 return;
1847 }
1848
1849 SourceLocation LParenLoc = Tok.getLocation();
1850 LexNonComment(Tok);
1851
1852 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1853 Tok.setKind(tok::identifier);
1854 else {
1855 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1856 << Tok.getKind();
1857 // Don't walk past anything that's not a real token.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001858 if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
Richard Smithae385082014-03-15 00:06:08 +00001859 return;
1860 }
1861
1862 // Discard the ')', preserving 'Tok' as our result.
1863 Token RParen;
1864 LexNonComment(RParen);
1865 if (RParen.isNot(tok::r_paren)) {
1866 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1867 << Tok.getKind() << tok::r_paren;
1868 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1869 }
1870 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001871 } else {
1872 llvm_unreachable("Unknown identifier!");
1873 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001874 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001875}
1876
1877void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1878 // If the 'used' status changed, and the macro requires 'unused' warning,
1879 // remove its SourceLocation from the warn-for-unused-macro locations.
1880 if (MI->isWarnIfUnused() && !MI->isUsed())
1881 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1882 MI->setIsUsed(true);
1883}