blob: d133bd30cf9281ff759eee6c656fdcbc7c075df8 [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;
414 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
415 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
416 if (Entry.TheLexer)
417 Val = Entry.TheLexer->isNextPPTokenLParen();
418 else if (Entry.ThePTHLexer)
419 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
420 else
421 Val = Entry.TheTokenLexer->isNextTokenLParen();
422
423 if (Val != 2)
424 break;
425
426 // Ran off the end of a source file?
427 if (Entry.ThePPLexer)
428 return false;
429 }
430 }
431
432 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
433 // have found something that isn't a '(' or we found the end of the
434 // translation unit. In either case, return false.
435 return Val == 1;
436}
437
438/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
439/// expanded as a macro, handle it and return the next token as 'Identifier'.
440bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Richard Smith20e883e2015-04-29 23:20:19 +0000441 const MacroDefinition &M) {
442 MacroInfo *MI = M.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000443
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000444 // If this is a macro expansion in the "#if !defined(x)" line for the file,
445 // then the macro could expand to different things in other contexts, we need
446 // to disable the optimization in this case.
447 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
448
449 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
450 if (MI->isBuiltinMacro()) {
Richard Smith36bd40d2015-05-04 03:15:40 +0000451 if (Callbacks)
452 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
453 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000454 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000455 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000456 }
457
458 /// Args - If this is a function-like macro expansion, this contains,
459 /// for each macro argument, the list of tokens that were provided to the
460 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000461 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000462
463 // Remember where the end of the expansion occurred. For an object-like
464 // macro, this is the identifier. For a function-like macro, this is the ')'.
465 SourceLocation ExpansionEnd = Identifier.getLocation();
466
467 // If this is a function-like macro, read the arguments.
468 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000469 // Remember that we are now parsing the arguments to a macro invocation.
470 // Preprocessor directives used inside macro arguments are not portable, and
471 // this enables the warning.
472 InMacroArgs = true;
473 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
474
475 // Finished parsing args.
476 InMacroArgs = false;
477
478 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000479 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000480
481 ++NumFnMacroExpanded;
482 } else {
483 ++NumMacroExpanded;
484 }
485
486 // Notice that this macro has been used.
487 markMacroAsUsed(MI);
488
489 // Remember where the token is expanded.
490 SourceLocation ExpandLoc = Identifier.getLocation();
491 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
492
493 if (Callbacks) {
494 if (InMacroArgs) {
495 // We can have macro expansion inside a conditional directive while
496 // reading the function macro arguments. To ensure, in that case, that
497 // MacroExpands callbacks still happen in source order, queue this
498 // callback to have it happen after the function macro callback.
499 DelayedMacroExpandsCallbacks.push_back(
Richard Smith36bd40d2015-05-04 03:15:40 +0000500 MacroExpandsInfo(Identifier, M, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000501 } else {
Richard Smith36bd40d2015-05-04 03:15:40 +0000502 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000503 if (!DelayedMacroExpandsCallbacks.empty()) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000504 for (unsigned i = 0, e = DelayedMacroExpandsCallbacks.size(); i != e;
505 ++i) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000506 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000507 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000508 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
509 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000510 }
511 DelayedMacroExpandsCallbacks.clear();
512 }
513 }
514 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000515
516 // If the macro definition is ambiguous, complain.
Richard Smith20e883e2015-04-29 23:20:19 +0000517 if (M.isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000518 Diag(Identifier, diag::warn_pp_ambiguous_macro)
519 << Identifier.getIdentifierInfo();
520 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
521 << Identifier.getIdentifierInfo();
Richard Smith20e883e2015-04-29 23:20:19 +0000522 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
523 if (OtherMI != MI)
524 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
525 << Identifier.getIdentifierInfo();
526 });
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000527 }
528
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000529 // If we started lexing a macro, enter the macro expansion body.
530
531 // If this macro expands to no tokens, don't bother to push it onto the
532 // expansion stack, only to take it right back off.
533 if (MI->getNumTokens() == 0) {
534 // No need for arg info.
535 if (Args) Args->destroy(*this);
536
Eli Friedman0834a4b2013-09-19 00:41:32 +0000537 // Propagate whitespace info as if we had pushed, then popped,
538 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000539 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000540 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000541 ++NumFastMacroExpanded;
542 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000543 } else if (MI->getNumTokens() == 1 &&
544 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
545 *this)) {
546 // Otherwise, if this macro expands into a single trivially-expanded
547 // token: expand it now. This handles common cases like
548 // "#define VAL 42".
549
550 // No need for arg info.
551 if (Args) Args->destroy(*this);
552
553 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
554 // identifier to the expanded token.
555 bool isAtStartOfLine = Identifier.isAtStartOfLine();
556 bool hasLeadingSpace = Identifier.hasLeadingSpace();
557
558 // Replace the result token.
559 Identifier = MI->getReplacementToken(0);
560
561 // Restore the StartOfLine/LeadingSpace markers.
562 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
563 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
564
565 // Update the tokens location to include both its expansion and physical
566 // locations.
567 SourceLocation Loc =
568 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
569 ExpansionEnd,Identifier.getLength());
570 Identifier.setLocation(Loc);
571
572 // If this is a disabled macro or #define X X, we must mark the result as
573 // unexpandable.
574 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
575 if (MacroInfo *NewMI = getMacroInfo(NewII))
576 if (!NewMI->isEnabled() || NewMI == MI) {
577 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000578 // Don't warn for "#define X X" like "#define bool bool" from
579 // stdbool.h.
580 if (NewMI != MI || MI->isFunctionLike())
581 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000582 }
583 }
584
585 // Since this is not an identifier token, it can't be macro expanded, so
586 // we're done.
587 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000588 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000589 }
590
591 // Start expanding the macro.
592 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000593 return false;
594}
595
Richard Trieu79b45382013-07-23 18:01:49 +0000596enum Bracket {
597 Brace,
598 Paren
599};
600
601/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
602/// token vector are properly nested.
603static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
604 SmallVector<Bracket, 8> Brackets;
605 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
606 E = Tokens.end();
607 I != E; ++I) {
608 if (I->is(tok::l_paren)) {
609 Brackets.push_back(Paren);
610 } else if (I->is(tok::r_paren)) {
611 if (Brackets.empty() || Brackets.back() == Brace)
612 return false;
613 Brackets.pop_back();
614 } else if (I->is(tok::l_brace)) {
615 Brackets.push_back(Brace);
616 } else if (I->is(tok::r_brace)) {
617 if (Brackets.empty() || Brackets.back() == Paren)
618 return false;
619 Brackets.pop_back();
620 }
621 }
Alexander Kornienkoa26c4952015-12-28 15:30:42 +0000622 return Brackets.empty();
Richard Trieu79b45382013-07-23 18:01:49 +0000623}
624
625/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
626/// vector of tokens in NewTokens. The new number of arguments will be placed
627/// in NumArgs and the ranges which need to surrounded in parentheses will be
628/// in ParenHints.
629/// Returns false if the token stream cannot be changed. If this is because
630/// of an initializer list starting a macro argument, the range of those
631/// initializer lists will be place in InitLists.
632static bool GenerateNewArgTokens(Preprocessor &PP,
633 SmallVectorImpl<Token> &OldTokens,
634 SmallVectorImpl<Token> &NewTokens,
635 unsigned &NumArgs,
636 SmallVectorImpl<SourceRange> &ParenHints,
637 SmallVectorImpl<SourceRange> &InitLists) {
638 if (!CheckMatchedBrackets(OldTokens))
639 return false;
640
641 // Once it is known that the brackets are matched, only a simple count of the
642 // braces is needed.
643 unsigned Braces = 0;
644
645 // First token of a new macro argument.
646 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
647
648 // First closing brace in a new macro argument. Used to generate
649 // SourceRanges for InitLists.
650 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
651 NumArgs = 0;
652 Token TempToken;
653 // Set to true when a macro separator token is found inside a braced list.
654 // If true, the fixed argument spans multiple old arguments and ParenHints
655 // will be updated.
656 bool FoundSeparatorToken = false;
657 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
658 E = OldTokens.end();
659 I != E; ++I) {
660 if (I->is(tok::l_brace)) {
661 ++Braces;
662 } else if (I->is(tok::r_brace)) {
663 --Braces;
664 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
665 ClosingBrace = I;
666 } else if (I->is(tok::eof)) {
667 // EOF token is used to separate macro arguments
668 if (Braces != 0) {
669 // Assume comma separator is actually braced list separator and change
670 // it back to a comma.
671 FoundSeparatorToken = true;
672 I->setKind(tok::comma);
673 I->setLength(1);
674 } else { // Braces == 0
675 // Separator token still separates arguments.
676 ++NumArgs;
677
678 // If the argument starts with a brace, it can't be fixed with
679 // parentheses. A different diagnostic will be given.
680 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
681 InitLists.push_back(
682 SourceRange(ArgStartIterator->getLocation(),
683 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
684 ClosingBrace = E;
685 }
686
687 // Add left paren
688 if (FoundSeparatorToken) {
689 TempToken.startToken();
690 TempToken.setKind(tok::l_paren);
691 TempToken.setLocation(ArgStartIterator->getLocation());
692 TempToken.setLength(0);
693 NewTokens.push_back(TempToken);
694 }
695
696 // Copy over argument tokens
697 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
698
699 // Add right paren and store the paren locations in ParenHints
700 if (FoundSeparatorToken) {
701 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
702 TempToken.startToken();
703 TempToken.setKind(tok::r_paren);
704 TempToken.setLocation(Loc);
705 TempToken.setLength(0);
706 NewTokens.push_back(TempToken);
707 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
708 Loc));
709 }
710
711 // Copy separator token
712 NewTokens.push_back(*I);
713
714 // Reset values
715 ArgStartIterator = I + 1;
716 FoundSeparatorToken = false;
717 }
718 }
719 }
720
721 return !ParenHints.empty() && InitLists.empty();
722}
723
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000724/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
725/// token is the '(' of the macro, this method is invoked to read all of the
726/// actual arguments specified for the macro invocation. This returns null on
727/// error.
728MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
729 MacroInfo *MI,
730 SourceLocation &MacroEnd) {
731 // The number of fixed arguments to parse.
732 unsigned NumFixedArgsLeft = MI->getNumArgs();
733 bool isVariadic = MI->isVariadic();
734
735 // Outer loop, while there are more arguments, keep reading them.
736 Token Tok;
737
738 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
739 // an argument value in a macro could expand to ',' or '(' or ')'.
740 LexUnexpandedToken(Tok);
741 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
742
743 // ArgTokens - Build up a list of tokens that make up each argument. Each
744 // argument is separated by an EOF token. Use a SmallVector so we can avoid
745 // heap allocations in the common case.
746 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000747 bool ContainsCodeCompletionTok = false;
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000748 bool FoundElidedComma = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000749
Richard Trieu79b45382013-07-23 18:01:49 +0000750 SourceLocation TooManyArgsLoc;
751
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000752 unsigned NumActuals = 0;
753 while (Tok.isNot(tok::r_paren)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000754 if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000755 break;
756
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000757 assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000758 "only expect argument separators here");
759
760 unsigned ArgTokenStart = ArgTokens.size();
761 SourceLocation ArgStartLoc = Tok.getLocation();
762
763 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
764 // that we already consumed the first one.
765 unsigned NumParens = 0;
766
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000767 while (true) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000768 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
769 // an argument value in a macro could expand to ',' or '(' or ')'.
770 LexUnexpandedToken(Tok);
771
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000772 if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000773 if (!ContainsCodeCompletionTok) {
774 Diag(MacroName, diag::err_unterm_macro_invoc);
775 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
776 << MacroName.getIdentifierInfo();
777 // Do not lose the EOF/EOD. Return it to the client.
778 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000779 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000780 }
David Blaikie2eabcc92016-02-09 18:52:09 +0000781 // Do not lose the EOF/EOD.
782 auto Toks = llvm::make_unique<Token[]>(1);
783 Toks[0] = Tok;
784 EnterTokenStream(std::move(Toks), 1, true);
785 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000786 } else if (Tok.is(tok::r_paren)) {
787 // If we found the ) token, the macro arg list is done.
788 if (NumParens-- == 0) {
789 MacroEnd = Tok.getLocation();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000790 if (!ArgTokens.empty() &&
791 ArgTokens.back().commaAfterElided()) {
792 FoundElidedComma = true;
793 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000794 break;
795 }
796 } else if (Tok.is(tok::l_paren)) {
797 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000798 } else if (Tok.is(tok::comma) && NumParens == 0 &&
799 !(Tok.getFlags() & Token::IgnoredComma)) {
800 // In Microsoft-compatibility mode, single commas from nested macro
801 // expansions should not be considered as argument separators. We test
802 // for this with the IgnoredComma token flag above.
803
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000804 // Comma ends this argument if there are more fixed arguments expected.
805 // However, if this is a variadic macro, and this is part of the
806 // variadic part, then the comma is just an argument token.
807 if (!isVariadic) break;
808 if (NumFixedArgsLeft > 1)
809 break;
810 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
811 // If this is a comment token in the argument list and we're just in
812 // -C mode (not -CC mode), discard the comment.
813 continue;
David Majnemerd8dee1f2015-03-18 07:53:20 +0000814 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000815 // Reading macro arguments can cause macros that we are currently
816 // expanding from to be popped off the expansion stack. Doing so causes
817 // them to be reenabled for expansion. Here we record whether any
818 // identifiers we lex as macro arguments correspond to disabled macros.
819 // If so, we mark the token as noexpand. This is a subtle aspect of
820 // C99 6.10.3.4p2.
821 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
822 if (!MI->isEnabled())
823 Tok.setFlag(Token::DisableExpand);
824 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000825 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000826 if (CodeComplete)
827 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
828 MI, NumActuals);
829 // Don't mark that we reached the code-completion point because the
830 // parser is going to handle the token and there will be another
831 // code-completion callback.
832 }
833
834 ArgTokens.push_back(Tok);
835 }
836
837 // If this was an empty argument list foo(), don't add this as an empty
838 // argument.
839 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
840 break;
841
842 // If this is not a variadic macro, and too many args were specified, emit
843 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000844 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000845 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000846 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
847 else
848 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000849 }
850
Richard Trieu79b45382013-07-23 18:01:49 +0000851 // Empty arguments are standard in C99 and C++0x, and are supported as an
852 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000853 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000854 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000855 diag::warn_cxx98_compat_empty_fnmacro_arg :
856 diag::ext_empty_fnmacro_arg);
857
858 // Add a marker EOF token to the end of the token list for this argument.
859 Token EOFTok;
860 EOFTok.startToken();
861 EOFTok.setKind(tok::eof);
862 EOFTok.setLocation(Tok.getLocation());
863 EOFTok.setLength(0);
864 ArgTokens.push_back(EOFTok);
865 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000866 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000867 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000868 }
869
870 // Okay, we either found the r_paren. Check to see if we parsed too few
871 // arguments.
872 unsigned MinArgsExpected = MI->getNumArgs();
873
Richard Trieu79b45382013-07-23 18:01:49 +0000874 // If this is not a variadic macro, and too many args were specified, emit
875 // an error.
876 if (!isVariadic && NumActuals > MinArgsExpected &&
877 !ContainsCodeCompletionTok) {
878 // Emit the diagnostic at the macro name in case there is a missing ).
879 // Emitting it at the , could be far away from the macro name.
880 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
881 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
882 << MacroName.getIdentifierInfo();
883
884 // Commas from braced initializer lists will be treated as argument
885 // separators inside macros. Attempt to correct for this with parentheses.
886 // TODO: See if this can be generalized to angle brackets for templates
887 // inside macro arguments.
888
Bob Wilson57217352013-07-27 21:59:57 +0000889 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000890 unsigned FixedNumArgs = 0;
891 SmallVector<SourceRange, 4> ParenHints, InitLists;
892 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
893 ParenHints, InitLists)) {
894 if (!InitLists.empty()) {
895 DiagnosticBuilder DB =
896 Diag(MacroName,
897 diag::note_init_list_at_beginning_of_macro_argument);
Craig Toppere335f252015-10-04 04:53:55 +0000898 for (SourceRange Range : InitLists)
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000899 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000900 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000901 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000902 }
903 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000904 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000905
906 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Craig Toppere335f252015-10-04 04:53:55 +0000907 for (SourceRange ParenLocation : ParenHints) {
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000908 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
909 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000910 }
911 ArgTokens.swap(FixedArgTokens);
912 NumActuals = FixedNumArgs;
913 }
914
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000915 // See MacroArgs instance var for description of this.
916 bool isVarargsElided = false;
917
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000918 if (ContainsCodeCompletionTok) {
919 // Recover from not-fully-formed macro invocation during code-completion.
920 Token EOFTok;
921 EOFTok.startToken();
922 EOFTok.setKind(tok::eof);
923 EOFTok.setLocation(Tok.getLocation());
924 EOFTok.setLength(0);
925 for (; NumActuals < MinArgsExpected; ++NumActuals)
926 ArgTokens.push_back(EOFTok);
927 }
928
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000929 if (NumActuals < MinArgsExpected) {
930 // There are several cases where too few arguments is ok, handle them now.
931 if (NumActuals == 0 && MinArgsExpected == 1) {
932 // #define A(X) or #define A(...) ---> A()
933
934 // If there is exactly one argument, and that argument is missing,
935 // then we have an empty "()" argument empty list. This is fine, even if
936 // the macro expects one argument (the argument is just empty).
937 isVarargsElided = MI->isVariadic();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000938 } else if ((FoundElidedComma || MI->isVariadic()) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000939 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
940 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
941 // Varargs where the named vararg parameter is missing: OK as extension.
942 // #define A(x, ...)
943 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000944 //
945 // If the macro contains the comma pasting extension, the diagnostic
946 // is suppressed; we know we'll get another diagnostic later.
947 if (!MI->hasCommaPasting()) {
948 Diag(Tok, diag::ext_missing_varargs_arg);
949 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
950 << MacroName.getIdentifierInfo();
951 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000952
953 // Remember this occurred, allowing us to elide the comma when used for
954 // cases like:
955 // #define A(x, foo...) blah(a, ## foo)
956 // #define B(x, ...) blah(a, ## __VA_ARGS__)
957 // #define C(...) blah(a, ## __VA_ARGS__)
958 // A(x) B(x) C()
959 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000960 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000961 // Otherwise, emit the error.
962 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000963 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
964 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000965 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000966 }
967
968 // Add a marker EOF token to the end of the token list for this argument.
969 SourceLocation EndLoc = Tok.getLocation();
970 Tok.startToken();
971 Tok.setKind(tok::eof);
972 Tok.setLocation(EndLoc);
973 Tok.setLength(0);
974 ArgTokens.push_back(Tok);
975
976 // If we expect two arguments, add both as empty.
977 if (NumActuals == 0 && MinArgsExpected == 2)
978 ArgTokens.push_back(Tok);
979
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000980 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
981 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000982 // Emit the diagnostic at the macro name in case there is a missing ).
983 // Emitting it at the , could be far away from the macro name.
984 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000985 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
986 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000987 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000988 }
989
990 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
991}
992
993/// \brief Keeps macro expanded tokens for TokenLexers.
994//
995/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
996/// going to lex in the cache and when it finishes the tokens are removed
997/// from the end of the cache.
998Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
999 ArrayRef<Token> tokens) {
1000 assert(tokLexer);
1001 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +00001002 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001003
1004 size_t newIndex = MacroExpandedTokens.size();
1005 bool cacheNeedsToGrow = tokens.size() >
1006 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
1007 MacroExpandedTokens.append(tokens.begin(), tokens.end());
1008
1009 if (cacheNeedsToGrow) {
1010 // Go through all the TokenLexers whose 'Tokens' pointer points in the
1011 // buffer and update the pointers to the (potential) new buffer array.
1012 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
1013 TokenLexer *prevLexer;
1014 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001015 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001016 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
1017 }
1018 }
1019
1020 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1021 return MacroExpandedTokens.data() + newIndex;
1022}
1023
1024void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1025 assert(!MacroExpandingLexersStack.empty());
1026 size_t tokIndex = MacroExpandingLexersStack.back().second;
1027 assert(tokIndex < MacroExpandedTokens.size());
1028 // Pop the cached macro expanded tokens from the end.
1029 MacroExpandedTokens.resize(tokIndex);
1030 MacroExpandingLexersStack.pop_back();
1031}
1032
1033/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1034/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1035/// the identifier tokens inserted.
1036static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1037 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001038 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001039 struct tm *TM = localtime(&TT);
1040
1041 static const char * const Months[] = {
1042 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1043 };
1044
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001045 {
1046 SmallString<32> TmpBuffer;
1047 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1048 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1049 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001050 Token TmpTok;
1051 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001052 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001053 DATELoc = TmpTok.getLocation();
1054 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001055
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001056 {
1057 SmallString<32> TmpBuffer;
1058 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1059 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1060 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001061 Token TmpTok;
1062 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001063 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001064 TIMELoc = TmpTok.getLocation();
1065 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001066}
1067
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001068/// HasFeature - Return true if we recognize and implement the feature
1069/// specified by the identifier as a standard language feature.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001070static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001071 const LangOptions &LangOpts = PP.getLangOpts();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001072
1073 // Normalize the feature name, __foo__ becomes foo.
1074 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
1075 Feature = Feature.substr(2, Feature.size() - 4);
1076
1077 return llvm::StringSwitch<bool>(Feature)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001078 .Case("address_sanitizer",
1079 LangOpts.Sanitize.hasOneOf(SanitizerKind::Address |
1080 SanitizerKind::KernelAddress))
Douglas Gregor4c27d102015-06-29 18:11:42 +00001081 .Case("assume_nonnull", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001082 .Case("attribute_analyzer_noreturn", true)
1083 .Case("attribute_availability", true)
1084 .Case("attribute_availability_with_message", true)
Bob Wilsonb111ec92015-03-02 19:01:14 +00001085 .Case("attribute_availability_app_extension", true)
Jordan Rose7e5de9c2015-07-16 22:30:10 +00001086 .Case("attribute_availability_with_version_underscores", true)
Tim Northover7a73cc72015-10-30 16:30:49 +00001087 .Case("attribute_availability_tvos", true)
1088 .Case("attribute_availability_watchos", true)
Manman Ren6731d732016-02-22 18:24:30 +00001089 .Case("attribute_availability_with_strict", true)
Manman Ren75bc6762016-03-21 17:30:55 +00001090 .Case("attribute_availability_with_replacement", true)
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +00001091 .Case("attribute_availability_in_templates", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001092 .Case("attribute_cf_returns_not_retained", true)
1093 .Case("attribute_cf_returns_retained", true)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00001094 .Case("attribute_cf_returns_on_parameters", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001095 .Case("attribute_deprecated_with_message", true)
Manman Renc7890fe2016-03-16 18:50:49 +00001096 .Case("attribute_deprecated_with_replacement", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001097 .Case("attribute_ext_vector_type", true)
1098 .Case("attribute_ns_returns_not_retained", true)
1099 .Case("attribute_ns_returns_retained", true)
1100 .Case("attribute_ns_consumes_self", true)
1101 .Case("attribute_ns_consumed", true)
1102 .Case("attribute_cf_consumed", true)
1103 .Case("attribute_objc_ivar_unused", true)
1104 .Case("attribute_objc_method_family", true)
1105 .Case("attribute_overloadable", true)
1106 .Case("attribute_unavailable_with_message", true)
1107 .Case("attribute_unused_on_fields", true)
1108 .Case("blocks", LangOpts.Blocks)
1109 .Case("c_thread_safety_attributes", true)
1110 .Case("cxx_exceptions", LangOpts.CXXExceptions)
Reid Kleckner6cf4a6b2015-08-13 17:56:49 +00001111 .Case("cxx_rtti", LangOpts.RTTI && LangOpts.RTTIData)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001112 .Case("enumerator_attributes", true)
Douglas Gregor4c27d102015-06-29 18:11:42 +00001113 .Case("nullability", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001114 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
1115 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
1116 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
Derek Bruening256c2e12016-04-21 21:32:04 +00001117 .Case("efficiency_sanitizer",
1118 LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency))
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001119 // Objective-C features
1120 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
1121 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00001122 .Case("objc_arc_weak", LangOpts.ObjCWeak)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001123 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
1124 .Case("objc_fixed_enum", LangOpts.ObjC2)
1125 .Case("objc_instancetype", LangOpts.ObjC2)
Douglas Gregorab209d82015-07-07 03:58:42 +00001126 .Case("objc_kindof", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001127 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
1128 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
1129 .Case("objc_property_explicit_atomic",
1130 true) // Does clang support explicit "atomic" keyword?
1131 .Case("objc_protocol_qualifier_mangling", true)
1132 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
1133 .Case("ownership_holds", true)
1134 .Case("ownership_returns", true)
1135 .Case("ownership_takes", true)
1136 .Case("objc_bool", true)
1137 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
1138 .Case("objc_array_literals", LangOpts.ObjC2)
1139 .Case("objc_dictionary_literals", LangOpts.ObjC2)
1140 .Case("objc_boxed_expressions", LangOpts.ObjC2)
Alex Denisovfde64952015-06-26 05:28:36 +00001141 .Case("objc_boxed_nsvalue_expressions", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001142 .Case("arc_cf_code_audited", true)
John McCall28592582015-02-01 22:34:06 +00001143 .Case("objc_bridge_id", true)
1144 .Case("objc_bridge_id_on_typedefs", true)
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001145 .Case("objc_generics", LangOpts.ObjC2)
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001146 .Case("objc_generics_variance", LangOpts.ObjC2)
Manman Ren515758e2016-03-10 23:51:03 +00001147 .Case("objc_class_property", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001148 // C11 features
1149 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +00001150 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001151 .Case("c_atomic", LangOpts.C11)
1152 .Case("c_generic_selections", LangOpts.C11)
1153 .Case("c_static_assert", LangOpts.C11)
1154 .Case("c_thread_local",
1155 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
1156 // C++11 features
1157 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
1158 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
1159 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +00001160 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001161 .Case("cxx_atomic", LangOpts.CPlusPlus11)
1162 .Case("cxx_attributes", LangOpts.CPlusPlus11)
1163 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
1164 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
1165 .Case("cxx_decltype", LangOpts.CPlusPlus11)
1166 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
1167 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
1168 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
1169 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
1170 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
1171 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
1172 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
1173 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
1174 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
1175 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
1176 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
1177 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
1178 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
1179 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
1180 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
1181 .Case("cxx_override_control", LangOpts.CPlusPlus11)
1182 .Case("cxx_range_for", LangOpts.CPlusPlus11)
1183 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
1184 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
1185 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
1186 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
1187 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
1188 .Case("cxx_thread_local",
1189 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
1190 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
1191 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
1192 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
1193 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
1194 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
1195 // C++1y features
1196 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
1197 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
1198 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
1199 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
1200 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
1201 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
1202 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
1203 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
1204 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
1205 // 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 Smith0a715422013-05-07 19:32:56 +00001288 // C++1y features supported by other languages as extensions.
1289 .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;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001424 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001425 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001426 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001427 } else if (PP.getCurrentSubmodule()) {
1428 // Start looking up in the directory *after* the one in which the current
1429 // file would be found, if any.
1430 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1431 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1432 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001433 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001434 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1435 } else {
1436 // Start looking up in the next directory.
1437 ++Lookup;
1438 }
1439
Richard Smith25d50752014-10-20 00:15:49 +00001440 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001441}
1442
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001443/// \brief Process single-argument builtin feature-like macros that return
1444/// integer values.
1445static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1446 Token &Tok, IdentifierInfo *II,
1447 Preprocessor &PP,
1448 llvm::function_ref<
1449 int(Token &Tok,
1450 bool &HasLexedNextTok)> Op) {
1451 // Parse the initial '('.
1452 PP.LexUnexpandedToken(Tok);
Douglas Gregorc83de302012-09-25 15:44:52 +00001453 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001454 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1455 << tok::l_paren;
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001456
1457 // Provide a dummy '0' value on output stream to elide further errors.
1458 if (!Tok.isOneOf(tok::eof, tok::eod)) {
1459 OS << 0;
1460 Tok.setKind(tok::numeric_constant);
1461 }
1462 return;
Douglas Gregorc83de302012-09-25 15:44:52 +00001463 }
1464
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001465 unsigned ParenDepth = 1;
Douglas Gregorc83de302012-09-25 15:44:52 +00001466 SourceLocation LParenLoc = Tok.getLocation();
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001467 llvm::Optional<int> Result;
Douglas Gregorc83de302012-09-25 15:44:52 +00001468
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001469 Token ResultTok;
1470 bool SuppressDiagnostic = false;
1471 while (true) {
1472 // Parse next token.
1473 PP.LexUnexpandedToken(Tok);
Douglas Gregorc83de302012-09-25 15:44:52 +00001474
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001475already_lexed:
1476 switch (Tok.getKind()) {
1477 case tok::eof:
1478 case tok::eod:
1479 // Don't provide even a dummy value if the eod or eof marker is
1480 // reached. Simply provide a diagnostic.
1481 PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1482 return;
1483
1484 case tok::comma:
1485 if (!SuppressDiagnostic) {
1486 PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1487 SuppressDiagnostic = true;
1488 }
1489 continue;
1490
1491 case tok::l_paren:
1492 ++ParenDepth;
1493 if (Result.hasValue())
1494 break;
1495 if (!SuppressDiagnostic) {
1496 PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1497 SuppressDiagnostic = true;
1498 }
1499 continue;
1500
1501 case tok::r_paren:
1502 if (--ParenDepth > 0)
1503 continue;
1504
1505 // The last ')' has been reached; return the value if one found or
1506 // a diagnostic and a dummy value.
1507 if (Result.hasValue())
1508 OS << Result.getValue();
1509 else {
1510 OS << 0;
1511 if (!SuppressDiagnostic)
1512 PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1513 }
1514 Tok.setKind(tok::numeric_constant);
1515 return;
1516
1517 default: {
1518 // Parse the macro argument, if one not found so far.
1519 if (Result.hasValue())
1520 break;
1521
1522 bool HasLexedNextToken = false;
1523 Result = Op(Tok, HasLexedNextToken);
1524 ResultTok = Tok;
1525 if (HasLexedNextToken)
1526 goto already_lexed;
1527 continue;
1528 }
1529 }
1530
1531 // Diagnose missing ')'.
1532 if (!SuppressDiagnostic) {
1533 if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1534 if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1535 Diag << LastII;
1536 else
1537 Diag << ResultTok.getKind();
1538 Diag << tok::r_paren << ResultTok.getLocation();
1539 }
1540 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1541 SuppressDiagnostic = true;
1542 }
Douglas Gregorc83de302012-09-25 15:44:52 +00001543 }
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001544}
Douglas Gregorc83de302012-09-25 15:44:52 +00001545
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001546/// \brief Helper function to return the IdentifierInfo structure of a Token
1547/// or generate a diagnostic if none available.
1548static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok,
1549 Preprocessor &PP,
1550 signed DiagID) {
1551 IdentifierInfo *II;
1552 if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1553 return II;
Douglas Gregorc83de302012-09-25 15:44:52 +00001554
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001555 PP.Diag(Tok.getLocation(), DiagID);
1556 return nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +00001557}
1558
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001559/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1560/// as a builtin macro, handle it and return the next token as 'Tok'.
1561void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1562 // Figure out which token this is.
1563 IdentifierInfo *II = Tok.getIdentifierInfo();
1564 assert(II && "Can't be a macro without id info!");
1565
1566 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1567 // invoke the pragma handler, then lex the token after it.
1568 if (II == Ident_Pragma)
1569 return Handle_Pragma(Tok);
1570 else if (II == Ident__pragma) // in non-MS mode this is null
1571 return HandleMicrosoft__pragma(Tok);
1572
1573 ++NumBuiltinMacroExpanded;
1574
1575 SmallString<128> TmpBuffer;
1576 llvm::raw_svector_ostream OS(TmpBuffer);
1577
1578 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001579 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001580 Tok.clearFlag(Token::NeedsCleaning);
1581
1582 if (II == Ident__LINE__) {
1583 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1584 // source file) of the current source line (an integer constant)". This can
1585 // be affected by #line.
1586 SourceLocation Loc = Tok.getLocation();
1587
1588 // Advance to the location of the first _, this might not be the first byte
1589 // of the token if it starts with an escaped newline.
1590 Loc = AdvanceToTokenCharacter(Loc, 0);
1591
1592 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1593 // a macro expansion. This doesn't matter for object-like macros, but
1594 // can matter for a function-like macro that expands to contain __LINE__.
1595 // Skip down through expansion points until we find a file loc for the
1596 // end of the expansion history.
1597 Loc = SourceMgr.getExpansionRange(Loc).second;
1598 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1599
1600 // __LINE__ expands to a simple numeric value.
1601 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1602 Tok.setKind(tok::numeric_constant);
1603 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1604 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1605 // character string literal)". This can be affected by #line.
1606 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1607
1608 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1609 // #include stack instead of the current file.
1610 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1611 SourceLocation NextLoc = PLoc.getIncludeLoc();
1612 while (NextLoc.isValid()) {
1613 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1614 if (PLoc.isInvalid())
1615 break;
1616
1617 NextLoc = PLoc.getIncludeLoc();
1618 }
1619 }
1620
1621 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1622 SmallString<128> FN;
1623 if (PLoc.isValid()) {
1624 FN += PLoc.getFilename();
1625 Lexer::Stringify(FN);
Yaron Keren09fb7c62015-03-10 07:33:23 +00001626 OS << '"' << FN << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001627 }
1628 Tok.setKind(tok::string_literal);
1629 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001630 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001631 if (!DATELoc.isValid())
1632 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1633 Tok.setKind(tok::string_literal);
1634 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1635 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1636 Tok.getLocation(),
1637 Tok.getLength()));
1638 return;
1639 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001640 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001641 if (!TIMELoc.isValid())
1642 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1643 Tok.setKind(tok::string_literal);
1644 Tok.setLength(strlen("\"hh:mm:ss\""));
1645 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1646 Tok.getLocation(),
1647 Tok.getLength()));
1648 return;
1649 } else if (II == Ident__INCLUDE_LEVEL__) {
1650 // Compute the presumed include depth of this token. This can be affected
1651 // by GNU line markers.
1652 unsigned Depth = 0;
1653
1654 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1655 if (PLoc.isValid()) {
1656 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1657 for (; PLoc.isValid(); ++Depth)
1658 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1659 }
1660
1661 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1662 OS << Depth;
1663 Tok.setKind(tok::numeric_constant);
1664 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001665 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001666 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1667 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1668
1669 // Get the file that we are lexing out of. If we're currently lexing from
1670 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001671 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001672 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1673
1674 if (TheLexer)
1675 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1676
1677 const char *Result;
1678 if (CurFile) {
1679 time_t TT = CurFile->getModificationTime();
1680 struct tm *TM = localtime(&TT);
1681 Result = asctime(TM);
1682 } else {
1683 Result = "??? ??? ?? ??:??:?? ????\n";
1684 }
1685 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001686 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001687 Tok.setKind(tok::string_literal);
1688 } else if (II == Ident__COUNTER__) {
1689 // __COUNTER__ expands to a simple numeric value.
1690 OS << CounterValue++;
1691 Tok.setKind(tok::numeric_constant);
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001692 } else if (II == Ident__has_feature) {
1693 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1694 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1695 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1696 diag::err_feature_check_malformed);
1697 return II && HasFeature(*this, II->getName());
1698 });
1699 } else if (II == Ident__has_extension) {
1700 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1701 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1702 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1703 diag::err_feature_check_malformed);
1704 return II && HasExtension(*this, II->getName());
1705 });
1706 } else if (II == Ident__has_builtin) {
1707 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1708 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1709 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1710 diag::err_feature_check_malformed);
1711 if (!II)
1712 return false;
1713 else if (II->getBuiltinID() != 0)
1714 return true;
1715 else {
1716 const LangOptions &LangOpts = getLangOpts();
1717 return llvm::StringSwitch<bool>(II->getName())
1718 .Case("__make_integer_seq", LangOpts.CPlusPlus)
Eric Fiselier6ad68552016-07-01 01:24:09 +00001719 .Case("__type_pack_element", LangOpts.CPlusPlus)
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001720 .Default(false);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001721 }
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001722 });
1723 } else if (II == Ident__is_identifier) {
1724 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1725 [](Token &Tok, bool &HasLexedNextToken) -> int {
1726 return Tok.is(tok::identifier);
1727 });
1728 } else if (II == Ident__has_attribute) {
1729 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1730 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1731 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1732 diag::err_feature_check_malformed);
1733 return II ? hasAttribute(AttrSyntax::GNU, nullptr, II,
1734 getTargetInfo(), getLangOpts()) : 0;
1735 });
1736 } else if (II == Ident__has_declspec) {
1737 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1738 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1739 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1740 diag::err_feature_check_malformed);
1741 return II ? hasAttribute(AttrSyntax::Declspec, nullptr, II,
1742 getTargetInfo(), getLangOpts()) : 0;
1743 });
1744 } else if (II == Ident__has_cpp_attribute) {
1745 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1746 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1747 IdentifierInfo *ScopeII = nullptr;
1748 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1749 diag::err_feature_check_malformed);
1750 if (!II)
1751 return false;
1752
1753 // It is possible to receive a scope token. Read the "::", if it is
1754 // available, and the subsequent identifier.
David Majnemerd6163622014-12-15 09:03:58 +00001755 LexUnexpandedToken(Tok);
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001756 if (Tok.isNot(tok::coloncolon))
1757 HasLexedNextToken = true;
1758 else {
1759 ScopeII = II;
1760 LexUnexpandedToken(Tok);
1761 II = ExpectFeatureIdentifierInfo(Tok, *this,
1762 diag::err_feature_check_malformed);
1763 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001764
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001765 return II ? hasAttribute(AttrSyntax::CXX, ScopeII, II,
1766 getTargetInfo(), getLangOpts()) : 0;
1767 });
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001768 } else if (II == Ident__has_include ||
1769 II == Ident__has_include_next) {
1770 // The argument to these two builtins should be a parenthesized
1771 // file name string literal using angle brackets (<>) or
1772 // double-quotes ("").
1773 bool Value;
1774 if (II == Ident__has_include)
1775 Value = EvaluateHasInclude(Tok, II, *this);
1776 else
1777 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001778
1779 if (Tok.isNot(tok::r_paren))
1780 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001781 OS << (int)Value;
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001782 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001783 } else if (II == Ident__has_warning) {
1784 // The argument should be a parenthesized string literal.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001785 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1786 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1787 std::string WarningName;
1788 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs58905d22012-11-17 19:15:38 +00001789
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001790 HasLexedNextToken = Tok.is(tok::string_literal);
1791 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1792 /*MacroExpansion=*/false))
1793 return false;
Andy Gibbs58905d22012-11-17 19:15:38 +00001794
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001795 // FIXME: Should we accept "-R..." flags here, or should that be
1796 // handled by a separate __has_remark?
1797 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1798 WarningName[1] != 'W') {
1799 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1800 return false;
1801 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001802
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001803 // Finally, check if the warning flags maps to a diagnostic group.
1804 // We construct a SmallVector here to talk to getDiagnosticIDs().
1805 // Although we don't use the result, this isn't a hot path, and not
1806 // worth special casing.
1807 SmallVector<diag::kind, 10> Diags;
1808 return !getDiagnostics().getDiagnosticIDs()->
1809 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1810 WarningName.substr(2), Diags);
1811 });
Douglas Gregorc83de302012-09-25 15:44:52 +00001812 } else if (II == Ident__building_module) {
1813 // The argument to this builtin should be an identifier. The
1814 // builtin evaluates to 1 when that identifier names the module we are
1815 // currently building.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001816 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1817 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1818 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1819 diag::err_expected_id_building_module);
Richard Smithbbcc9f02016-08-26 00:14:38 +00001820 return getLangOpts().isCompilingModule() && II &&
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001821 (II->getName() == getLangOpts().CurrentModule);
1822 });
Douglas Gregorc83de302012-09-25 15:44:52 +00001823 } else if (II == Ident__MODULE__) {
1824 // The current module as an identifier.
1825 OS << getLangOpts().CurrentModule;
1826 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1827 Tok.setIdentifierInfo(ModuleII);
1828 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001829 } else if (II == Ident__identifier) {
1830 SourceLocation Loc = Tok.getLocation();
1831
1832 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1833 // if the parens are missing.
1834 LexNonComment(Tok);
1835 if (Tok.isNot(tok::l_paren)) {
1836 // No '(', use end of last token.
1837 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1838 << II << tok::l_paren;
1839 // If the next token isn't valid as our argument, we can't recover.
1840 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1841 Tok.setKind(tok::identifier);
1842 return;
1843 }
1844
1845 SourceLocation LParenLoc = Tok.getLocation();
1846 LexNonComment(Tok);
1847
1848 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1849 Tok.setKind(tok::identifier);
1850 else {
1851 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1852 << Tok.getKind();
1853 // Don't walk past anything that's not a real token.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001854 if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
Richard Smithae385082014-03-15 00:06:08 +00001855 return;
1856 }
1857
1858 // Discard the ')', preserving 'Tok' as our result.
1859 Token RParen;
1860 LexNonComment(RParen);
1861 if (RParen.isNot(tok::r_paren)) {
1862 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1863 << Tok.getKind() << tok::r_paren;
1864 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1865 }
1866 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001867 } else {
1868 llvm_unreachable("Unknown identifier!");
1869 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001870 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001871}
1872
1873void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1874 // If the 'used' status changed, and the macro requires 'unused' warning,
1875 // remove its SourceLocation from the warn-for-unused-macro locations.
1876 if (MI->isWarnIfUnused() && !MI->isUsed())
1877 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1878 MI->setIsUsed(true);
1879}