Coverage Report

Created: 2025-07-18 06:59

/src/keystone/llvm/lib/MC/MCParser/AsmParser.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
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
//
10
// This class implements the parser for assembly files.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "llvm/ADT/APFloat.h"
15
#include "llvm/ADT/STLExtras.h"
16
#include "llvm/ADT/SmallString.h"
17
#include "llvm/ADT/StringMap.h"
18
#include "llvm/ADT/Twine.h"
19
#include "llvm/MC/MCAsmInfo.h"
20
#include "llvm/MC/MCContext.h"
21
#include "llvm/MC/MCDwarf.h"
22
#include "llvm/MC/MCExpr.h"
23
#include "llvm/MC/MCInstrInfo.h"
24
#include "llvm/MC/MCObjectFileInfo.h"
25
#include "llvm/MC/MCParser/AsmCond.h"
26
#include "llvm/MC/MCParser/AsmLexer.h"
27
#include "llvm/MC/MCParser/MCAsmParser.h"
28
#include "llvm/MC/MCParser/MCAsmParserUtils.h"
29
#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30
#include "llvm/MC/MCParser/MCTargetAsmParser.h"
31
#include "llvm/MC/MCRegisterInfo.h"
32
#include "llvm/MC/MCSectionMachO.h"
33
#include "llvm/MC/MCStreamer.h"
34
#include "llvm/MC/MCSymbol.h"
35
#include "llvm/MC/MCValue.h"
36
#include "llvm/Support/ErrorHandling.h"
37
#include "llvm/Support/MathExtras.h"
38
#include "llvm/Support/MemoryBuffer.h"
39
#include "llvm/Support/SourceMgr.h"
40
#include "llvm/Support/raw_ostream.h"
41
#include <cctype>
42
#include <deque>
43
#include <set>
44
#include <string>
45
#include <vector>
46
47
#include <keystone/keystone.h>
48
//#include <iostream>
49
50
using namespace llvm_ks;
51
52
0
MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
53
54
namespace {
55
/// \brief Helper types for tracking macro definitions.
56
typedef std::vector<AsmToken> MCAsmMacroArgument;
57
typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
58
59
struct MCAsmMacroParameter {
60
  StringRef Name;
61
  MCAsmMacroArgument Value;
62
  bool Required;
63
  bool Vararg;
64
65
1.23M
  MCAsmMacroParameter() : Required(false), Vararg(false) {}
66
};
67
68
typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
69
70
struct MCAsmMacro {
71
  StringRef Name;
72
  StringRef Body;
73
  MCAsmMacroParameters Parameters;
74
75
public:
76
  MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
77
37.7k
      : Name(N), Body(B), Parameters(std::move(P)) {}
78
};
79
80
/// \brief Helper class for storing information about an active macro
81
/// instantiation.
82
struct MacroInstantiation {
83
  /// The location of the instantiation.
84
  SMLoc InstantiationLoc;
85
86
  /// The buffer where parsing should resume upon instantiation completion.
87
  int ExitBuffer;
88
89
  /// The location where parsing should resume upon instantiation completion.
90
  SMLoc ExitLoc;
91
92
  /// The depth of TheCondStack at the start of the instantiation.
93
  size_t CondStackDepth;
94
95
public:
96
  MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
97
};
98
99
struct ParseStatementInfo {
100
  // error code for Keystone
101
  unsigned int KsError;
102
103
  /// \brief The parsed operands from the last parsed statement.
104
  SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
105
106
  /// \brief The opcode from the last parsed instruction.
107
  unsigned Opcode;
108
109
  /// \brief Was there an error parsing the inline assembly?
110
  bool ParseError;
111
112
  SmallVectorImpl<AsmRewrite> *AsmRewrites;
113
114
106M
  ParseStatementInfo() : KsError(0), Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
115
  ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
116
0
    : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
117
};
118
119
/// \brief The concrete assembly parser instance.
120
class AsmParser : public MCAsmParser {
121
  AsmParser(const AsmParser &) = delete;
122
  void operator=(const AsmParser &) = delete;
123
private:
124
  AsmLexer Lexer;
125
  MCContext &Ctx;
126
  MCStreamer &Out;
127
  const MCAsmInfo &MAI;
128
  SourceMgr &SrcMgr;
129
  SourceMgr::DiagHandlerTy SavedDiagHandler;
130
  void *SavedDiagContext;
131
  std::unique_ptr<MCAsmParserExtension> PlatformParser;
132
133
  /// This is the current buffer index we're lexing from as managed by the
134
  /// SourceMgr object.
135
  unsigned CurBuffer;
136
137
  AsmCond TheCondState;
138
  std::vector<AsmCond> TheCondStack;
139
140
  /// \brief maps directive names to handler methods in parser
141
  /// extensions. Extensions register themselves in this map by calling
142
  /// addDirectiveHandler.
143
  StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
144
145
  /// \brief Map of currently defined macros.
146
  StringMap<MCAsmMacro> MacroMap;
147
148
  /// \brief Stack of active macro instantiations.
149
  std::vector<MacroInstantiation*> ActiveMacros;
150
151
  /// \brief List of bodies of anonymous macros.
152
  std::deque<MCAsmMacro> MacroLikeBodies;
153
154
  /// Boolean tracking whether macro substitution is enabled.
155
  unsigned MacrosEnabledFlag : 1;
156
157
  /// \brief Keeps track of how many .macro's have been instantiated.
158
  unsigned NumOfMacroInstantiations;
159
160
  /// Flag tracking whether any errors have been encountered.
161
  bool HadError;
162
163
  /// The values from the last parsed cpp hash file line comment if any.
164
  StringRef CppHashFilename;
165
  int64_t CppHashLineNumber;
166
  SMLoc CppHashLoc;
167
  unsigned CppHashBuf;
168
  /// When generating dwarf for assembly source files we need to calculate the
169
  /// logical line number based on the last parsed cpp hash file line comment
170
  /// and current line. Since this is slow and messes up the SourceMgr's
171
  /// cache we save the last info we queried with SrcMgr.FindLineNumber().
172
  SMLoc LastQueryIDLoc;
173
174
  /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
175
  unsigned AssemblerDialect;
176
177
  /// \brief is Darwin compatibility enabled?
178
  bool IsDarwin;
179
180
  /// \brief Are we parsing ms-style inline assembly?
181
  bool ParsingInlineAsm;
182
183
  /// \brief Should we use PC relative offsets by default?
184
  bool NasmDefaultRel;
185
186
  // Keystone syntax support
187
  int KsSyntax;
188
189
public:
190
  AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
191
            const MCAsmInfo &MAI);
192
  ~AsmParser() override;
193
194
  size_t Run(bool NoInitialTextSection, uint64_t Address, bool NoFinalize = false) override;
195
196
  void addDirectiveHandler(StringRef Directive,
197
8.77M
                           ExtensionDirectiveHandler Handler) override {
198
8.77M
    ExtensionDirectiveMap[Directive] = Handler;
199
8.77M
  }
200
201
106k
  void addAliasForDirective(StringRef Directive, StringRef Alias) override {
202
106k
    DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
203
106k
  }
204
205
public:
206
  /// @name MCAsmParser Interface
207
  /// {
208
209
1.78k
  SourceMgr &getSourceManager() override { return SrcMgr; }
210
246M
  MCAsmLexer &getLexer() override { return Lexer; }
211
16.2M
  MCContext &getContext() override { return Ctx; }
212
538M
  MCStreamer &getStreamer() override { return Out; }
213
770k
  unsigned getAssemblerDialect() override {
214
770k
    if (AssemblerDialect == ~0U)
215
770k
      return MAI.getAssemblerDialect();
216
74
    else
217
74
      return AssemblerDialect;
218
770k
  }
219
133
  void setAssemblerDialect(unsigned i) override {
220
133
    AssemblerDialect = i;
221
133
  }
222
223
  void Note(SMLoc L, const Twine &Msg,
224
            ArrayRef<SMRange> Ranges = None) override;
225
  bool Warning(SMLoc L, const Twine &Msg,
226
               ArrayRef<SMRange> Ranges = None) override;
227
  bool Error(SMLoc L, const Twine &Msg,
228
             ArrayRef<SMRange> Ranges = None) override;
229
230
  const AsmToken &Lex() override;
231
232
0
  void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
233
0
  bool isParsingInlineAsm() override { return ParsingInlineAsm; }
234
235
0
  void setNasmDefaultRel(bool V) override { NasmDefaultRel = V; }
236
3.28k
  bool isNasmDefaultRel() override { return NasmDefaultRel; }
237
238
  bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
239
                        unsigned &NumOutputs, unsigned &NumInputs,
240
                        SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
241
                        SmallVectorImpl<std::string> &Constraints,
242
                        SmallVectorImpl<std::string> &Clobbers,
243
                        const MCInstrInfo *MII,
244
                        MCAsmParserSemaCallback &SI, uint64_t &Address) override;
245
246
  bool parseExpression(const MCExpr *&Res);
247
  bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
248
  bool parsePrimaryExprAux(const MCExpr *&Res, SMLoc &EndLoc, unsigned int depth);
249
  bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
250
  bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
251
  bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
252
                             SMLoc &EndLoc) override;
253
  bool parseAbsoluteExpression(int64_t &Res) override;
254
255
  /// \brief Parse an identifier or string (as a quoted identifier)
256
  /// and set \p Res to the identifier contents.
257
  bool parseIdentifier(StringRef &Res) override;
258
  void eatToEndOfStatement() override;
259
260
  void checkForValidSection() override;
261
262
  void initializeDirectiveKindMap(int syntax) override;    // Keystone NASM support
263
  /// }
264
265
private:
266
267
  bool parseStatement(ParseStatementInfo &Info,
268
                      MCAsmParserSemaCallback *SI, uint64_t &Address);
269
  void eatToEndOfLine();
270
  bool parseCppHashLineFilenameComment(SMLoc L);
271
272
  void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
273
                        ArrayRef<MCAsmMacroParameter> Parameters);
274
  bool expandMacro(raw_svector_ostream &OS, StringRef Body,
275
                   ArrayRef<MCAsmMacroParameter> Parameters,
276
                   ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
277
                   SMLoc L);
278
279
  /// \brief Are macros enabled in the parser?
280
8.16M
  bool areMacrosEnabled() {return MacrosEnabledFlag;}
281
282
  /// \brief Control a flag in the parser that enables or disables macros.
283
0
  void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
284
285
  /// \brief Lookup a previously defined macro.
286
  /// \param Name Macro name.
287
  /// \returns Pointer to macro. NULL if no such macro was defined.
288
  const MCAsmMacro* lookupMacro(StringRef Name);
289
290
  /// \brief Define a new macro with the given name and information.
291
  void defineMacro(StringRef Name, MCAsmMacro Macro);
292
293
  /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
294
  void undefineMacro(StringRef Name);
295
296
  /// \brief Are we inside a macro instantiation?
297
301k
  bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
298
299
  /// \brief Handle entry to macro instantiation.
300
  ///
301
  /// \param M The macro.
302
  /// \param NameLoc Instantiation location.
303
  bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
304
305
  /// \brief Handle exit from macro instantiation.
306
  void handleMacroExit();
307
308
  /// \brief Extract AsmTokens for a macro argument.
309
  bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
310
311
  /// \brief Parse all macro arguments for a given macro.
312
  bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
313
314
  void printMacroInstantiations();
315
  void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
316
1.22M
                    ArrayRef<SMRange> Ranges = None) const {
317
1.22M
    SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
318
1.22M
  }
319
  static void DiagHandler(const SMDiagnostic &Diag, void *Context);
320
321
  /// \brief Enter the specified file. This returns true on failure.
322
  bool enterIncludeFile(const std::string &Filename);
323
324
  /// \brief Process the specified file for the .incbin directive.
325
  /// This returns true on failure.
326
  bool processIncbinFile(const std::string &Filename);
327
328
  /// \brief Reset the current lexer position to that given by \p Loc. The
329
  /// current token is not set; clients should ensure Lex() is called
330
  /// subsequently.
331
  ///
332
  /// \param InBuffer If not 0, should be the known buffer id that contains the
333
  /// location.
334
  void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
335
336
  /// \brief Parse up to the end of statement and a return the contents from the
337
  /// current token until the end of the statement; the current token on exit
338
  /// will be either the EndOfStatement or EOF.
339
  StringRef parseStringToEndOfStatement() override;
340
341
  /// \brief Parse until the end of a statement or a comma is encountered,
342
  /// return the contents from the current token up to the end or comma.
343
  StringRef parseStringToComma();
344
345
  bool parseAssignment(StringRef Name, bool allow_redef,
346
                       bool NoDeadStrip = false);
347
348
  unsigned getBinOpPrecedence(AsmToken::TokenKind K,
349
                              MCBinaryExpr::Opcode &Kind);
350
351
  bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
352
  bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
353
  bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
354
355
  bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
356
357
  // Generic (target and platform independent) directive parsing.
358
  enum DirectiveKind {
359
    DK_NO_DIRECTIVE, // Placeholder
360
    DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
361
    DK_RELOC,
362
    DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
363
    DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
364
    DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
365
    DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
366
    DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
367
    DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
368
    DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
369
    DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
370
    DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
371
    DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
372
    DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
373
    DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
374
    DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
375
    DK_CV_FILE, DK_CV_LOC, DK_CV_LINETABLE, DK_CV_INLINE_LINETABLE,
376
    DK_CV_STRINGTABLE, DK_CV_FILECHECKSUMS,
377
    DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
378
    DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
379
    DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
380
    DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
381
    DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
382
    DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
383
    DK_MACROS_ON, DK_MACROS_OFF,
384
    DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
385
    DK_SLEB128, DK_ULEB128,
386
    DK_ERR, DK_ERROR, DK_WARNING,
387
    DK_NASM_BITS,    // NASM directive 'bits'
388
    DK_NASM_DEFAULT, // NASM directive 'default'
389
    DK_NASM_USE32,   // NASM directive 'use32'
390
    DK_END
391
  };
392
393
  /// \brief Maps directive name --> DirectiveKind enum, for
394
  /// directives parsed by this class.
395
  StringMap<DirectiveKind> DirectiveKindMap;
396
397
  // ".ascii", ".asciz", ".string"
398
  bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
399
  bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
400
  bool parseDirectiveValue(unsigned Size, unsigned int &KsError); // ".byte", ".long", ...
401
  bool parseDirectiveOctaValue(unsigned int &KsError); // ".octa"
402
  bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
403
  bool parseDirectiveFill(); // ".fill"
404
  bool parseDirectiveZero(); // ".zero"
405
  // ".set", ".equ", ".equiv"
406
  bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
407
  bool parseDirectiveOrg(); // ".org"
408
  // ".align{,32}", ".p2align{,w,l}"
409
  bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
410
411
  // ".file", ".line", ".loc", ".stabs"
412
  bool parseDirectiveFile(SMLoc DirectiveLoc);
413
  bool parseDirectiveLine();
414
  bool parseDirectiveLoc();
415
  bool parseDirectiveStabs();
416
417
  // ".cv_file", ".cv_loc", ".cv_linetable", "cv_inline_linetable"
418
  bool parseDirectiveCVFile();
419
  bool parseDirectiveCVLoc();
420
  bool parseDirectiveCVLinetable();
421
  bool parseDirectiveCVInlineLinetable();
422
  bool parseDirectiveCVStringTable();
423
  bool parseDirectiveCVFileChecksums();
424
425
  // .cfi directives
426
  bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
427
  bool parseDirectiveCFIWindowSave();
428
  bool parseDirectiveCFISections();
429
  bool parseDirectiveCFIStartProc();
430
  bool parseDirectiveCFIEndProc();
431
  bool parseDirectiveCFIDefCfaOffset();
432
  bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
433
  bool parseDirectiveCFIAdjustCfaOffset();
434
  bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
435
  bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
436
  bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
437
  bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
438
  bool parseDirectiveCFIRememberState();
439
  bool parseDirectiveCFIRestoreState();
440
  bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
441
  bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
442
  bool parseDirectiveCFIEscape();
443
  bool parseDirectiveCFISignalFrame();
444
  bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
445
446
  // macro directives
447
  bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
448
  bool parseDirectiveExitMacro(StringRef Directive);
449
  bool parseDirectiveEndMacro(StringRef Directive);
450
  bool parseDirectiveMacro(SMLoc DirectiveLoc);
451
  bool parseDirectiveMacrosOnOff(StringRef Directive);
452
453
  // ".bundle_align_mode"
454
  bool parseDirectiveBundleAlignMode();
455
  // ".bundle_lock"
456
  bool parseDirectiveBundleLock();
457
  // ".bundle_unlock"
458
  bool parseDirectiveBundleUnlock();
459
460
  // ".space", ".skip"
461
  bool parseDirectiveSpace(StringRef IDVal);
462
463
  // .sleb128 (Signed=true) and .uleb128 (Signed=false)
464
  bool parseDirectiveLEB128(bool Signed);
465
466
  /// \brief Parse a directive like ".globl" which
467
  /// accepts a single symbol (which should be a label or an external).
468
  bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
469
470
  bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
471
472
  bool parseDirectiveAbort(); // ".abort"
473
  bool parseDirectiveInclude(); // ".include"
474
  bool parseDirectiveIncbin(); // ".incbin"
475
476
  // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
477
  bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
478
  // ".ifb" or ".ifnb", depending on ExpectBlank.
479
  bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
480
  // ".ifc" or ".ifnc", depending on ExpectEqual.
481
  bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
482
  // ".ifeqs" or ".ifnes", depending on ExpectEqual.
483
  bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
484
  // ".ifdef" or ".ifndef", depending on expect_defined
485
  bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
486
  bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
487
  bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
488
  bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
489
  bool parseEscapedString(std::string &Data) override;
490
491
  const MCExpr *applyModifierToExpr(const MCExpr *E,
492
                                    MCSymbolRefExpr::VariantKind Variant);
493
494
  // Macro-like directives
495
  MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
496
  void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
497
                                raw_svector_ostream &OS);
498
  bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
499
  bool parseDirectiveIrp(SMLoc DirectiveLoc);  // ".irp"
500
  bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
501
  bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
502
503
  // "_emit" or "__emit"
504
  bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
505
                            size_t Len);
506
507
  // "align"
508
  bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
509
510
  // "end"
511
  bool parseDirectiveEnd(SMLoc DirectiveLoc);
512
513
  // ".err" or ".error"
514
  bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
515
516
  // ".warning"
517
  bool parseDirectiveWarning(SMLoc DirectiveLoc);
518
519
  // "bits" (Nasm)
520
  bool parseNasmDirectiveBits();
521
522
  // "use32" (Nasm)
523
  bool parseNasmDirectiveUse32();
524
525
  // "default" (Nasm)
526
  bool parseNasmDirectiveDefault();
527
528
  bool isNasmDirective(StringRef str);  // is this str a NASM directive?
529
  bool isDirective(StringRef str);  // is this str a directive?
530
};
531
}
532
533
namespace llvm_ks {
534
535
extern MCAsmParserExtension *createDarwinAsmParser();
536
extern MCAsmParserExtension *createELFAsmParser();
537
extern MCAsmParserExtension *createCOFFAsmParser();
538
539
}
540
541
enum { DEFAULT_ADDRSPACE = 0 };
542
543
AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
544
                     const MCAsmInfo &MAI)
545
132k
    : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
546
132k
      PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
547
132k
      MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
548
132k
      AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
549
132k
      NasmDefaultRel(false) {
550
  // Save the old handler.
551
132k
  SavedDiagHandler = SrcMgr.getDiagHandler();
552
132k
  SavedDiagContext = SrcMgr.getDiagContext();
553
  // Set our own handler which calls the saved handler.
554
132k
  SrcMgr.setDiagHandler(DiagHandler, this);
555
132k
  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
556
557
  // Initialize the platform / file format parser.
558
132k
  PlatformParser.reset(createDarwinAsmParser());
559
132k
  IsDarwin = true;
560
#if 0
561
  switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
562
  case MCObjectFileInfo::IsCOFF:
563
    PlatformParser.reset(createCOFFAsmParser());
564
    break;
565
  case MCObjectFileInfo::IsMachO:
566
    PlatformParser.reset(createDarwinAsmParser());
567
    IsDarwin = true;
568
    break;
569
  case MCObjectFileInfo::IsELF:
570
    PlatformParser.reset(createELFAsmParser());
571
    break;
572
  }
573
#endif
574
575
132k
  PlatformParser->Initialize(*this);
576
132k
  initializeDirectiveKindMap(0);
577
578
132k
  NumOfMacroInstantiations = 0;
579
132k
}
580
581
132k
AsmParser::~AsmParser() {
582
132k
  assert((HadError || ActiveMacros.empty()) &&
583
132k
         "Unexpected active macro instantiation!");
584
    
585
  // Restore the saved diagnostics handler and context for use during
586
  // finalization
587
132k
  SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);  
588
132k
}
589
590
320k
void AsmParser::printMacroInstantiations() {
591
  // Print the active macro instantiation stack.
592
320k
  for (std::vector<MacroInstantiation *>::const_reverse_iterator
593
320k
           it = ActiveMacros.rbegin(),
594
320k
           ie = ActiveMacros.rend();
595
1.22M
       it != ie; ++it)
596
909k
    printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
597
909k
                 "while in macro instantiation");
598
320k
}
599
600
19.3k
void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
601
19.3k
  printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
602
19.3k
  printMacroInstantiations();
603
19.3k
}
604
605
185k
bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
606
185k
  if(getTargetParser().getTargetOptions().MCNoWarn)
607
0
    return false;
608
185k
  if (getTargetParser().getTargetOptions().MCFatalWarnings)
609
0
    return Error(L, Msg, Ranges);
610
185k
  printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
611
185k
  printMacroInstantiations();
612
185k
  return false;
613
185k
}
614
615
114k
bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
616
114k
  HadError = true;
617
114k
  printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
618
114k
  printMacroInstantiations();
619
114k
  return true;
620
114k
}
621
622
45
bool AsmParser::enterIncludeFile(const std::string &Filename) {
623
45
  std::string IncludedFile;
624
45
  unsigned NewBuf =
625
45
      SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
626
45
  if (!NewBuf)
627
45
    return true;
628
629
0
  CurBuffer = NewBuf;
630
0
  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
631
0
  return false;
632
45
}
633
634
/// Process the specified .incbin file by searching for it in the include paths
635
/// then just emitting the byte contents of the file to the streamer. This
636
/// returns true on failure.
637
0
bool AsmParser::processIncbinFile(const std::string &Filename) {
638
0
  std::string IncludedFile;
639
0
  unsigned NewBuf =
640
0
      SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
641
0
  if (!NewBuf)
642
0
    return true;
643
644
  // Pick up the bytes from the file and emit them.
645
0
  getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
646
0
  return false;
647
0
}
648
649
324k
void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
650
324k
  CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
651
324k
  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
652
324k
                  Loc.getPointer());
653
324k
}
654
655
196M
const AsmToken &AsmParser::Lex() {
656
196M
  const AsmToken *tok = &Lexer.Lex();
657
658
196M
  if (tok->is(AsmToken::Eof)) {
659
    // If this is the end of an included file, pop the parent file off the
660
    // include stack.
661
110k
    SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
662
110k
    if (ParentIncludeLoc != SMLoc()) {
663
0
      jumpToLoc(ParentIncludeLoc);
664
0
      tok = &Lexer.Lex();   // qq
665
0
    }
666
110k
  }
667
668
  //if (tok->is(AsmToken::Error))
669
  //  Error(Lexer.getErrLoc(), Lexer.getErr());
670
671
196M
  return *tok;
672
196M
}
673
674
size_t AsmParser::Run(bool NoInitialTextSection, uint64_t Address, bool NoFinalize)
675
132k
{
676
  // count number of statement
677
132k
  size_t count = 0;
678
679
  // Create the initial section, if requested.
680
132k
  if (!NoInitialTextSection)
681
132k
    Out.InitSections(false);
682
683
  // Prime the lexer.
684
132k
  Lex();
685
132k
  if (!Lexer.isNot(AsmToken::Error)) {
686
735
    KsError = KS_ERR_ASM_TOKEN_INVALID;
687
735
    return 0;
688
735
  }
689
690
132k
  HadError = false;
691
132k
  AsmCond StartingCondState = TheCondState;
692
693
  // If we are generating dwarf for assembly source files save the initial text
694
  // section and generate a .file directive.
695
132k
  if (getContext().getGenDwarfForAssembly()) {
696
0
    MCSection *Sec = getStreamer().getCurrentSection().first;
697
0
    if (!Sec->getBeginSymbol()) {
698
0
      MCSymbol *SectionStartSym = getContext().createTempSymbol();
699
0
      getStreamer().EmitLabel(SectionStartSym);
700
0
      Sec->setBeginSymbol(SectionStartSym);
701
0
    }
702
0
    bool InsertResult = getContext().addGenDwarfSection(Sec);
703
0
    assert(InsertResult && ".text section should not have debug info yet");
704
0
    (void)InsertResult;
705
0
    getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
706
0
        0, StringRef(), getContext().getMainFileName()));
707
0
  }
708
709
  // While we have input, parse each statement.
710
106M
  while (Lexer.isNot(AsmToken::Eof)) {
711
106M
    ParseStatementInfo Info;
712
106M
    if (!parseStatement(Info, nullptr, Address)) {
713
100M
      count++;
714
100M
      continue;
715
100M
    }
716
717
    //printf(">> 222 error = %u\n", Info.KsError);
718
6.27M
    if (!KsError) {
719
65.5k
        KsError = Info.KsError;
720
65.5k
        return 0;
721
65.5k
    }
722
723
    // We had an error, validate that one was emitted and recover by skipping to
724
    // the next line.
725
    // assert(HadError && "Parse statement returned an error, but none emitted!");
726
727
    //eatToEndOfStatement();
728
6.27M
  }
729
730
66.6k
  if (TheCondState.TheCond != StartingCondState.TheCond ||
731
66.6k
      TheCondState.Ignore != StartingCondState.Ignore) {
732
    //return TokError("unmatched .ifs or .elses");
733
6.28k
    KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
734
6.28k
    return 0;
735
6.28k
  }
736
737
  // Check to see that all assembler local symbols were actually defined.
738
  // Targets that don't do subsections via symbols may not want this, though,
739
  // so conservatively exclude them. Only do this if we're finalizing, though,
740
  // as otherwise we won't necessarilly have seen everything yet.
741
60.3k
  if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
742
0
    for (const auto &TableEntry : getContext().getSymbols()) {
743
0
      MCSymbol *Sym = TableEntry.getValue();
744
      // Variable symbols may not be marked as defined, so check those
745
      // explicitly. If we know it's a variable, we have a definition for
746
      // the purposes of this check.
747
0
      if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined()) {
748
        // FIXME: We would really like to refer back to where the symbol was
749
        // first referenced for a source location. We need to add something
750
        // to track that. Currently, we just point to the end of the file.
751
        //return Error(getLexer().getLoc(), "assembler local symbol '" +
752
        //                                      Sym->getName() + "' not defined");    // qq: set KsError, then return 0
753
0
        KsError = KS_ERR_ASM_SYMBOL_MISSING;
754
0
        return 0;
755
0
      }
756
0
    }
757
0
  }
758
759
  // Finalize the output stream if there are no errors and if the client wants
760
  // us to.
761
60.3k
  if (!KsError) {
762
47.4k
      if (!HadError && !NoFinalize)
763
45.1k
          KsError = Out.Finish();
764
47.4k
  } else
765
12.8k
      Out.Finish();
766
767
  //return HadError || getContext().hadError();
768
60.3k
  return count;
769
60.3k
}
770
771
void AsmParser::checkForValidSection()
772
943k
{
773
#if 0
774
  if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
775
    TokError("expected section directive before assembly directive");
776
    Out.InitSections(false);
777
  }
778
#endif
779
943k
}
780
781
/// \brief Throw away the rest of the line for testing purposes.
782
void AsmParser::eatToEndOfStatement()
783
4.23M
{
784
53.9M
  while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
785
49.6M
    Lex();
786
787
  // Eat EOL.
788
4.23M
  if (Lexer.is(AsmToken::EndOfStatement))
789
4.23M
    Lex();
790
4.23M
}
791
792
348k
StringRef AsmParser::parseStringToEndOfStatement() {
793
348k
  const char *Start = getTok().getLoc().getPointer();
794
795
2.99M
  while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
796
2.64M
    Lex();
797
798
348k
  const char *End = getTok().getLoc().getPointer();
799
348k
  return StringRef(Start, End - Start);
800
348k
}
801
802
290k
StringRef AsmParser::parseStringToComma() {
803
290k
  const char *Start = getTok().getLoc().getPointer();
804
805
3.62M
  while (Lexer.isNot(AsmToken::EndOfStatement) &&
806
3.62M
         Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
807
3.33M
    Lex();
808
809
290k
  const char *End = getTok().getLoc().getPointer();
810
290k
  return StringRef(Start, End - Start);
811
290k
}
812
813
/// \brief Parse a paren expression and return it.
814
/// NOTE: This assumes the leading '(' has already been consumed.
815
///
816
/// parenexpr ::= expr)
817
///
818
928k
bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
819
928k
  if (parseExpression(Res))
820
906k
    return true;
821
21.9k
  if (Lexer.isNot(AsmToken::RParen))
822
    //return TokError("expected ')' in parentheses expression");
823
10.2k
    return true;
824
11.6k
  EndLoc = Lexer.getTok().getEndLoc();
825
11.6k
  Lex();
826
11.6k
  return false;
827
21.9k
}
828
829
/// \brief Parse a bracket expression and return it.
830
/// NOTE: This assumes the leading '[' has already been consumed.
831
///
832
/// bracketexpr ::= expr]
833
///
834
0
bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
835
0
  if (parseExpression(Res))
836
0
    return true;
837
0
  if (Lexer.isNot(AsmToken::RBrac)) {
838
    //return TokError("expected ']' in brackets expression");
839
0
    KsError = KS_ERR_ASM_INVALIDOPERAND;
840
0
    return true;
841
0
  }
842
0
  EndLoc = Lexer.getTok().getEndLoc();
843
0
  Lex();
844
0
  return false;
845
0
}
846
847
bool AsmParser::parsePrimaryExprAux(const MCExpr *&Res, SMLoc &EndLoc, unsigned int depth)
848
8.46M
{
849
8.46M
  if (depth > 0x100) {
850
40
    KsError = KS_ERR_ASM_EXPR_TOKEN;
851
40
    return true;
852
40
  }
853
8.46M
  SMLoc FirstTokenLoc = getLexer().getLoc();
854
8.46M
  AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
855
8.46M
  switch (FirstTokenKind) {
856
644k
  default:
857
    //return TokError("unknown token in expression");
858
644k
    KsError = KS_ERR_ASM_EXPR_TOKEN;
859
644k
    return true;
860
  // If we have an error assume that we've already handled it.
861
148k
  case AsmToken::Error:
862
148k
    return true;
863
70.6k
  case AsmToken::Exclaim:
864
70.6k
    Lex(); // Eat the operator.
865
70.6k
    if (parsePrimaryExprAux(Res, EndLoc, depth+1))
866
19.4k
      return true;
867
51.2k
    Res = MCUnaryExpr::createLNot(Res, getContext());
868
51.2k
    return false;
869
188k
  case AsmToken::Dollar:
870
210k
  case AsmToken::At:
871
221k
  case AsmToken::String:
872
2.17M
  case AsmToken::Identifier: {
873
2.17M
    StringRef Identifier;
874
2.17M
    if (parseIdentifier(Identifier)) {
875
184k
      if (FirstTokenKind == AsmToken::Dollar) {
876
176k
        if (Lexer.getMAI().getDollarIsPC()) {
877
          // This is a '$' reference, which references the current PC.  Emit a
878
          // temporary label to the streamer and refer to it.
879
3.97k
          MCSymbol *Sym = Ctx.createTempSymbol();
880
3.97k
          Out.EmitLabel(Sym);
881
3.97k
          Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
882
3.97k
                                        getContext());
883
3.97k
          EndLoc = FirstTokenLoc;
884
3.97k
          return false;
885
3.97k
        }
886
        //return Error(FirstTokenLoc, "invalid token in expression");
887
172k
        KsError = KS_ERR_ASM_INVALIDOPERAND;
888
172k
        return true;
889
176k
      }
890
184k
    }
891
    // Parse symbol variant
892
1.99M
    std::pair<StringRef, StringRef> Split;
893
1.99M
    if (!MAI.useParensForSymbolVariant()) {
894
1.13M
      if (FirstTokenKind == AsmToken::String) {
895
8.68k
        if (Lexer.is(AsmToken::At)) {
896
955
          Lexer.Lex(); // eat @
897
          //SMLoc AtLoc = getLexer().getLoc();
898
955
          StringRef VName;
899
955
          if (parseIdentifier(VName)) {
900
            //return Error(AtLoc, "expected symbol variant after '@'");
901
286
            KsError = KS_ERR_ASM_INVALIDOPERAND;
902
286
            return true;
903
286
          }
904
905
669
          Split = std::make_pair(Identifier, VName);
906
669
        }
907
1.12M
      } else {
908
1.12M
        Split = Identifier.split('@');
909
1.12M
      }
910
1.13M
    } else if (Lexer.is(AsmToken::LParen)) {
911
14.5k
      Lexer.Lex(); // eat (
912
14.5k
      StringRef VName;
913
14.5k
      parseIdentifier(VName);
914
14.5k
      if (Lexer.isNot(AsmToken::RParen)) {
915
          //return Error(Lexer.getTok().getLoc(),
916
          //             "unexpected token in variant, expected ')'");
917
6.46k
          KsError = KS_ERR_ASM_INVALIDOPERAND;
918
6.46k
          return true;
919
6.46k
      }
920
8.09k
      Lexer.Lex(); // eat )
921
8.09k
      Split = std::make_pair(Identifier, VName);
922
8.09k
    }
923
924
1.99M
    EndLoc = SMLoc::getFromPointer(Identifier.end());
925
926
    // This is a symbol reference.
927
1.99M
    StringRef SymbolName = Identifier;
928
1.99M
    MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
929
930
    // Lookup the symbol variant if used.
931
1.99M
    if (Split.second.size()) {
932
108k
      Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
933
108k
      if (Variant != MCSymbolRefExpr::VK_Invalid) {
934
64.1k
        SymbolName = Split.first;
935
64.1k
      } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
936
0
        Variant = MCSymbolRefExpr::VK_None;
937
43.9k
      } else {
938
        //return Error(SMLoc::getFromPointer(Split.second.begin()),
939
        //             "invalid variant '" + Split.second + "'");
940
43.9k
        KsError = KS_ERR_ASM_INVALIDOPERAND;
941
43.9k
        return true;
942
43.9k
      }
943
108k
    }
944
945
1.94M
    if (SymbolName.empty()) {
946
12.8k
        return true;
947
12.8k
    }
948
1.93M
    MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
949
950
    // If this is an absolute variable reference, substitute it now to preserve
951
    // semantics in the face of reassignment.
952
1.93M
    if (Sym->isVariable() &&
953
1.93M
        isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
954
6.46k
      if (Variant) {
955
        //return Error(EndLoc, "unexpected modifier on variable reference");
956
265
        KsError = KS_ERR_ASM_INVALIDOPERAND;
957
265
        return true;
958
265
      }
959
960
6.19k
      Res = Sym->getVariableValue(/*SetUsed*/ false);
961
6.19k
      return false;
962
6.46k
    }
963
964
    // Otherwise create a symbol ref.
965
1.92M
    Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
966
1.92M
    return false;
967
1.93M
  }
968
6.64k
  case AsmToken::BigNum:
969
    // return TokError("literal value out of range for directive");
970
6.64k
    KsError = KS_ERR_ASM_DIRECTIVE_VALUE_RANGE;
971
6.64k
    return true;
972
2.11M
  case AsmToken::Integer: {
973
    //SMLoc Loc = getTok().getLoc();
974
2.11M
    bool valid;
975
2.11M
    int64_t IntVal = getTok().getIntVal(valid);
976
2.11M
    if (!valid) {
977
0
        return true;
978
0
    }
979
2.11M
    Res = MCConstantExpr::create(IntVal, getContext());
980
2.11M
    EndLoc = Lexer.getTok().getEndLoc();
981
2.11M
    Lex(); // Eat token.
982
    // Look for 'b' or 'f' following an Integer as a directional label
983
2.11M
    if (Lexer.getKind() == AsmToken::Identifier) {
984
109k
      StringRef IDVal = getTok().getString();
985
      // Lookup the symbol variant if used.
986
109k
      std::pair<StringRef, StringRef> Split = IDVal.split('@');
987
109k
      MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
988
109k
      if (Split.first.size() != IDVal.size()) {
989
9.55k
        Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
990
9.55k
        if (Variant == MCSymbolRefExpr::VK_Invalid) {
991
          // return TokError("invalid variant '" + Split.second + "'");
992
9.21k
          KsError = KS_ERR_ASM_VARIANT_INVALID;
993
9.21k
          return true;
994
9.21k
        }
995
340
        IDVal = Split.first;
996
340
      }
997
99.8k
      if (IDVal == "f" || IDVal == "b") {
998
3.45k
        bool valid;
999
3.45k
        MCSymbol *Sym =
1000
3.45k
            Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b", valid);
1001
3.45k
        if (!valid)
1002
3.45k
            return true;
1003
0
        Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1004
0
        if (IDVal == "b" && Sym->isUndefined()) {
1005
          //return Error(Loc, "invalid reference to undefined symbol");
1006
0
          KsError = KS_ERR_ASM_INVALIDOPERAND;
1007
0
          return true;
1008
0
        }
1009
0
        EndLoc = Lexer.getTok().getEndLoc();
1010
0
        Lex(); // Eat identifier.
1011
0
      }
1012
99.8k
    }
1013
2.10M
    return false;
1014
2.11M
  }
1015
522k
  case AsmToken::Real: {
1016
522k
    APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
1017
522k
    uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1018
522k
    Res = MCConstantExpr::create(IntVal, getContext());
1019
522k
    EndLoc = Lexer.getTok().getEndLoc();
1020
522k
    Lex(); // Eat token.
1021
522k
    return false;
1022
2.11M
  }
1023
781k
  case AsmToken::Dot: {
1024
    // This is a '.' reference, which references the current PC.  Emit a
1025
    // temporary label to the streamer and refer to it.
1026
781k
    MCSymbol *Sym = Ctx.createTempSymbol();
1027
781k
    Out.EmitLabel(Sym);
1028
781k
    Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1029
781k
    EndLoc = Lexer.getTok().getEndLoc();
1030
781k
    Lex(); // Eat identifier.
1031
781k
    return false;
1032
2.11M
  }
1033
928k
  case AsmToken::LParen:
1034
928k
    Lex(); // Eat the '('.
1035
928k
    return parseParenExpr(Res, EndLoc);
1036
4.12k
  case AsmToken::LBrac:
1037
4.12k
    if (!PlatformParser->HasBracketExpressions()) {
1038
      // return TokError("brackets expression not supported on this target");
1039
4.12k
      KsError = KS_ERR_ASM_EXPR_BRACKET;
1040
4.12k
      return true;
1041
4.12k
    }
1042
0
    Lex(); // Eat the '['.
1043
0
    return parseBracketExpr(Res, EndLoc);
1044
744k
  case AsmToken::Minus:
1045
744k
    Lex(); // Eat the operator.
1046
744k
    if (parsePrimaryExprAux(Res, EndLoc, depth+1))
1047
49.6k
      return true;
1048
694k
    Res = MCUnaryExpr::createMinus(Res, getContext());
1049
694k
    return false;
1050
219k
  case AsmToken::Plus:
1051
219k
    Lex(); // Eat the operator.
1052
219k
    if (parsePrimaryExprAux(Res, EndLoc, depth+1))
1053
16.8k
      return true;
1054
202k
    Res = MCUnaryExpr::createPlus(Res, getContext());
1055
202k
    return false;
1056
105k
  case AsmToken::Tilde:
1057
105k
    Lex(); // Eat the operator.
1058
105k
    if (parsePrimaryExprAux(Res, EndLoc, depth+1))
1059
10.3k
      return true;
1060
95.4k
    Res = MCUnaryExpr::createNot(Res, getContext());
1061
95.4k
    return false;
1062
8.46M
  }
1063
8.46M
}
1064
1065
/// \brief Parse a primary expression and return it.
1066
///  primaryexpr ::= (parenexpr
1067
///  primaryexpr ::= symbol
1068
///  primaryexpr ::= number
1069
///  primaryexpr ::= '.'
1070
///  primaryexpr ::= ~,+,- primaryexpr
1071
bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc)
1072
7.32M
{
1073
7.32M
  return parsePrimaryExprAux(Res, EndLoc, 0);
1074
7.32M
}
1075
1076
2.21M
bool AsmParser::parseExpression(const MCExpr *&Res) {
1077
2.21M
  SMLoc EndLoc;
1078
2.21M
  return parseExpression(Res, EndLoc);
1079
2.21M
}
1080
1081
const MCExpr *
1082
AsmParser::applyModifierToExpr(const MCExpr *E,
1083
72.8k
                               MCSymbolRefExpr::VariantKind Variant) {
1084
  // Ask the target implementation about this expression first.
1085
72.8k
  const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1086
72.8k
  if (NewE)
1087
772
    return NewE;
1088
  // Recurse over the given expression, rebuilding it to apply the given variant
1089
  // if there is exactly one symbol.
1090
72.0k
  switch (E->getKind()) {
1091
0
  case MCExpr::Target:
1092
9.70k
  case MCExpr::Constant:
1093
9.70k
    return nullptr;
1094
1095
23.0k
  case MCExpr::SymbolRef: {
1096
23.0k
    const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1097
1098
23.0k
    if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1099
      //TokError("invalid variant on expression '" + getTok().getIdentifier() +
1100
      //         "' (already modified)");
1101
2.04k
      return E;
1102
2.04k
    }
1103
1104
21.0k
    return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1105
23.0k
  }
1106
1107
10.5k
  case MCExpr::Unary: {
1108
10.5k
    const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1109
10.5k
    const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1110
10.5k
    if (!Sub)
1111
4.36k
      return nullptr;
1112
6.13k
    return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1113
10.5k
  }
1114
1115
28.7k
  case MCExpr::Binary: {
1116
28.7k
    const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1117
28.7k
    const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1118
28.7k
    const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1119
1120
28.7k
    if (!LHS && !RHS)
1121
1.66k
      return nullptr;
1122
1123
27.0k
    if (!LHS)
1124
1.55k
      LHS = BE->getLHS();
1125
27.0k
    if (!RHS)
1126
5.68k
      RHS = BE->getRHS();
1127
1128
27.0k
    return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1129
28.7k
  }
1130
72.0k
  }
1131
1132
72.0k
  llvm_unreachable("Invalid expression kind!");
1133
72.0k
}
1134
1135
/// \brief Parse an expression and return it.
1136
///
1137
///  expr ::= expr &&,|| expr               -> lowest.
1138
///  expr ::= expr |,^,&,! expr
1139
///  expr ::= expr ==,!=,<>,<,<=,>,>= expr
1140
///  expr ::= expr <<,>> expr
1141
///  expr ::= expr +,- expr
1142
///  expr ::= expr *,/,% expr               -> highest.
1143
///  expr ::= primaryexpr
1144
///
1145
5.01M
bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1146
  // Parse the expression.
1147
5.01M
  Res = nullptr;
1148
5.01M
  if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1149
1.96M
    return true;
1150
1151
  // As a special case, we support 'a op b @ modifier' by rewriting the
1152
  // expression to include the modifier. This is inefficient, but in general we
1153
  // expect users to use 'a@modifier op b'.
1154
3.05M
  if (Lexer.getKind() == AsmToken::At) {
1155
45.7k
    Lex();
1156
1157
45.7k
    if (Lexer.isNot(AsmToken::Identifier)) {
1158
      // return TokError("unexpected symbol modifier following '@'");
1159
10.0k
      KsError = KS_ERR_ASM_SYMBOL_MODIFIER;
1160
10.0k
      return true;
1161
10.0k
    }
1162
1163
35.7k
    MCSymbolRefExpr::VariantKind Variant =
1164
35.7k
        MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1165
35.7k
    if (Variant == MCSymbolRefExpr::VK_Invalid) {
1166
      // return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1167
30.9k
      KsError = KS_ERR_ASM_VARIANT_INVALID;
1168
30.9k
      return true;
1169
30.9k
    }
1170
1171
4.80k
    const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1172
4.80k
    if (!ModifiedRes) {
1173
      // return TokError("invalid modifier '" + getTok().getIdentifier() +
1174
      //                 "' (no symbols present)");
1175
797
      KsError = KS_ERR_ASM_VARIANT_INVALID;
1176
797
      return true;
1177
797
    }
1178
1179
4.00k
    Res = ModifiedRes;
1180
4.00k
    Lex();
1181
4.00k
  }
1182
1183
  // Try to constant fold it up front, if possible.
1184
3.00M
  int64_t Value;
1185
3.00M
  if (Res->evaluateAsAbsolute(Value))
1186
1.29M
    Res = MCConstantExpr::create(Value, getContext());
1187
1188
3.00M
  return false;
1189
3.05M
}
1190
1191
211
bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1192
211
  Res = nullptr;
1193
211
  return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1194
211
}
1195
1196
bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1197
20
                                      SMLoc &EndLoc) {
1198
20
  if (parseParenExpr(Res, EndLoc))
1199
16
    return true;
1200
1201
4
  for (; ParenDepth > 0; --ParenDepth) {
1202
0
    if (parseBinOpRHS(1, Res, EndLoc))
1203
0
      return true;
1204
1205
    // We don't Lex() the last RParen.
1206
    // This is the same behavior as parseParenExpression().
1207
0
    if (ParenDepth - 1 > 0) {
1208
0
      if (Lexer.isNot(AsmToken::RParen)) {
1209
        // return TokError("expected ')' in parentheses expression");
1210
0
        KsError = KS_ERR_ASM_RPAREN;
1211
0
        return true;
1212
0
      }
1213
0
      EndLoc = Lexer.getTok().getEndLoc();
1214
0
      Lex();
1215
0
    }
1216
0
  }
1217
4
  return false;
1218
4
}
1219
1220
760k
bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1221
760k
  const MCExpr *Expr;
1222
1223
  //SMLoc StartLoc = Lexer.getLoc();
1224
760k
  if (parseExpression(Expr))
1225
19.3k
    return true;
1226
1227
740k
  if (!Expr->evaluateAsAbsolute(Res)) {
1228
    //return Error(StartLoc, "expected absolute expression");
1229
113k
    KsError = KS_ERR_ASM_INVALIDOPERAND;
1230
113k
    return true;
1231
113k
  }
1232
1233
627k
  return false;
1234
740k
}
1235
1236
static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1237
                                         MCBinaryExpr::Opcode &Kind,
1238
7.40M
                                         bool ShouldUseLogicalShr) {
1239
7.40M
  switch (K) {
1240
4.00M
  default:
1241
4.00M
    return 0; // not a binop.
1242
1243
  // Lowest Precedence: &&, ||
1244
11.9k
  case AsmToken::AmpAmp:
1245
11.9k
    Kind = MCBinaryExpr::LAnd;
1246
11.9k
    return 1;
1247
23.4k
  case AsmToken::PipePipe:
1248
23.4k
    Kind = MCBinaryExpr::LOr;
1249
23.4k
    return 1;
1250
1251
  // Low Precedence: |, &, ^
1252
  //
1253
  // FIXME: gas seems to support '!' as an infix operator?
1254
43.8k
  case AsmToken::Pipe:
1255
43.8k
    Kind = MCBinaryExpr::Or;
1256
43.8k
    return 2;
1257
214k
  case AsmToken::Caret:
1258
214k
    Kind = MCBinaryExpr::Xor;
1259
214k
    return 2;
1260
62.8k
  case AsmToken::Amp:
1261
62.8k
    Kind = MCBinaryExpr::And;
1262
62.8k
    return 2;
1263
1264
  // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1265
9.72k
  case AsmToken::EqualEqual:
1266
9.72k
    Kind = MCBinaryExpr::EQ;
1267
9.72k
    return 3;
1268
1.61k
  case AsmToken::ExclaimEqual:
1269
11.0k
  case AsmToken::LessGreater:
1270
11.0k
    Kind = MCBinaryExpr::NE;
1271
11.0k
    return 3;
1272
74.6k
  case AsmToken::Less:
1273
74.6k
    Kind = MCBinaryExpr::LT;
1274
74.6k
    return 3;
1275
8.59k
  case AsmToken::LessEqual:
1276
8.59k
    Kind = MCBinaryExpr::LTE;
1277
8.59k
    return 3;
1278
81.2k
  case AsmToken::Greater:
1279
81.2k
    Kind = MCBinaryExpr::GT;
1280
81.2k
    return 3;
1281
12.7k
  case AsmToken::GreaterEqual:
1282
12.7k
    Kind = MCBinaryExpr::GTE;
1283
12.7k
    return 3;
1284
1285
  // Intermediate Precedence: <<, >>
1286
10.5k
  case AsmToken::LessLess:
1287
10.5k
    Kind = MCBinaryExpr::Shl;
1288
10.5k
    return 4;
1289
8.07k
  case AsmToken::GreaterGreater:
1290
8.07k
    Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1291
8.07k
    return 4;
1292
1293
  // High Intermediate Precedence: +, -
1294
476k
  case AsmToken::Plus:
1295
476k
    Kind = MCBinaryExpr::Add;
1296
476k
    return 5;
1297
1.62M
  case AsmToken::Minus:
1298
1.62M
    Kind = MCBinaryExpr::Sub;
1299
1.62M
    return 5;
1300
1301
  // Highest Precedence: *, /, %
1302
456k
  case AsmToken::Star:
1303
456k
    Kind = MCBinaryExpr::Mul;
1304
456k
    return 6;
1305
192k
  case AsmToken::Slash:
1306
192k
    Kind = MCBinaryExpr::Div;
1307
192k
    return 6;
1308
87.1k
  case AsmToken::Percent:
1309
87.1k
    Kind = MCBinaryExpr::Mod;
1310
87.1k
    return 6;
1311
7.40M
  }
1312
7.40M
}
1313
1314
static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1315
                                      MCBinaryExpr::Opcode &Kind,
1316
0
                                      bool ShouldUseLogicalShr) {
1317
0
  switch (K) {
1318
0
  default:
1319
0
    return 0; // not a binop.
1320
1321
  // Lowest Precedence: &&, ||
1322
0
  case AsmToken::AmpAmp:
1323
0
    Kind = MCBinaryExpr::LAnd;
1324
0
    return 2;
1325
0
  case AsmToken::PipePipe:
1326
0
    Kind = MCBinaryExpr::LOr;
1327
0
    return 1;
1328
1329
  // Low Precedence: ==, !=, <>, <, <=, >, >=
1330
0
  case AsmToken::EqualEqual:
1331
0
    Kind = MCBinaryExpr::EQ;
1332
0
    return 3;
1333
0
  case AsmToken::ExclaimEqual:
1334
0
  case AsmToken::LessGreater:
1335
0
    Kind = MCBinaryExpr::NE;
1336
0
    return 3;
1337
0
  case AsmToken::Less:
1338
0
    Kind = MCBinaryExpr::LT;
1339
0
    return 3;
1340
0
  case AsmToken::LessEqual:
1341
0
    Kind = MCBinaryExpr::LTE;
1342
0
    return 3;
1343
0
  case AsmToken::Greater:
1344
0
    Kind = MCBinaryExpr::GT;
1345
0
    return 3;
1346
0
  case AsmToken::GreaterEqual:
1347
0
    Kind = MCBinaryExpr::GTE;
1348
0
    return 3;
1349
1350
  // Low Intermediate Precedence: +, -
1351
0
  case AsmToken::Plus:
1352
0
    Kind = MCBinaryExpr::Add;
1353
0
    return 4;
1354
0
  case AsmToken::Minus:
1355
0
    Kind = MCBinaryExpr::Sub;
1356
0
    return 4;
1357
1358
  // High Intermediate Precedence: |, &, ^
1359
  //
1360
  // FIXME: gas seems to support '!' as an infix operator?
1361
0
  case AsmToken::Pipe:
1362
0
    Kind = MCBinaryExpr::Or;
1363
0
    return 5;
1364
0
  case AsmToken::Caret:
1365
0
    Kind = MCBinaryExpr::Xor;
1366
0
    return 5;
1367
0
  case AsmToken::Amp:
1368
0
    Kind = MCBinaryExpr::And;
1369
0
    return 5;
1370
1371
  // Highest Precedence: *, /, %, <<, >>
1372
0
  case AsmToken::Star:
1373
0
    Kind = MCBinaryExpr::Mul;
1374
0
    return 6;
1375
0
  case AsmToken::Slash:
1376
0
    Kind = MCBinaryExpr::Div;
1377
0
    return 6;
1378
0
  case AsmToken::Percent:
1379
0
    Kind = MCBinaryExpr::Mod;
1380
0
    return 6;
1381
0
  case AsmToken::LessLess:
1382
0
    Kind = MCBinaryExpr::Shl;
1383
0
    return 6;
1384
0
  case AsmToken::GreaterGreater:
1385
0
    Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1386
0
    return 6;
1387
0
  }
1388
0
}
1389
1390
unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1391
7.40M
                                       MCBinaryExpr::Opcode &Kind) {
1392
7.40M
  bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1393
7.40M
  return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1394
7.40M
                  : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1395
7.40M
}
1396
1397
/// \brief Parse all binary operators with precedence >= 'Precedence'.
1398
/// Res contains the LHS of the expression on input.
1399
bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1400
3.46M
                              SMLoc &EndLoc) {
1401
5.42M
  while (1) {
1402
5.42M
    MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1403
5.42M
    unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1404
1405
    // If the next token is lower precedence than we are allowed to eat, return
1406
    // successfully with what we ate already.
1407
5.42M
    if (TokPrec < Precedence)
1408
3.17M
      return false;
1409
1410
2.25M
    Lex();
1411
1412
    // Eat the next primary expression.
1413
2.25M
    const MCExpr *RHS;
1414
2.25M
    if (parsePrimaryExpr(RHS, EndLoc))
1415
274k
      return true;
1416
1417
    // If BinOp binds less tightly with RHS than the operator after RHS, let
1418
    // the pending operator take RHS as its LHS.
1419
1.97M
    MCBinaryExpr::Opcode Dummy;
1420
1.97M
    unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1421
1.97M
    if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1422
16.5k
      return true;
1423
1424
    // Merge LHS and RHS according to operator.
1425
1.96M
    Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
1426
1.96M
  }
1427
3.46M
}
1428
1429
bool AsmParser::isNasmDirective(StringRef IDVal)
1430
1.93k
{
1431
1.93k
    return (DirectiveKindMap.find(IDVal.lower()) != DirectiveKindMap.end());
1432
1.93k
}
1433
1434
bool AsmParser::isDirective(StringRef IDVal)
1435
7.83M
{
1436
7.83M
    if (KsSyntax == KS_OPT_SYNTAX_NASM)
1437
798
        return isNasmDirective(IDVal);
1438
7.83M
    else // Directives start with "."
1439
7.83M
        return (!IDVal.empty() && IDVal[0] == '.' && IDVal != ".");
1440
7.83M
}
1441
1442
/// ParseStatement:
1443
///   ::= EndOfStatement
1444
///   ::= Label* Directive ...Operands... EndOfStatement
1445
///   ::= Label* Identifier OperandList* EndOfStatement
1446
// return true on error
1447
bool AsmParser::parseStatement(ParseStatementInfo &Info,
1448
                               MCAsmParserSemaCallback *SI, uint64_t &Address)
1449
106M
{
1450
106M
  KsError = 0;
1451
106M
  if (Lexer.is(AsmToken::EndOfStatement)) {
1452
87.6M
    Out.AddBlankLine();
1453
87.6M
    Lex();
1454
87.6M
    return false;
1455
87.6M
  }
1456
1457
  // Statements always start with an identifier or are a full line comment.
1458
19.1M
  AsmToken ID = getTok();
1459
  //printf(">>> parseStatement:ID = %s\n", ID.getString().str().c_str());
1460
19.1M
  SMLoc IDLoc = ID.getLoc();
1461
19.1M
  StringRef IDVal;
1462
19.1M
  int64_t LocalLabelVal = -1;
1463
  // A full line comment is a '#' as the first token.
1464
19.1M
  if (Lexer.is(AsmToken::Hash))
1465
8.77M
    return parseCppHashLineFilenameComment(IDLoc);
1466
1467
  // Allow an integer followed by a ':' as a directional local label.
1468
10.3M
  if (Lexer.is(AsmToken::Integer)) {
1469
17.5k
    bool valid;
1470
17.5k
    LocalLabelVal = getTok().getIntVal(valid);
1471
17.5k
    if (!valid) {
1472
0
        return true;
1473
0
    }
1474
17.5k
    if (LocalLabelVal < 0) {
1475
3.17k
      if (!TheCondState.Ignore) {
1476
        // return TokError("unexpected token at start of statement");
1477
381
        Info.KsError = KS_ERR_ASM_STAT_TOKEN;
1478
381
        return true;
1479
381
      }
1480
2.79k
      IDVal = "";
1481
14.3k
    } else {
1482
14.3k
      IDVal = getTok().getString();
1483
14.3k
      Lex(); // Consume the integer token to be used as an identifier token.
1484
14.3k
      if (Lexer.getKind() != AsmToken::Colon) {
1485
10.7k
        if (!TheCondState.Ignore) {
1486
          // return TokError("unexpected token at start of statement");
1487
3.05k
          Info.KsError = KS_ERR_ASM_STAT_TOKEN;
1488
3.05k
          return true;
1489
3.05k
        }
1490
10.7k
      }
1491
14.3k
    }
1492
10.3M
  } else if (Lexer.is(AsmToken::Dot)) {
1493
    // Treat '.' as a valid identifier in this context.
1494
528k
    Lex();
1495
528k
    IDVal = ".";
1496
9.79M
  } else if (Lexer.is(AsmToken::LCurly)) {
1497
    // Treat '{' as a valid identifier in this context.
1498
9.90k
    Lex();
1499
9.90k
    IDVal = "{";
1500
9.78M
  } else if (Lexer.is(AsmToken::RCurly)) {
1501
    // Treat '}' as a valid identifier in this context.
1502
11.8k
    Lex();
1503
11.8k
    IDVal = "}";
1504
9.77M
  } else if (KsSyntax == KS_OPT_SYNTAX_NASM && Lexer.is(AsmToken::LBrac)) {
1505
    // [bits xx]
1506
4
    Lex();
1507
4
    ID = Lexer.getTok();
1508
4
    if (ID.getString().lower() == "bits") {
1509
0
        Lex();
1510
0
        if (parseNasmDirectiveBits()) {
1511
0
            Info.KsError = KS_ERR_ASM_DIRECTIVE_ID;
1512
0
            return true;
1513
0
        } else {
1514
0
            return false;
1515
0
        }
1516
4
    } else {
1517
4
        Info.KsError = KS_ERR_ASM_DIRECTIVE_ID;
1518
4
        return true;
1519
4
    }
1520
9.77M
  } else if (KsSyntax == KS_OPT_SYNTAX_NASM && isNasmDirective(ID.getString())) {
1521
116
      Lex();
1522
116
      IDVal = ID.getString();
1523
9.77M
  } else if (parseIdentifier(IDVal)) {
1524
96.2k
    if (!TheCondState.Ignore) {
1525
      // return TokError("unexpected token at start of statement");
1526
64.7k
      Info.KsError = KS_ERR_ASM_STAT_TOKEN;
1527
64.7k
      return true;
1528
64.7k
    }
1529
31.4k
    IDVal = "";
1530
31.4k
  }
1531
1532
  // Handle conditional assembly here before checking for skipping.  We
1533
  // have to do this so that .endif isn't skipped in a ".if 0" block for
1534
  // example.
1535
1536
10.2M
  StringMap<DirectiveKind>::const_iterator DirKindIt =
1537
10.2M
      DirectiveKindMap.find(IDVal.lower());
1538
10.2M
  DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1539
10.2M
                              ? DK_NO_DIRECTIVE
1540
10.2M
                              : DirKindIt->getValue();
1541
10.2M
  switch (DirKind) {
1542
9.81M
  default:
1543
9.81M
    break;
1544
9.81M
  case DK_IF:
1545
19.9k
  case DK_IFEQ:
1546
24.2k
  case DK_IFGE:
1547
29.5k
  case DK_IFGT:
1548
36.5k
  case DK_IFLE:
1549
39.4k
  case DK_IFLT:
1550
42.6k
  case DK_IFNE:
1551
42.6k
    return parseDirectiveIf(IDLoc, DirKind);
1552
16.1k
  case DK_IFB:
1553
16.1k
    return parseDirectiveIfb(IDLoc, true);
1554
19.6k
  case DK_IFNB:
1555
19.6k
    return parseDirectiveIfb(IDLoc, false);
1556
13.7k
  case DK_IFC:
1557
13.7k
    return parseDirectiveIfc(IDLoc, true);
1558
751
  case DK_IFEQS:
1559
751
    return parseDirectiveIfeqs(IDLoc, true);
1560
282k
  case DK_IFNC:
1561
282k
    return parseDirectiveIfc(IDLoc, false);
1562
27.0k
  case DK_IFNES:
1563
27.0k
    return parseDirectiveIfeqs(IDLoc, false);
1564
4.14k
  case DK_IFDEF:
1565
4.14k
    return parseDirectiveIfdef(IDLoc, true);
1566
6.36k
  case DK_IFNDEF:
1567
6.36k
  case DK_IFNOTDEF:
1568
6.36k
    return parseDirectiveIfdef(IDLoc, false);
1569
16.4k
  case DK_ELSEIF:
1570
16.4k
    return parseDirectiveElseIf(IDLoc);
1571
14.7k
  case DK_ELSE:
1572
14.7k
    return parseDirectiveElse(IDLoc);
1573
8.06k
  case DK_ENDIF:
1574
8.06k
    return parseDirectiveEndIf(IDLoc);
1575
10.2M
  }
1576
1577
  // Ignore the statement if in the middle of inactive conditional
1578
  // (e.g. ".if 0").
1579
9.81M
  if (TheCondState.Ignore) {
1580
79.4k
    eatToEndOfStatement();
1581
79.4k
    return false;
1582
79.4k
  }
1583
1584
  // FIXME: Recurse on local labels?
1585
1586
  // See what kind of statement we have.
1587
9.73M
  switch (Lexer.getKind()) {
1588
4.71k
  case AsmToken::Colon: {
1589
4.71k
    bool valid;
1590
4.71k
    if (!getTargetParser().isLabel(ID, valid))
1591
50
      break;
1592
4.66k
    if (!valid) {
1593
0
        Info.KsError = KS_ERR_ASM_LABEL_INVALID;
1594
0
        return true;
1595
0
    }
1596
4.66k
    checkForValidSection();
1597
1598
    // identifier ':'   -> Label.
1599
4.66k
    Lex();
1600
1601
    // Diagnose attempt to use '.' as a label.
1602
4.66k
    if (IDVal == ".") {
1603
      //return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1604
2.18k
      KsError = KS_ERR_ASM_INVALIDOPERAND;
1605
2.18k
      return true;
1606
2.18k
    }
1607
1608
    // Diagnose attempt to use a variable as a label.
1609
    //
1610
    // FIXME: Diagnostics. Note the location of the definition as a label.
1611
    // FIXME: This doesn't diagnose assignment to a symbol which has been
1612
    // implicitly marked as external.
1613
2.47k
    MCSymbol *Sym;
1614
2.47k
    if (LocalLabelVal == -1) {
1615
2.07k
      if (ParsingInlineAsm && SI) {
1616
0
        StringRef RewrittenLabel =
1617
0
            SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1618
0
        assert(RewrittenLabel.size() &&
1619
0
               "We should have an internal name here.");
1620
0
        Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1621
0
                                       RewrittenLabel);
1622
0
        IDVal = RewrittenLabel;
1623
0
      }
1624
2.07k
      if (IDVal.empty()) {
1625
12
          return true;
1626
12
      }
1627
2.06k
      Sym = getContext().getOrCreateSymbol(IDVal);
1628
2.06k
    } else {
1629
406
      bool valid;
1630
406
      Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal, valid);
1631
406
      if (!valid) {
1632
406
          Info.KsError = KS_ERR_ASM_LABEL_INVALID;
1633
406
          return true;
1634
406
      }
1635
406
    }
1636
1637
2.06k
    Sym->redefineIfPossible();
1638
1639
2.06k
    if (!Sym->isUndefined() || Sym->isVariable()) {
1640
      //return Error(IDLoc, "invalid symbol redefinition");
1641
65
      Info.KsError = KS_ERR_ASM_SYMBOL_REDEFINED;
1642
65
      return true;
1643
65
    }
1644
1645
    // Emit the label.
1646
1.99k
    if (!ParsingInlineAsm)
1647
1.99k
      Out.EmitLabel(Sym);
1648
1649
1.99k
    getTargetParser().onLabelParsed(Sym);
1650
1651
    // Consume any end of statement token, if present, to avoid spurious
1652
    // AddBlankLine calls().
1653
1.99k
    if (Lexer.is(AsmToken::EndOfStatement)) {
1654
458
      Lex();
1655
458
      if (Lexer.is(AsmToken::Eof))
1656
171
        return false;
1657
458
    }
1658
1659
1.82k
    return false;
1660
1.99k
  }
1661
1662
1.57M
  case AsmToken::Equal:
1663
1.57M
    if (!getTargetParser().equalIsAsmAssignment())
1664
3.04k
      break;
1665
    // identifier '=' ... -> assignment statement
1666
1.57M
    Lex();
1667
1668
1.57M
    if (parseAssignment(IDVal, true)) {
1669
750k
        Info.KsError = KS_ERR_ASM_DIRECTIVE_EQU;
1670
750k
        return true;
1671
750k
    }
1672
821k
    return false;
1673
1674
8.15M
  default: // Normal instruction or directive.
1675
8.15M
    break;
1676
9.73M
  }
1677
1678
  // If macros are enabled, check to see if this is a macro instantiation.
1679
8.16M
  if (areMacrosEnabled())
1680
8.16M
    if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1681
322k
      return handleMacroEntry(M, IDLoc);
1682
322k
    }
1683
1684
  // Otherwise, we have a normal instruction or directive.
1685
7.83M
  if (isDirective(IDVal)) {
1686
    // There are several entities interested in parsing directives:
1687
    //
1688
    // 1. The target-specific assembly parser. Some directives are target
1689
    //    specific or may potentially behave differently on certain targets.
1690
    // 2. Asm parser extensions. For example, platform-specific parsers
1691
    //    (like the ELF parser) register themselves as extensions.
1692
    // 3. The generic directive parser implemented by this class. These are
1693
    //    all the directives that behave in a target and platform independent
1694
    //    manner, or at least have a default behavior that's shared between
1695
    //    all targets and platforms.
1696
1697
    // First query the target-specific parser. It will return 'true' if it
1698
    // isn't interested in this directive.
1699
7.37M
      uint64_t BytesInFragment = getStreamer().getCurrentFragmentSize();
1700
7.37M
      if (!getTargetParser().ParseDirective(ID)){
1701
        // increment the address for the next statement if the directive
1702
        // has emitted any value to the streamer.
1703
480k
        Address += getStreamer().getCurrentFragmentSize() - BytesInFragment;
1704
480k
        return false;
1705
480k
        }
1706
1707
    // Next, check the extension directive map to see if any extension has
1708
    // registered itself to parse this directive.
1709
6.89M
    std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1710
6.89M
        ExtensionDirectiveMap.lookup(IDVal);
1711
6.89M
    if (Handler.first)
1712
1.07M
      return (*Handler.second)(Handler.first, IDVal, IDLoc);
1713
1714
    // Finally, if no one else is interested in this directive, it must be
1715
    // generic and familiar to this class.
1716
5.81M
    switch (DirKind) {
1717
4.27M
    default:
1718
4.27M
      break;
1719
4.27M
    case DK_SET:
1720
9.54k
    case DK_EQU:
1721
9.54k
      return parseDirectiveSet(IDVal, true);
1722
0
    case DK_EQUIV:
1723
0
      return parseDirectiveSet(IDVal, false);
1724
1.38k
    case DK_ASCII:
1725
1.38k
      return parseDirectiveAscii(IDVal, false);
1726
2.42k
    case DK_ASCIZ:
1727
11.8k
    case DK_STRING:
1728
11.8k
      return parseDirectiveAscii(IDVal, true);
1729
11.6k
    case DK_BYTE:
1730
11.6k
      return parseDirectiveValue(1, Info.KsError);
1731
624
    case DK_SHORT:
1732
658
    case DK_VALUE:
1733
46.4k
    case DK_2BYTE:
1734
46.4k
      return parseDirectiveValue(2, Info.KsError);
1735
1.01k
    case DK_LONG:
1736
22.3k
    case DK_INT:
1737
203k
    case DK_4BYTE:
1738
203k
      return parseDirectiveValue(4, Info.KsError);
1739
132
    case DK_QUAD:
1740
1.60k
    case DK_8BYTE:
1741
1.60k
      return parseDirectiveValue(8, Info.KsError);
1742
2.71k
    case DK_OCTA:
1743
2.71k
      return parseDirectiveOctaValue(Info.KsError);
1744
1.42k
    case DK_SINGLE:
1745
18.0k
    case DK_FLOAT:
1746
18.0k
      return parseDirectiveRealValue(APFloat::IEEEsingle);
1747
3
    case DK_DOUBLE:
1748
3
      return parseDirectiveRealValue(APFloat::IEEEdouble);
1749
130k
    case DK_ALIGN: {
1750
130k
      bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1751
130k
      return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1752
1.42k
    }
1753
706
    case DK_ALIGN32: {
1754
706
      bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1755
706
      return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1756
1.42k
    }
1757
4.34k
    case DK_BALIGN:
1758
4.34k
      return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1759
5.05k
    case DK_BALIGNW:
1760
5.05k
      return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1761
812
    case DK_BALIGNL:
1762
812
      return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1763
0
    case DK_P2ALIGN:
1764
0
      return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1765
0
    case DK_P2ALIGNW:
1766
0
      return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1767
0
    case DK_P2ALIGNL:
1768
0
      return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1769
36.3k
    case DK_ORG:
1770
36.3k
      return parseDirectiveOrg();
1771
126k
    case DK_FILL:
1772
126k
      return parseDirectiveFill();
1773
48.2k
    case DK_ZERO:
1774
48.2k
      return parseDirectiveZero();
1775
0
    case DK_EXTERN:
1776
0
      eatToEndOfStatement(); // .extern is the default, ignore it.
1777
0
      return false;
1778
616
    case DK_GLOBL:
1779
664
    case DK_GLOBAL:
1780
664
      return parseDirectiveSymbolAttribute(MCSA_Global);
1781
0
    case DK_LAZY_REFERENCE:
1782
0
      return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1783
0
    case DK_NO_DEAD_STRIP:
1784
0
      return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1785
0
    case DK_SYMBOL_RESOLVER:
1786
0
      return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1787
0
    case DK_PRIVATE_EXTERN:
1788
0
      return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1789
0
    case DK_REFERENCE:
1790
0
      return parseDirectiveSymbolAttribute(MCSA_Reference);
1791
0
    case DK_WEAK_DEFINITION:
1792
0
      return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1793
0
    case DK_WEAK_REFERENCE:
1794
0
      return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1795
0
    case DK_WEAK_DEF_CAN_BE_HIDDEN:
1796
0
      return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1797
19.2k
    case DK_COMM:
1798
19.3k
    case DK_COMMON:
1799
19.3k
      return parseDirectiveComm(/*IsLocal=*/false);
1800
3.06k
    case DK_LCOMM:
1801
3.06k
      return parseDirectiveComm(/*IsLocal=*/true);
1802
58
    case DK_ABORT:
1803
58
      return parseDirectiveAbort();
1804
1.52k
    case DK_INCLUDE:
1805
1.52k
      return parseDirectiveInclude();
1806
0
    case DK_INCBIN:
1807
0
      return parseDirectiveIncbin();
1808
6
    case DK_CODE16:
1809
6
    case DK_CODE16GCC:
1810
      // return TokError(Twine(IDVal) + " not supported yet");
1811
6
      Info.KsError = KS_ERR_ASM_UNSUPPORTED;
1812
6
      return true;
1813
287k
    case DK_REPT:
1814
287k
      return parseDirectiveRept(IDLoc, IDVal);
1815
28.8k
    case DK_IRP:
1816
28.8k
      return parseDirectiveIrp(IDLoc);
1817
31.6k
    case DK_IRPC:
1818
31.6k
      return parseDirectiveIrpc(IDLoc);
1819
27.3k
    case DK_ENDR:
1820
27.3k
      return parseDirectiveEndr(IDLoc);
1821
0
    case DK_BUNDLE_ALIGN_MODE:
1822
0
      return parseDirectiveBundleAlignMode();
1823
0
    case DK_BUNDLE_LOCK:
1824
0
      return parseDirectiveBundleLock();
1825
0
    case DK_BUNDLE_UNLOCK:
1826
0
      return parseDirectiveBundleUnlock();
1827
0
    case DK_SLEB128:
1828
0
      return parseDirectiveLEB128(true);
1829
0
    case DK_ULEB128:
1830
0
      return parseDirectiveLEB128(false);
1831
3.60k
    case DK_SPACE:
1832
16.9k
    case DK_SKIP:
1833
16.9k
      return parseDirectiveSpace(IDVal);
1834
26.1k
    case DK_FILE:
1835
26.1k
      return parseDirectiveFile(IDLoc);
1836
51.4k
    case DK_LINE:
1837
51.4k
      return parseDirectiveLine();
1838
2.79k
    case DK_LOC:
1839
2.79k
      return parseDirectiveLoc();
1840
1
    case DK_STABS:
1841
1
      return parseDirectiveStabs();
1842
0
    case DK_CV_FILE:
1843
0
      return parseDirectiveCVFile();
1844
0
    case DK_CV_LOC:
1845
0
      return parseDirectiveCVLoc();
1846
0
    case DK_CV_LINETABLE:
1847
0
      return parseDirectiveCVLinetable();
1848
0
    case DK_CV_INLINE_LINETABLE:
1849
0
      return parseDirectiveCVInlineLinetable();
1850
0
    case DK_CV_STRINGTABLE:
1851
0
      return parseDirectiveCVStringTable();
1852
0
    case DK_CV_FILECHECKSUMS:
1853
0
      return parseDirectiveCVFileChecksums();
1854
0
    case DK_CFI_SECTIONS:
1855
0
      return parseDirectiveCFISections();
1856
0
    case DK_CFI_STARTPROC:
1857
0
      return parseDirectiveCFIStartProc();
1858
0
    case DK_CFI_ENDPROC:
1859
0
      return parseDirectiveCFIEndProc();
1860
0
    case DK_CFI_DEF_CFA:
1861
0
      return parseDirectiveCFIDefCfa(IDLoc);
1862
0
    case DK_CFI_DEF_CFA_OFFSET:
1863
0
      return parseDirectiveCFIDefCfaOffset();
1864
0
    case DK_CFI_ADJUST_CFA_OFFSET:
1865
0
      return parseDirectiveCFIAdjustCfaOffset();
1866
0
    case DK_CFI_DEF_CFA_REGISTER:
1867
0
      return parseDirectiveCFIDefCfaRegister(IDLoc);
1868
0
    case DK_CFI_OFFSET:
1869
0
      return parseDirectiveCFIOffset(IDLoc);
1870
0
    case DK_CFI_REL_OFFSET:
1871
0
      return parseDirectiveCFIRelOffset(IDLoc);
1872
0
    case DK_CFI_PERSONALITY:
1873
0
      return parseDirectiveCFIPersonalityOrLsda(true);
1874
0
    case DK_CFI_LSDA:
1875
0
      return parseDirectiveCFIPersonalityOrLsda(false);
1876
0
    case DK_CFI_REMEMBER_STATE:
1877
0
      return parseDirectiveCFIRememberState();
1878
0
    case DK_CFI_RESTORE_STATE:
1879
0
      return parseDirectiveCFIRestoreState();
1880
0
    case DK_CFI_SAME_VALUE:
1881
0
      return parseDirectiveCFISameValue(IDLoc);
1882
0
    case DK_CFI_RESTORE:
1883
0
      return parseDirectiveCFIRestore(IDLoc);
1884
0
    case DK_CFI_ESCAPE:
1885
0
      return parseDirectiveCFIEscape();
1886
0
    case DK_CFI_SIGNAL_FRAME:
1887
0
      return parseDirectiveCFISignalFrame();
1888
0
    case DK_CFI_UNDEFINED:
1889
0
      return parseDirectiveCFIUndefined(IDLoc);
1890
0
    case DK_CFI_REGISTER:
1891
0
      return parseDirectiveCFIRegister(IDLoc);
1892
0
    case DK_CFI_WINDOW_SAVE:
1893
0
      return parseDirectiveCFIWindowSave();
1894
0
    case DK_MACROS_ON:
1895
0
    case DK_MACROS_OFF:
1896
0
      return parseDirectiveMacrosOnOff(IDVal);
1897
32.7k
    case DK_MACRO:
1898
32.7k
      return parseDirectiveMacro(IDLoc);
1899
0
    case DK_EXITM:
1900
0
      return parseDirectiveExitMacro(IDVal);
1901
12.0k
    case DK_ENDM:
1902
305k
    case DK_ENDMACRO:
1903
305k
      return parseDirectiveEndMacro(IDVal);
1904
44
    case DK_PURGEM:
1905
44
      return parseDirectivePurgeMacro(IDLoc);
1906
18.9k
    case DK_END:
1907
18.9k
      return parseDirectiveEnd(IDLoc);
1908
1.92k
    case DK_ERR:
1909
1.92k
      return parseDirectiveError(IDLoc, false);
1910
2.17k
    case DK_ERROR:
1911
2.17k
      return parseDirectiveError(IDLoc, true);
1912
4.35k
    case DK_WARNING:
1913
4.35k
      return parseDirectiveWarning(IDLoc);
1914
24.1k
    case DK_RELOC:
1915
24.1k
      return parseDirectiveReloc(IDLoc);
1916
0
    case DK_NASM_BITS:
1917
0
      if (parseNasmDirectiveBits()) {
1918
0
          Info.KsError = KS_ERR_ASM_DIRECTIVE_ID;
1919
0
          return true;
1920
0
      } else {
1921
0
          return false;
1922
0
      }
1923
0
    case DK_NASM_USE32:
1924
0
      return parseNasmDirectiveUse32();
1925
0
    case DK_NASM_DEFAULT:
1926
0
      if (parseNasmDirectiveDefault()) {
1927
0
        Info.KsError = KS_ERR_ASM_DIRECTIVE_ID;
1928
0
        return true;
1929
0
      } else {
1930
0
        return false;
1931
0
      }
1932
5.81M
    }
1933
1934
    //return Error(IDLoc, "unknown directive");
1935
4.27M
    KsError = KS_ERR_ASM_DIRECTIVE_UNKNOWN;
1936
4.27M
    return true;
1937
5.81M
  }
1938
1939
  // __asm _emit or __asm __emit
1940
464k
  if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1941
0
                           IDVal == "_EMIT" || IDVal == "__EMIT"))
1942
0
    return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1943
1944
  // __asm align
1945
464k
  if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1946
0
    return parseDirectiveMSAlign(IDLoc, Info);
1947
1948
464k
  if (ParsingInlineAsm && (IDVal == "even"))
1949
0
    Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
1950
464k
  checkForValidSection();
1951
1952
  // Canonicalize the opcode to lower case.
1953
464k
  std::string OpcodeStr = IDVal.lower();
1954
464k
  ParseInstructionInfo IInfo(Info.AsmRewrites);
1955
  //printf(">> Going to ParseInstruction()\n");
1956
464k
  bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1957
464k
                                                     Info.ParsedOperands, Info.KsError);
1958
464k
  Info.ParseError = HadError;
1959
1960
  // If parsing succeeded, match the instruction.
1961
464k
  if (!HadError) {
1962
235k
    uint64_t ErrorInfo;
1963
    //printf(">> Going to MatchAndEmitInstruction()\n");
1964
235k
    return getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1965
235k
                                              Info.ParsedOperands, Out,
1966
235k
                                              ErrorInfo, ParsingInlineAsm,
1967
235k
                                              Info.KsError, Address);
1968
235k
  }
1969
1970
229k
  return true;
1971
464k
}
1972
1973
/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
1974
/// since they may not be able to be tokenized to get to the end of line token.
1975
void AsmParser::eatToEndOfLine()
1976
8.77M
{
1977
8.77M
  if (!Lexer.is(AsmToken::EndOfStatement))
1978
1.75M
    Lexer.LexUntilEndOfLine();
1979
  // Eat EOL.
1980
8.77M
  Lex();
1981
8.77M
}
1982
1983
/// parseCppHashLineFilenameComment as this:
1984
///   ::= # number "filename"
1985
/// or just as a full line comment if it doesn't have a number and a string.
1986
8.77M
bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
1987
8.77M
  Lex(); // Eat the hash token.
1988
1989
8.77M
  if (getLexer().isNot(AsmToken::Integer)) {
1990
    // Consume the line since in cases it is not a well-formed line directive,
1991
    // as if were simply a full line comment.
1992
7.67M
    eatToEndOfLine();
1993
7.67M
    return false;
1994
7.67M
  }
1995
1996
1.09M
  bool valid;
1997
1.09M
  int64_t LineNumber = getTok().getIntVal(valid);
1998
1.09M
  if (!valid) {
1999
0
      return true;
2000
0
  }
2001
1.09M
  Lex();
2002
2003
1.09M
  if (getLexer().isNot(AsmToken::String)) {
2004
1.09M
    eatToEndOfLine();
2005
1.09M
    return false;
2006
1.09M
  }
2007
2008
3.91k
  StringRef Filename = getTok().getString();
2009
  // Get rid of the enclosing quotes.
2010
3.91k
  Filename = Filename.substr(1, Filename.size() - 2);
2011
2012
  // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
2013
3.91k
  CppHashLoc = L;
2014
3.91k
  CppHashFilename = Filename;
2015
3.91k
  CppHashLineNumber = LineNumber;
2016
3.91k
  CppHashBuf = CurBuffer;
2017
2018
  // Ignore any trailing characters, they're just comment.
2019
3.91k
  eatToEndOfLine();
2020
3.91k
  return false;
2021
1.09M
}
2022
2023
/// \brief will use the last parsed cpp hash line filename comment
2024
/// for the Filename and LineNo if any in the diagnostic.
2025
1.30M
void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2026
1.30M
  const AsmParser *Parser = static_cast<const AsmParser *>(Context);
2027
1.30M
  raw_ostream &OS = errs();
2028
2029
1.30M
  const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2030
1.30M
  SMLoc DiagLoc = Diag.getLoc();
2031
1.30M
  unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2032
1.30M
  unsigned CppHashBuf =
2033
1.30M
      Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
2034
2035
  // Like SourceMgr::printMessage() we need to print the include stack if any
2036
  // before printing the message.
2037
1.30M
  unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2038
1.30M
  if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2039
1.30M
      DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2040
958k
    SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2041
958k
    DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2042
958k
  }
2043
2044
  // If we have not parsed a cpp hash line filename comment or the source
2045
  // manager changed or buffer changed (like in a nested include) then just
2046
  // print the normal diagnostic using its Filename and LineNo.
2047
1.30M
  if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
2048
1.30M
      DiagBuf != CppHashBuf) {
2049
1.27M
    if (Parser->SavedDiagHandler)
2050
0
      Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2051
1.27M
    else
2052
1.27M
      Diag.print(nullptr, OS);
2053
1.27M
    return;
2054
1.27M
  }
2055
2056
  // Use the CppHashFilename and calculate a line number based on the
2057
  // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
2058
  // the diagnostic.
2059
26.5k
  const std::string &Filename = Parser->CppHashFilename;
2060
2061
26.5k
  int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2062
26.5k
  int CppHashLocLineNo =
2063
26.5k
      Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
2064
26.5k
  int LineNo =
2065
26.5k
      Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2066
2067
26.5k
  SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2068
26.5k
                       Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2069
26.5k
                       Diag.getLineContents(), Diag.getRanges());
2070
2071
26.5k
  if (Parser->SavedDiagHandler)
2072
0
    Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2073
26.5k
  else
2074
26.5k
    NewDiag.print(nullptr, OS);
2075
26.5k
}
2076
2077
// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2078
// difference being that that function accepts '@' as part of identifiers and
2079
// we can't do that. AsmLexer.cpp should probably be changed to handle
2080
// '@' as a special case when needed.
2081
16.4M
static bool isIdentifierChar(char c) {
2082
16.4M
  return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2083
16.4M
         c == '.';
2084
16.4M
}
2085
2086
bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2087
                            ArrayRef<MCAsmMacroParameter> Parameters,
2088
                            ArrayRef<MCAsmMacroArgument> A,
2089
                            bool EnableAtPseudoVariable, SMLoc L)
2090
159M
{
2091
159M
  unsigned NParameters = Parameters.size();
2092
159M
  bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2093
159M
  if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2094
    //return Error(L, "Wrong number of arguments");
2095
0
    return true;
2096
2097
  // A macro without parameters is handled differently on Darwin:
2098
  // gas accepts no arguments and does no substitutions
2099
164M
  while (!Body.empty()) {
2100
    // Scan for the next substitution.
2101
98.5M
    std::size_t End = Body.size(), Pos = 0;
2102
1.86G
    for (; Pos != End; ++Pos) {
2103
      // Check for a substitution or escape.
2104
1.77G
      if (IsDarwin && !NParameters) {
2105
        // This macro has no parameters, look for $0, $1, etc.
2106
730M
        if (Body[Pos] != '$' || Pos + 1 == End)
2107
721M
          continue;
2108
2109
9.02M
        char Next = Body[Pos + 1];
2110
9.02M
        if (Next == '$' || Next == 'n' ||
2111
9.02M
            isdigit(static_cast<unsigned char>(Next)))
2112
763k
          break;
2113
1.04G
      } else {
2114
        // This macro has parameters, look for \foo, \bar, etc.
2115
1.04G
        if (Body[Pos] == '\\' && Pos + 1 != End)
2116
4.68M
          break;
2117
1.04G
      }
2118
1.77G
    }
2119
2120
    // Add the prefix.
2121
98.5M
    OS << Body.slice(0, Pos);
2122
2123
    // Check if we reached the end.
2124
98.5M
    if (Pos == End)
2125
93.1M
      break;
2126
2127
5.45M
    if (IsDarwin && !NParameters) {
2128
763k
      switch (Body[Pos + 1]) {
2129
      // $$ => $
2130
61.3k
      case '$':
2131
61.3k
        OS << '$';
2132
61.3k
        break;
2133
2134
      // $n => number of arguments
2135
373k
      case 'n':
2136
373k
        OS << A.size();
2137
373k
        break;
2138
2139
      // $[0-9] => argument
2140
328k
      default: {
2141
        // Missing arguments are ignored.
2142
328k
        unsigned Index = Body[Pos + 1] - '0';
2143
328k
        if (Index >= A.size())
2144
323k
          break;
2145
2146
        // Otherwise substitute with the token values, with spaces eliminated.
2147
4.67k
        for (const AsmToken &Token : A[Index])
2148
45.0k
          OS << Token.getString();
2149
4.67k
        break;
2150
328k
      }
2151
763k
      }
2152
763k
      Pos += 2;
2153
4.68M
    } else {
2154
4.68M
      unsigned I = Pos + 1;
2155
2156
      // Check for the \@ pseudo-variable.
2157
4.68M
      if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2158
71.9k
        ++I;
2159
4.61M
      else
2160
16.3M
        while (isIdentifierChar(Body[I]) && I + 1 != End)
2161
11.7M
          ++I;
2162
2163
4.68M
      const char *Begin = Body.data() + Pos + 1;
2164
4.68M
      StringRef Argument(Begin, I - (Pos + 1));
2165
4.68M
      unsigned Index = 0;
2166
2167
4.68M
      if (Argument == "@") {
2168
71.9k
        OS << NumOfMacroInstantiations;
2169
71.9k
        Pos += 2;
2170
4.61M
      } else {
2171
9.21M
        for (; Index < NParameters; ++Index)
2172
4.62M
          if (Parameters[Index].Name == Argument)
2173
23.0k
            break;
2174
2175
4.61M
        if (Index == NParameters) {
2176
4.59M
          if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2177
7.77k
            Pos += 3;
2178
4.58M
          else {
2179
4.58M
            OS << '\\' << Argument;
2180
4.58M
            Pos = I;
2181
4.58M
          }
2182
4.59M
        } else {
2183
23.0k
          bool VarargParameter = HasVararg && Index == (NParameters - 1);
2184
23.0k
          for (const AsmToken &Token : A[Index])
2185
            // We expect no quotes around the string's contents when
2186
            // parsing for varargs.
2187
123k
            if (Token.getKind() != AsmToken::String || VarargParameter)
2188
117k
              OS << Token.getString();
2189
6.26k
            else {
2190
6.26k
              bool valid;
2191
6.26k
              OS << Token.getStringContents(valid);
2192
6.26k
              if (!valid) {
2193
0
                  return true;
2194
0
              }
2195
6.26k
            }
2196
2197
23.0k
          Pos += 1 + Argument.size();
2198
23.0k
        }
2199
4.61M
      }
2200
4.68M
    }
2201
    // Update the scan point.
2202
5.45M
    Body = Body.substr(Pos);
2203
5.45M
  }
2204
2205
159M
  return false;
2206
159M
}
2207
2208
MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2209
                                       size_t CondStackDepth)
2210
331k
    : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2211
331k
      CondStackDepth(CondStackDepth) {}
2212
2213
0
static bool isOperator(AsmToken::TokenKind kind) {
2214
0
  switch (kind) {
2215
0
  default:
2216
0
    return false;
2217
0
  case AsmToken::Plus:
2218
0
  case AsmToken::Minus:
2219
0
  case AsmToken::Tilde:
2220
0
  case AsmToken::Slash:
2221
0
  case AsmToken::Star:
2222
0
  case AsmToken::Dot:
2223
0
  case AsmToken::Equal:
2224
0
  case AsmToken::EqualEqual:
2225
0
  case AsmToken::Pipe:
2226
0
  case AsmToken::PipePipe:
2227
0
  case AsmToken::Caret:
2228
0
  case AsmToken::Amp:
2229
0
  case AsmToken::AmpAmp:
2230
0
  case AsmToken::Exclaim:
2231
0
  case AsmToken::ExclaimEqual:
2232
0
  case AsmToken::Percent:
2233
0
  case AsmToken::Less:
2234
0
  case AsmToken::LessEqual:
2235
0
  case AsmToken::LessLess:
2236
0
  case AsmToken::LessGreater:
2237
0
  case AsmToken::Greater:
2238
0
  case AsmToken::GreaterEqual:
2239
0
  case AsmToken::GreaterGreater:
2240
0
    return true;
2241
0
  }
2242
0
}
2243
2244
namespace {
2245
class AsmLexerSkipSpaceRAII {
2246
public:
2247
1.08M
  AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2248
1.08M
    Lexer.setSkipSpace(SkipSpace);
2249
1.08M
  }
2250
2251
1.08M
  ~AsmLexerSkipSpaceRAII() {
2252
1.08M
    Lexer.setSkipSpace(true);
2253
1.08M
  }
2254
2255
private:
2256
  AsmLexer &Lexer;
2257
};
2258
}
2259
2260
bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg)
2261
1.08M
{
2262
2263
1.08M
  if (Vararg) {
2264
0
    if (Lexer.isNot(AsmToken::EndOfStatement)) {
2265
0
      StringRef Str = parseStringToEndOfStatement();
2266
0
      MA.emplace_back(AsmToken::String, Str);
2267
0
    }
2268
0
    return false;
2269
0
  }
2270
2271
1.08M
  unsigned ParenLevel = 0;
2272
1.08M
  unsigned AddTokens = 0;
2273
2274
  // Darwin doesn't use spaces to delmit arguments.
2275
1.08M
  AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2276
2277
2.18M
  for (;;) {
2278
2.18M
    if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
2279
      // return TokError("unexpected token in macro instantiation");
2280
61
      KsError = KS_ERR_ASM_MACRO_TOKEN;
2281
61
      return true;
2282
61
    }
2283
2284
2.18M
    if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
2285
722k
      break;
2286
2287
1.45M
    if (Lexer.is(AsmToken::Space)) {
2288
0
      Lex(); // Eat spaces
2289
2290
      // Spaces can delimit parameters, but could also be part an expression.
2291
      // If the token after a space is an operator, add the token and the next
2292
      // one into this argument
2293
0
      if (!IsDarwin) {
2294
0
        if (isOperator(Lexer.getKind())) {
2295
          // Check to see whether the token is used as an operator,
2296
          // or part of an identifier
2297
0
          const char *NextChar = getTok().getEndLoc().getPointer();
2298
0
          if (*NextChar == ' ')
2299
0
            AddTokens = 2;
2300
0
        }
2301
2302
0
        if (!AddTokens && ParenLevel == 0) {
2303
0
          break;
2304
0
        }
2305
0
      }
2306
0
    }
2307
2308
    // handleMacroEntry relies on not advancing the lexer here
2309
    // to be able to fill in the remaining default parameter values
2310
1.45M
    if (Lexer.is(AsmToken::EndOfStatement))
2311
361k
      break;
2312
2313
    // Adjust the current parentheses level.
2314
1.09M
    if (Lexer.is(AsmToken::LParen))
2315
38.9k
      ++ParenLevel;
2316
1.05M
    else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2317
4.06k
      --ParenLevel;
2318
2319
    // Append the token to the current argument list.
2320
1.09M
    MA.push_back(getTok());
2321
1.09M
    if (AddTokens)
2322
0
      AddTokens--;
2323
1.09M
    Lex();
2324
1.09M
  }
2325
2326
1.08M
  if (ParenLevel != 0) {
2327
    // return TokError("unbalanced parentheses in macro argument");
2328
8.35k
    KsError = KS_ERR_ASM_MACRO_PAREN;
2329
8.35k
    return true;
2330
8.35k
  }
2331
1.07M
  return false;
2332
1.08M
}
2333
2334
// Parse the macro instantiation arguments.
2335
bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2336
                                    MCAsmMacroArguments &A)
2337
360k
{
2338
360k
  const unsigned NParameters = M ? M->Parameters.size() : 0;
2339
360k
  bool NamedParametersFound = false;
2340
360k
  SmallVector<SMLoc, 4> FALocs;
2341
2342
360k
  A.resize(NParameters);
2343
360k
  FALocs.resize(NParameters);
2344
2345
  // Parse two kinds of macro invocations:
2346
  // - macros defined without any parameters accept an arbitrary number of them
2347
  // - macros defined with parameters accept at most that many of them
2348
360k
  bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2349
1.08M
  for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2350
1.07M
       ++Parameter) {
2351
    //SMLoc IDLoc = Lexer.getLoc();
2352
1.07M
    MCAsmMacroParameter FA;
2353
2354
1.07M
    if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2355
15.2k
      if (parseIdentifier(FA.Name)) {
2356
        //Error(IDLoc, "invalid argument identifier for formal argument");
2357
0
        eatToEndOfStatement();
2358
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2359
0
        return true;
2360
0
      }
2361
2362
15.2k
      if (!Lexer.is(AsmToken::Equal)) {
2363
        //TokError("expected '=' after formal parameter identifier");
2364
0
        eatToEndOfStatement();
2365
0
        KsError = KS_ERR_ASM_MACRO_EQU;
2366
0
        return true;
2367
0
      }
2368
15.2k
      Lex();
2369
2370
15.2k
      NamedParametersFound = true;
2371
15.2k
    }
2372
2373
1.07M
    if (NamedParametersFound && FA.Name.empty()) {
2374
      //Error(IDLoc, "cannot mix positional and keyword arguments");
2375
2.02k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2376
2.02k
      eatToEndOfStatement();
2377
2.02k
      return true;
2378
2.02k
    }
2379
2380
1.07M
    bool Vararg = HasVararg && Parameter == (NParameters - 1);
2381
1.07M
    if (parseMacroArgument(FA.Value, Vararg)) {
2382
8.32k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2383
8.32k
      return true;
2384
8.32k
    }
2385
2386
1.06M
    unsigned PI = Parameter;
2387
1.06M
    if (!FA.Name.empty()) {
2388
15.2k
      unsigned FAI = 0;
2389
42.7k
      for (FAI = 0; FAI < NParameters; ++FAI)
2390
36.3k
        if (M->Parameters[FAI].Name == FA.Name)
2391
8.83k
          break;
2392
2393
15.2k
      if (FAI >= NParameters) {
2394
        //assert(M && "expected macro to be defined");
2395
        //Error(IDLoc,
2396
        //      "parameter named '" + FA.Name + "' does not exist for macro '" +
2397
        //      M->Name + "'");
2398
6.41k
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2399
6.41k
        return true;
2400
6.41k
      }
2401
8.83k
      PI = FAI;
2402
8.83k
    }
2403
2404
1.06M
    if (!FA.Value.empty()) {
2405
183k
      if (A.size() <= PI)
2406
163k
        A.resize(PI + 1);
2407
183k
      A[PI] = FA.Value;
2408
2409
183k
      if (FALocs.size() <= PI)
2410
163k
        FALocs.resize(PI + 1);
2411
2412
183k
      FALocs[PI] = Lexer.getLoc();
2413
183k
    }
2414
2415
    // At the end of the statement, fill in remaining arguments that have
2416
    // default values. If there aren't any, then the next argument is
2417
    // required but missing
2418
1.06M
    if (Lexer.is(AsmToken::EndOfStatement)) {
2419
342k
      bool Failure = false;
2420
442k
      for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2421
100k
        if (A[FAI].empty()) {
2422
92.3k
          if (M->Parameters[FAI].Required) {
2423
            //Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2424
            //      "missing value for required parameter "
2425
            //      "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2426
0
            KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2427
0
            Failure = true;
2428
0
          }
2429
2430
92.3k
          if (!M->Parameters[FAI].Value.empty())
2431
12.9k
            A[FAI] = M->Parameters[FAI].Value;
2432
92.3k
        }
2433
100k
      }
2434
342k
      return Failure;
2435
342k
    }
2436
2437
720k
    if (Lexer.is(AsmToken::Comma))
2438
720k
      Lex();
2439
720k
  }
2440
2441
  // return TokError("too many positional arguments");
2442
1.82k
  KsError = KS_ERR_ASM_MACRO_ARGS;
2443
1.82k
  return true;
2444
360k
}
2445
2446
8.18M
const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
2447
8.18M
  StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2448
8.18M
  return (I == MacroMap.end()) ? nullptr : &I->getValue();
2449
8.18M
}
2450
2451
5.72k
void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2452
5.72k
  MacroMap.insert(std::make_pair(Name, std::move(Macro)));
2453
5.72k
}
2454
2455
0
void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
2456
2457
bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc)
2458
322k
{
2459
  // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2460
  // this, although we should protect against infinite loops.
2461
322k
  if (ActiveMacros.size() == 20) {
2462
    // return TokError("macros cannot be nested more than 20 levels deep");
2463
14.6k
    KsError = KS_ERR_ASM_MACRO_LEVELS_EXCEED;
2464
14.6k
    return true;
2465
14.6k
  }
2466
2467
307k
  MCAsmMacroArguments A;
2468
307k
  if (parseMacroArguments(M, A)) {
2469
8.37k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2470
8.37k
    return true;
2471
8.37k
  }
2472
2473
  // Macro instantiation is lexical, unfortunately. We construct a new buffer
2474
  // to hold the macro body with substitutions.
2475
299k
  SmallString<256> Buf;
2476
299k
  StringRef Body = M->Body;
2477
299k
  raw_svector_ostream OS(Buf);
2478
2479
299k
  if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc())) {
2480
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2481
0
    return true;
2482
0
  }
2483
2484
  // We include the .endmacro in the buffer as our cue to exit the macro
2485
  // instantiation.
2486
299k
  OS << ".endmacro\n";
2487
2488
299k
  std::unique_ptr<MemoryBuffer> Instantiation =
2489
299k
      MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2490
2491
  // Create the macro instantiation object and add to the current macro
2492
  // instantiation stack.
2493
299k
  MacroInstantiation *MI = new MacroInstantiation(
2494
299k
      NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2495
299k
  ActiveMacros.push_back(MI);
2496
2497
299k
  ++NumOfMacroInstantiations;
2498
2499
  // Jump to the macro instantiation and prime the lexer.
2500
299k
  CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2501
299k
  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2502
299k
  Lex();
2503
2504
299k
  return false;
2505
299k
}
2506
2507
324k
void AsmParser::handleMacroExit() {
2508
  // Jump to the EndOfStatement we should return to, and consume it.
2509
324k
  jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2510
324k
  Lex();
2511
2512
  // Pop the instantiation entry.
2513
324k
  delete ActiveMacros.back();
2514
324k
  ActiveMacros.pop_back();
2515
324k
}
2516
2517
bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2518
1.57M
                                bool NoDeadStrip) {
2519
1.57M
  MCSymbol *Sym;
2520
1.57M
  const MCExpr *Value;
2521
1.57M
  if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2522
1.57M
                                               Value)) {
2523
750k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2524
750k
    return true;
2525
750k
  }
2526
2527
824k
  if (!Sym) {
2528
    // In the case where we parse an expression starting with a '.', we will
2529
    // not generate an error, nor will we create a symbol.  In this case we
2530
    // should just return out.
2531
299k
    return false;
2532
299k
  }
2533
2534
  // Do the assignment.
2535
524k
  if (!Out.EmitAssignment(Sym, Value)) {
2536
2.11k
    KsError = KS_ERR_ASM_DIRECTIVE_ID;
2537
2.11k
    return true;
2538
2.11k
  }
2539
522k
  if (NoDeadStrip)
2540
435
    Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2541
2542
522k
  return false;
2543
524k
}
2544
2545
/// parseIdentifier:
2546
///   ::= identifier
2547
///   ::= string
2548
bool AsmParser::parseIdentifier(StringRef &Res)
2549
12.2M
{
2550
  // The assembler has relaxed rules for accepting identifiers, in particular we
2551
  // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2552
  // separate tokens. At this level, we have already lexed so we cannot (currently)
2553
  // handle this as a context dependent token, instead we detect adjacent tokens
2554
  // and return the combined identifier.
2555
12.2M
  if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2556
287k
    SMLoc PrefixLoc = getLexer().getLoc();
2557
2558
    // Consume the prefix character, and check for a following identifier.
2559
287k
    Lex();
2560
287k
    if (Lexer.isNot(AsmToken::Identifier)) {
2561
251k
      KsError = KS_ERR_ASM_MACRO_INVALID;
2562
251k
      return true;
2563
251k
    }
2564
2565
    // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2566
35.7k
    if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer()) {
2567
3.95k
      KsError = KS_ERR_ASM_MACRO_INVALID;
2568
3.95k
      return true;
2569
3.95k
    }
2570
2571
    // Construct the joined identifier and consume the token.
2572
31.7k
    Res =
2573
31.7k
        StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2574
31.7k
    Lex();
2575
31.7k
    return false;
2576
35.7k
  }
2577
2578
11.9M
  if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String)) {
2579
61.7k
    KsError = KS_ERR_ASM_MACRO_INVALID;
2580
61.7k
    return true;
2581
61.7k
  }
2582
2583
11.9M
  Res = getTok().getIdentifier();
2584
2585
11.9M
  Lex(); // Consume the identifier token.
2586
2587
11.9M
  return false;
2588
11.9M
}
2589
2590
/// parseDirectiveSet:
2591
///   ::= .equ identifier ',' expression
2592
///   ::= .equiv identifier ',' expression
2593
///   ::= .set identifier ',' expression
2594
9.54k
bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2595
9.54k
  StringRef Name;
2596
2597
9.54k
  if (parseIdentifier(Name)) {
2598
    // return TokError("expected identifier after '" + Twine(IDVal) + "'");
2599
3.22k
    KsError = KS_ERR_ASM_DIRECTIVE_ID;
2600
3.22k
    return true;
2601
3.22k
  }
2602
2603
6.32k
  if (getLexer().isNot(AsmToken::Comma)) {
2604
    // return TokError("unexpected token in '" + Twine(IDVal) + "'");
2605
3.64k
    KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
2606
3.64k
    return true;
2607
3.64k
  }
2608
2.67k
  Lex();
2609
2610
2.67k
  return parseAssignment(Name, allow_redef, true);
2611
6.32k
}
2612
2613
bool AsmParser::parseEscapedString(std::string &Data)
2614
25.6k
{
2615
25.6k
  if (!getLexer().is(AsmToken::String)) {
2616
0
      KsError = KS_ERR_ASM_ESC_STR;
2617
0
      return true;
2618
0
  }
2619
2620
25.6k
  Data = "";
2621
25.6k
  bool valid;
2622
25.6k
  StringRef Str = getTok().getStringContents(valid);
2623
25.6k
  if (!valid) {
2624
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2625
0
      return true;
2626
0
  }
2627
2628
711k
  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2629
686k
    if (Str[i] != '\\') {
2630
607k
      Data += Str[i];
2631
607k
      continue;
2632
607k
    }
2633
2634
    // Recognize escaped characters. Note that this escape semantics currently
2635
    // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2636
79.1k
    ++i;
2637
79.1k
    if (i == e) {
2638
      // return TokError("unexpected backslash at end of string");
2639
0
      KsError = KS_ERR_ASM_ESC_BACKSLASH;
2640
0
      return true;
2641
0
    }
2642
2643
    // Recognize octal sequences.
2644
79.1k
    if ((unsigned)(Str[i] - '0') <= 7) {
2645
      // Consume up to three octal characters.
2646
31.8k
      unsigned Value = Str[i] - '0';
2647
2648
31.8k
      if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2649
17.5k
        ++i;
2650
17.5k
        Value = Value * 8 + (Str[i] - '0');
2651
2652
17.5k
        if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2653
6.28k
          ++i;
2654
6.28k
          Value = Value * 8 + (Str[i] - '0');
2655
6.28k
        }
2656
17.5k
      }
2657
2658
31.8k
      if (Value > 255) {
2659
        // return TokError("invalid octal escape sequence (out of range)");
2660
262
        KsError = KS_ERR_ASM_ESC_BACKSLASH;
2661
262
        return true;
2662
262
      }
2663
2664
31.5k
      Data += (unsigned char)Value;
2665
31.5k
      continue;
2666
31.8k
    }
2667
2668
    // Otherwise recognize individual escapes.
2669
47.3k
    switch (Str[i]) {
2670
1.09k
    default:
2671
      // Just reject invalid escape sequences for now.
2672
      // return TokError("invalid escape sequence (unrecognized character)");
2673
1.09k
      KsError = KS_ERR_ASM_ESC_SEQUENCE;
2674
1.09k
      return true;
2675
2676
6.12k
    case 'b': Data += '\b'; break;
2677
4.40k
    case 'f': Data += '\f'; break;
2678
1.97k
    case 'n': Data += '\n'; break;
2679
4.76k
    case 'r': Data += '\r'; break;
2680
7.57k
    case 't': Data += '\t'; break;
2681
6.04k
    case '"': Data += '"'; break;
2682
15.3k
    case '\\': Data += '\\'; break;
2683
47.3k
    }
2684
47.3k
  }
2685
2686
24.2k
  return false;
2687
25.6k
}
2688
2689
/// parseDirectiveAscii:
2690
///   ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2691
bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated)
2692
13.1k
{
2693
13.1k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2694
9.65k
    checkForValidSection();
2695
2696
13.5k
    for (;;) {
2697
13.5k
      if (getLexer().isNot(AsmToken::String)) {
2698
        // return TokError("expected string in '" + Twine(IDVal) + "' directive");
2699
5.18k
        KsError = KS_ERR_ASM_DIRECTIVE_STR;
2700
5.18k
        return true;
2701
5.18k
      }
2702
2703
8.34k
      std::string Data;
2704
8.34k
      if (parseEscapedString(Data)) {
2705
117
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2706
117
        return true;
2707
117
      }
2708
2709
8.23k
      getStreamer().EmitBytes(Data);
2710
8.23k
      if (ZeroTerminated)
2711
8.13k
        getStreamer().EmitBytes(StringRef("\0", 1));
2712
2713
8.23k
      Lex();
2714
2715
8.23k
      if (getLexer().is(AsmToken::EndOfStatement))
2716
1.25k
        break;
2717
2718
6.97k
      if (getLexer().isNot(AsmToken::Comma)) {
2719
        // return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
2720
3.09k
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
2721
3.09k
        return true;
2722
3.09k
      }
2723
3.88k
      Lex();
2724
3.88k
    }
2725
9.65k
  }
2726
2727
4.79k
  Lex();
2728
4.79k
  return false;
2729
13.1k
}
2730
2731
/// parseDirectiveReloc
2732
///  ::= .reloc expression , identifier [ , expression ]
2733
bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc)
2734
24.1k
{
2735
24.1k
  const MCExpr *Offset;
2736
24.1k
  const MCExpr *Expr = nullptr;
2737
2738
  //SMLoc OffsetLoc = Lexer.getTok().getLoc();
2739
24.1k
  if (parseExpression(Offset)) {
2740
468
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2741
468
    return true;
2742
468
  }
2743
2744
  // We can only deal with constant expressions at the moment.
2745
23.6k
  int64_t OffsetValue;
2746
23.6k
  if (!Offset->evaluateAsAbsolute(OffsetValue)) {
2747
    //return Error(OffsetLoc, "expression is not a constant value");
2748
2.25k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2749
2.25k
    return true;
2750
2.25k
  }
2751
2752
21.4k
  if (OffsetValue < 0) {
2753
    //return Error(OffsetLoc, "expression is negative");
2754
1.59k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2755
1.59k
    return true;
2756
1.59k
  }
2757
2758
19.8k
  if (Lexer.isNot(AsmToken::Comma)) {
2759
    // return TokError("expected comma");
2760
3.25k
    KsError = KS_ERR_ASM_DIRECTIVE_COMMA;
2761
3.25k
    return true;
2762
3.25k
  }
2763
16.5k
  Lexer.Lex();
2764
2765
16.5k
  if (Lexer.isNot(AsmToken::Identifier)) {
2766
    // return TokError("expected relocation name");
2767
4.10k
    KsError = KS_ERR_ASM_DIRECTIVE_RELOC_NAME;
2768
4.10k
    return true;
2769
4.10k
  }
2770
  //SMLoc NameLoc = Lexer.getTok().getLoc();
2771
12.4k
  StringRef Name = Lexer.getTok().getIdentifier();
2772
12.4k
  Lexer.Lex();
2773
2774
12.4k
  if (Lexer.is(AsmToken::Comma)) {
2775
9.23k
    Lexer.Lex();
2776
    //SMLoc ExprLoc = Lexer.getLoc();
2777
9.23k
    if (parseExpression(Expr)) {
2778
422
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2779
422
      return true;
2780
422
    }
2781
2782
8.81k
    MCValue Value;
2783
8.81k
    if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr)) {
2784
      //return Error(ExprLoc, "expression must be relocatable");
2785
6.80k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2786
6.80k
      return true;
2787
6.80k
    }
2788
8.81k
  }
2789
2790
5.24k
  if (Lexer.isNot(AsmToken::EndOfStatement)) {
2791
    // return TokError("unexpected token in .reloc directive");
2792
533
    KsError = KS_ERR_ASM_DIRECTIVE_RELOC_TOKEN;
2793
533
    return true;
2794
533
  }
2795
2796
4.70k
  if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc)) {
2797
    //return Error(NameLoc, "unknown relocation name");
2798
4.70k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2799
4.70k
    return true;
2800
4.70k
  }
2801
2802
0
  return false;
2803
4.70k
}
2804
2805
/// parseDirectiveValue
2806
///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
2807
bool AsmParser::parseDirectiveValue(unsigned Size, unsigned int &KsError)
2808
263k
{
2809
263k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2810
56.0k
    checkForValidSection();
2811
2812
166k
    for (;;) {
2813
166k
      const MCExpr *Value;
2814
166k
      SMLoc ExprLoc = getLexer().getLoc();
2815
166k
      if (parseExpression(Value)) {
2816
3.61k
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2817
3.61k
        return true;
2818
3.61k
      }
2819
2820
      // Special case constant expressions to match code generator.
2821
162k
      if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2822
17.0k
        assert(Size <= 8 && "Invalid size");
2823
17.0k
        uint64_t IntValue = MCE->getValue();
2824
17.0k
        if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) {
2825
            // return Error(ExprLoc, "literal value out of range for directive");
2826
593
            KsError = KS_ERR_ASM_DIRECTIVE_VALUE_RANGE;
2827
593
            return true;
2828
593
        }
2829
16.4k
        bool Error;
2830
16.4k
        getStreamer().EmitIntValue(IntValue, Size, Error);
2831
16.4k
        if (Error) {
2832
0
            KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
2833
0
            return true;
2834
0
        }
2835
16.4k
      } else
2836
145k
        getStreamer().EmitValue(Value, Size, ExprLoc);
2837
2838
161k
      if (getLexer().is(AsmToken::EndOfStatement))
2839
50.6k
        break;
2840
2841
      // FIXME: Improve diagnostic.
2842
111k
      if (getLexer().isNot(AsmToken::Comma)) {
2843
        // return TokError("unexpected token in directive");
2844
1.19k
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
2845
1.19k
        return true;
2846
1.19k
      }
2847
110k
      Lex();
2848
110k
    }
2849
56.0k
  }
2850
2851
258k
  Lex();
2852
258k
  return false;
2853
263k
}
2854
2855
/// ParseDirectiveOctaValue
2856
///  ::= .octa [ hexconstant (, hexconstant)* ]
2857
bool AsmParser::parseDirectiveOctaValue(unsigned int &KsError)
2858
2.71k
{
2859
2.71k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2860
686
    checkForValidSection();
2861
2862
13.7k
    for (;;) {
2863
13.7k
      if (Lexer.getKind() == AsmToken::Error) {
2864
20
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2865
20
        return true;
2866
20
      }
2867
13.7k
      if (Lexer.getKind() != AsmToken::Integer &&
2868
13.7k
          Lexer.getKind() != AsmToken::BigNum) {
2869
        // return TokError("unknown token in expression");
2870
109
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
2871
109
        return true;
2872
109
      }
2873
2874
      // SMLoc ExprLoc = getLexer().getLoc();
2875
13.6k
      bool valid;
2876
13.6k
      APInt IntValue = getTok().getAPIntVal(valid);
2877
13.6k
      if (!valid) {
2878
0
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2879
0
          return true;
2880
0
      }
2881
13.6k
      Lex();
2882
2883
13.6k
      uint64_t hi, lo;
2884
13.6k
      if (IntValue.isIntN(64)) {
2885
8.63k
        hi = 0;
2886
8.63k
        lo = IntValue.getZExtValue();
2887
8.63k
      } else if (IntValue.isIntN(128)) {
2888
        // It might actually have more than 128 bits, but the top ones are zero.
2889
5.01k
        hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2890
5.01k
        lo = IntValue.getLoBits(64).getZExtValue();
2891
5.01k
      } else {
2892
        // return Error(ExprLoc, "literal value out of range for directive");
2893
22
        KsError = KS_ERR_ASM_DIRECTIVE_VALUE_RANGE;
2894
22
        return true;
2895
22
      }
2896
2897
13.6k
      bool Error;
2898
13.6k
      if (MAI.isLittleEndian()) {
2899
9.07k
        getStreamer().EmitIntValue(lo, 8, Error);
2900
9.07k
        getStreamer().EmitIntValue(hi, 8, Error);
2901
9.07k
      } else {
2902
4.57k
        getStreamer().EmitIntValue(hi, 8, Error);
2903
4.57k
        getStreamer().EmitIntValue(lo, 8, Error);
2904
4.57k
      }
2905
2906
13.6k
      if (getLexer().is(AsmToken::EndOfStatement))
2907
429
        break;
2908
2909
      // FIXME: Improve diagnostic.
2910
13.2k
      if (getLexer().isNot(AsmToken::Comma)) {
2911
        // return TokError("unexpected token in directive");
2912
106
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
2913
106
        return true;
2914
106
      }
2915
13.1k
      Lex();
2916
13.1k
    }
2917
686
  }
2918
2919
2.45k
  Lex();
2920
2.45k
  return false;
2921
2.71k
}
2922
2923
/// parseDirectiveRealValue
2924
///  ::= (.single | .double) [ expression (, expression)* ]
2925
bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics)
2926
18.0k
{
2927
18.0k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
2928
15.6k
    checkForValidSection();
2929
2930
65.9k
    for (;;) {
2931
      // We don't truly support arithmetic on floating point expressions, so we
2932
      // have to manually parse unary prefixes.
2933
65.9k
      bool IsNeg = false;
2934
65.9k
      if (getLexer().is(AsmToken::Minus)) {
2935
17.1k
        Lex();
2936
17.1k
        IsNeg = true;
2937
48.8k
      } else if (getLexer().is(AsmToken::Plus))
2938
12.1k
        Lex();
2939
2940
65.9k
      if (getLexer().isNot(AsmToken::Integer) &&
2941
65.9k
          getLexer().isNot(AsmToken::Real) &&
2942
65.9k
          getLexer().isNot(AsmToken::Identifier)) {
2943
        // return TokError("unexpected token in directive");
2944
1.14k
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
2945
1.14k
        return true;
2946
1.14k
      }
2947
2948
      // Convert to an APFloat.
2949
64.8k
      APFloat Value(Semantics);
2950
64.8k
      StringRef IDVal = getTok().getString();
2951
64.8k
      if (getLexer().is(AsmToken::Identifier)) {
2952
19.8k
        if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2953
9.81k
          Value = APFloat::getInf(Semantics);
2954
10.0k
        else if (!IDVal.compare_lower("nan"))
2955
4.07k
          Value = APFloat::getNaN(Semantics, false, ~0);
2956
5.93k
        else {
2957
          // return TokError("invalid floating point literal");
2958
5.93k
          KsError = KS_ERR_ASM_DIRECTIVE_FPOINT;
2959
5.93k
          return true;
2960
5.93k
        }
2961
45.0k
      } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2962
45.0k
                 APFloat::opInvalidOp) {
2963
        // return TokError("invalid floating point literal");
2964
38
        KsError = KS_ERR_ASM_DIRECTIVE_FPOINT;
2965
38
        return true;
2966
38
      }
2967
58.8k
      if (IsNeg)
2968
15.5k
        Value.changeSign();
2969
2970
      // Consume the numeric token.
2971
58.8k
      Lex();
2972
2973
      // Emit the value as an integer.
2974
58.8k
      APInt AsInt = Value.bitcastToAPInt();
2975
58.8k
      bool Error;
2976
58.8k
      getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2977
58.8k
                                 AsInt.getBitWidth() / 8, Error);
2978
58.8k
      if (Error) {
2979
0
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
2980
0
          return true;
2981
0
      }
2982
2983
58.8k
      if (getLexer().is(AsmToken::EndOfStatement))
2984
2.17k
        break;
2985
2986
56.6k
      if (getLexer().isNot(AsmToken::Comma)) {
2987
        // return TokError("unexpected token in directive");
2988
6.34k
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
2989
6.34k
        return true;
2990
6.34k
      }
2991
50.3k
      Lex();
2992
50.3k
    }
2993
15.6k
  }
2994
2995
4.62k
  Lex();
2996
4.62k
  return false;
2997
18.0k
}
2998
2999
/// parseDirectiveZero
3000
///  ::= .zero expression
3001
bool AsmParser::parseDirectiveZero()
3002
48.2k
{
3003
48.2k
  checkForValidSection();
3004
3005
48.2k
  int64_t NumBytes;
3006
48.2k
  if (parseAbsoluteExpression(NumBytes)) {
3007
2.59k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3008
2.59k
    return true;
3009
2.59k
  }
3010
3011
45.6k
  int64_t Val = 0;
3012
45.6k
  if (getLexer().is(AsmToken::Comma)) {
3013
41.0k
    Lex();
3014
41.0k
    if (parseAbsoluteExpression(Val)) {
3015
2.11k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3016
2.11k
      return true;
3017
2.11k
    }
3018
41.0k
  }
3019
3020
43.4k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3021
    // return TokError("unexpected token in '.zero' directive");
3022
2.72k
    KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
3023
2.72k
    return true;
3024
2.72k
  }
3025
3026
40.7k
  Lex();
3027
3028
40.7k
  getStreamer().EmitFill(NumBytes, Val);
3029
3030
40.7k
  return false;
3031
43.4k
}
3032
3033
/// parseDirectiveFill
3034
///  ::= .fill expression [ , expression [ , expression ] ]
3035
bool AsmParser::parseDirectiveFill()
3036
126k
{
3037
126k
  checkForValidSection();
3038
3039
126k
  SMLoc RepeatLoc = getLexer().getLoc();
3040
126k
  int64_t NumValues;
3041
126k
  if (parseAbsoluteExpression(NumValues)) {
3042
6.23k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3043
6.23k
    return true;
3044
6.23k
  }
3045
3046
120k
  if (NumValues < 0) {
3047
101k
    Warning(RepeatLoc,
3048
101k
            "'.fill' directive with negative repeat count has no effect");
3049
101k
    NumValues = 0;
3050
101k
  }
3051
3052
120k
  int64_t FillSize = 1;
3053
120k
  int64_t FillExpr = 0;
3054
3055
120k
  SMLoc SizeLoc, ExprLoc;
3056
120k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3057
113k
    if (getLexer().isNot(AsmToken::Comma)) {
3058
      // return TokError("unexpected token in '.fill' directive");
3059
4.89k
      KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
3060
4.89k
      return true;
3061
4.89k
    }
3062
108k
    Lex();
3063
3064
108k
    SizeLoc = getLexer().getLoc();
3065
108k
    if (parseAbsoluteExpression(FillSize)) {
3066
30.1k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3067
30.1k
      return true;
3068
30.1k
    }
3069
3070
78.1k
    if (getLexer().isNot(AsmToken::EndOfStatement)) {
3071
56.6k
      if (getLexer().isNot(AsmToken::Comma)) {
3072
        // return TokError("unexpected token in '.fill' directive");
3073
2.90k
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
3074
2.90k
        return true;
3075
2.90k
      }
3076
53.7k
      Lex();
3077
3078
53.7k
      ExprLoc = getLexer().getLoc();
3079
53.7k
      if (parseAbsoluteExpression(FillExpr)) {
3080
40.6k
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3081
40.6k
        return true;
3082
40.6k
      }
3083
3084
13.0k
      if (getLexer().isNot(AsmToken::EndOfStatement)) {
3085
        // return TokError("unexpected token in '.fill' directive");
3086
3.50k
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
3087
3.50k
        return true;
3088
3.50k
      }
3089
3090
9.57k
      Lex();
3091
9.57k
    }
3092
78.1k
  }
3093
3094
38.4k
  if (FillSize < 0) {
3095
9.86k
    Warning(SizeLoc, "'.fill' directive with negative size has no effect");
3096
9.86k
    NumValues = 0;
3097
9.86k
  }
3098
38.4k
  if (FillSize > 8) {
3099
19.0k
    Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3100
19.0k
    FillSize = 8;
3101
19.0k
  }
3102
3103
38.4k
  if (!isUInt<32>(FillExpr) && FillSize > 4)
3104
4.57k
    Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3105
3106
38.4k
  if (NumValues > 0) {
3107
8.88k
    int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
3108
8.88k
    FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
3109
8.88k
    bool Error;
3110
422M
    for (uint64_t i = 0, e = NumValues; i != e; ++i) {
3111
422M
      getStreamer().EmitIntValue(FillExpr, NonZeroFillSize, Error);
3112
422M
      if (Error) {
3113
1.28k
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3114
1.28k
          return true;
3115
1.28k
      }
3116
422M
      if (NonZeroFillSize < FillSize) {
3117
105M
        getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize, Error);
3118
105M
        if (Error) {
3119
0
            KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3120
0
            return true;
3121
0
        }
3122
105M
      }
3123
422M
    }
3124
8.88k
  }
3125
3126
37.2k
  return false;
3127
38.4k
}
3128
3129
/// parseDirectiveOrg
3130
///  ::= .org expression [ , expression ]
3131
36.3k
bool AsmParser::parseDirectiveOrg() {
3132
36.3k
  checkForValidSection();
3133
3134
36.3k
  const MCExpr *Offset;
3135
36.3k
  if (parseExpression(Offset)) {
3136
3.28k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3137
3.28k
    return true;
3138
3.28k
  }
3139
3140
  // Parse optional fill expression.
3141
33.1k
  int64_t FillExpr = 0;
3142
33.1k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3143
2.65k
    if (getLexer().isNot(AsmToken::Comma)) {
3144
      // return TokError("unexpected token in '.org' directive");
3145
1.81k
      KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
3146
1.81k
      return true;
3147
1.81k
    }
3148
836
    Lex();
3149
3150
836
    if (parseAbsoluteExpression(FillExpr)) {
3151
271
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3152
271
      return true;
3153
271
    }
3154
3155
565
    if (getLexer().isNot(AsmToken::EndOfStatement)) {
3156
      // return TokError("unexpected token in '.org' directive");
3157
171
      KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
3158
171
      return true;
3159
171
    }
3160
565
  }
3161
3162
30.8k
  Lex();
3163
30.8k
  getStreamer().emitValueToOffset(Offset, FillExpr);
3164
30.8k
  return false;
3165
33.1k
}
3166
3167
/// parseDirectiveAlign
3168
///  ::= {.align, ...} expression [ , expression [ , expression ]]
3169
bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize)
3170
140k
{
3171
140k
  checkForValidSection();
3172
3173
  //SMLoc AlignmentLoc = getLexer().getLoc();
3174
140k
  int64_t Alignment;
3175
140k
  if (parseAbsoluteExpression(Alignment)) {
3176
3.67k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3177
3.67k
    return true;
3178
3.67k
  }
3179
3180
137k
  SMLoc MaxBytesLoc;
3181
137k
  bool HasFillExpr = false;
3182
137k
  int64_t FillExpr = 0;
3183
137k
  int64_t MaxBytesToFill = 0;
3184
137k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3185
111k
    if (getLexer().isNot(AsmToken::Comma)) {
3186
      // return TokError("unexpected token in directive");
3187
5.48k
      KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
3188
5.48k
      return true;
3189
5.48k
    }
3190
105k
    Lex();
3191
3192
    // The fill expression can be omitted while specifying a maximum number of
3193
    // alignment bytes, e.g:
3194
    //  .align 3,,4
3195
105k
    if (getLexer().isNot(AsmToken::Comma)) {
3196
100k
      HasFillExpr = true;
3197
100k
      if (parseAbsoluteExpression(FillExpr)) {
3198
14.7k
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3199
14.7k
        return true;
3200
14.7k
      }
3201
100k
    }
3202
3203
90.9k
    if (getLexer().isNot(AsmToken::EndOfStatement)) {
3204
66.9k
      if (getLexer().isNot(AsmToken::Comma)) {
3205
        // return TokError("unexpected token in directive");
3206
3.67k
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
3207
3.67k
        return true;
3208
3.67k
      }
3209
63.2k
      Lex();
3210
3211
63.2k
      MaxBytesLoc = getLexer().getLoc();
3212
63.2k
      if (parseAbsoluteExpression(MaxBytesToFill)) {
3213
16.0k
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3214
16.0k
        return true;
3215
16.0k
      }
3216
3217
47.2k
      if (getLexer().isNot(AsmToken::EndOfStatement)) {
3218
        // return TokError("unexpected token in directive");
3219
4.85k
        KsError = KS_ERR_ASM_DIRECTIVE_TOKEN;
3220
4.85k
        return true;
3221
4.85k
      }
3222
47.2k
    }
3223
90.9k
  }
3224
3225
92.4k
  Lex();
3226
3227
92.4k
  if (!HasFillExpr)
3228
30.6k
    FillExpr = 0;
3229
3230
  // Compute alignment in bytes.
3231
92.4k
  if (IsPow2) {
3232
    // FIXME: Diagnose overflow.
3233
72.2k
    if (Alignment >= 32) {
3234
      //Error(AlignmentLoc, "invalid alignment value");
3235
17.0k
      Alignment = 31;
3236
17.0k
    }
3237
3238
72.2k
    Alignment = 1ULL << Alignment;
3239
72.2k
  } else {
3240
    // Reject alignments that aren't either a power of two or zero,
3241
    // for gas compatibility. Alignment of zero is silently rounded
3242
    // up to one.
3243
20.1k
    if (Alignment == 0)
3244
7.71k
      Alignment = 1;
3245
20.1k
    if (!isPowerOf2_64(Alignment)) {
3246
      //Error(AlignmentLoc, "alignment must be a power of 2");
3247
3.13k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3248
3.13k
      return true;
3249
3.13k
    }
3250
20.1k
  }
3251
3252
  // Diagnose non-sensical max bytes to align.
3253
89.2k
  if (MaxBytesLoc.isValid()) {
3254
42.2k
    if (MaxBytesToFill < 1) {
3255
      //Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
3256
      //                   "many bytes, ignoring maximum bytes expression");
3257
3.65k
      MaxBytesToFill = 0;
3258
3.65k
    }
3259
3260
42.2k
    if (MaxBytesToFill >= Alignment) {
3261
33.7k
      Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3262
33.7k
                           "has no effect");
3263
33.7k
      MaxBytesToFill = 0;
3264
33.7k
    }
3265
42.2k
  }
3266
3267
  // Check whether we should use optimal code alignment for this .align
3268
  // directive.
3269
89.2k
  const MCSection *Section = getStreamer().getCurrentSection().first;
3270
89.2k
  assert(Section && "must have section to emit alignment");
3271
89.2k
  bool UseCodeAlign = Section->UseCodeAlign();
3272
89.2k
  if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3273
89.2k
      ValueSize == 1 && UseCodeAlign) {
3274
33.6k
    getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
3275
55.5k
  } else {
3276
    // FIXME: Target specific behavior about how the "extra" bytes are filled.
3277
55.5k
    getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3278
55.5k
                                       MaxBytesToFill);
3279
55.5k
  }
3280
3281
89.2k
  return false;
3282
89.2k
}
3283
3284
/// parseDirectiveFile
3285
/// ::= .file [number] filename
3286
/// ::= .file number directory filename
3287
bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc)
3288
26.1k
{
3289
  // FIXME: I'm not sure what this is.
3290
26.1k
  int64_t FileNumber = -1;
3291
  //SMLoc FileNumberLoc = getLexer().getLoc();
3292
26.1k
  if (getLexer().is(AsmToken::Integer)) {
3293
7.76k
    bool valid;
3294
7.76k
    FileNumber = getTok().getIntVal(valid);
3295
7.76k
    if (!valid) {
3296
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3297
0
        return true;
3298
0
    }
3299
7.76k
    Lex();
3300
3301
7.76k
    if (FileNumber < 1) {
3302
      //return TokError("file number less than one");
3303
1.42k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3304
1.42k
      return true;
3305
1.42k
    }
3306
7.76k
  }
3307
3308
24.7k
  if (getLexer().isNot(AsmToken::String)) {
3309
    //return TokError("unexpected token in '.file' directive");
3310
8.46k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3311
8.46k
    return true;
3312
8.46k
  }
3313
3314
  // Usually the directory and filename together, otherwise just the directory.
3315
  // Allow the strings to have escaped octal character sequence.
3316
16.2k
  std::string Path = getTok().getString();
3317
16.2k
  if (parseEscapedString(Path))
3318
1.10k
    return true;
3319
15.1k
  Lex();
3320
3321
15.1k
  StringRef Directory;
3322
15.1k
  StringRef Filename;
3323
15.1k
  std::string FilenameData;
3324
15.1k
  if (getLexer().is(AsmToken::String)) {
3325
431
    if (FileNumber == -1)
3326
      //return TokError("explicit path specified, but no file number");
3327
19
      return true;
3328
412
    if (parseEscapedString(FilenameData))
3329
72
      return true;
3330
340
    Filename = FilenameData;
3331
340
    Directory = Path;
3332
340
    Lex();
3333
14.7k
  } else {
3334
14.7k
    Filename = Path;
3335
14.7k
  }
3336
3337
15.0k
  if (getLexer().isNot(AsmToken::EndOfStatement))
3338
    //return TokError("unexpected token in '.file' directive");
3339
520
    return true;
3340
3341
14.5k
  if (FileNumber == -1)
3342
14.2k
    getStreamer().EmitFileDirective(Filename);
3343
307
  else {
3344
307
    if (getContext().getGenDwarfForAssembly())
3345
      //Error(DirectiveLoc,
3346
      //      "input can't have .file dwarf directives when -g is "
3347
      //      "used to generate dwarf debug info for assembly code");
3348
0
      return true;
3349
3350
307
    if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
3351
307
        0)
3352
      //Error(FileNumberLoc, "file number already allocated");
3353
307
      return true;
3354
307
  }
3355
3356
14.2k
  return false;
3357
14.5k
}
3358
3359
/// parseDirectiveLine
3360
/// ::= .line [number]
3361
bool AsmParser::parseDirectiveLine()
3362
51.4k
{
3363
51.4k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3364
3.14k
    if (getLexer().isNot(AsmToken::Integer)) {
3365
      //return TokError("unexpected token in '.line' directive");
3366
2.00k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3367
2.00k
      return true;
3368
2.00k
    }
3369
3370
1.14k
    bool valid;
3371
1.14k
    int64_t LineNumber = getTok().getIntVal(valid);
3372
1.14k
    if (!valid) {
3373
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3374
0
        return true;
3375
0
    }
3376
1.14k
    (void)LineNumber;
3377
1.14k
    Lex();
3378
3379
    // FIXME: Do something with the .line.
3380
1.14k
  }
3381
3382
49.4k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3383
    //return TokError("unexpected token in '.line' directive");
3384
295
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3385
295
    return true;
3386
295
  }
3387
3388
49.1k
  return false;
3389
49.4k
}
3390
3391
/// parseDirectiveLoc
3392
/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3393
///                                [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3394
/// The first number is a file number, must have been previously assigned with
3395
/// a .file directive, the second number is the line number and optionally the
3396
/// third number is a column position (zero if not specified).  The remaining
3397
/// optional items are .loc sub-directives.
3398
bool AsmParser::parseDirectiveLoc()
3399
2.79k
{
3400
2.79k
  if (getLexer().isNot(AsmToken::Integer)) {
3401
    //return TokError("unexpected token in '.loc' directive");
3402
2.39k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3403
2.39k
    return true;
3404
2.39k
  }
3405
396
  bool valid;
3406
396
  int64_t FileNumber = getTok().getIntVal(valid);
3407
396
  if (!valid) {
3408
0
      return true;
3409
0
  }
3410
396
  if (FileNumber < 1) {
3411
    //return TokError("file number less than one in '.loc' directive");
3412
20
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3413
20
    return true;
3414
20
  }
3415
376
  if (!getContext().isValidDwarfFileNumber(FileNumber)) {
3416
    //return TokError("unassigned file number in '.loc' directive");
3417
376
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3418
376
    return true;
3419
376
  }
3420
0
  Lex();
3421
3422
0
  int64_t LineNumber = 0;
3423
0
  if (getLexer().is(AsmToken::Integer)) {
3424
0
    bool valid;
3425
0
    LineNumber = getTok().getIntVal(valid);
3426
0
    if (!valid) {
3427
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3428
0
        return true;
3429
0
    }
3430
0
    if (LineNumber < 0) {
3431
      //return TokError("line number less than zero in '.loc' directive");
3432
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3433
0
      return true;
3434
0
    }
3435
0
    Lex();
3436
0
  }
3437
3438
0
  int64_t ColumnPos = 0;
3439
0
  if (getLexer().is(AsmToken::Integer)) {
3440
0
    bool valid;
3441
0
    ColumnPos = getTok().getIntVal(valid);
3442
0
    if (!valid) {
3443
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3444
0
        return true;
3445
0
    }
3446
0
    if (ColumnPos < 0) {
3447
      //return TokError("column position less than zero in '.loc' directive");
3448
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3449
0
      return true;
3450
0
    }
3451
0
    Lex();
3452
0
  }
3453
3454
0
  unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3455
0
  unsigned Isa = 0;
3456
0
  int64_t Discriminator = 0;
3457
0
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
3458
0
    for (;;) {
3459
0
      if (getLexer().is(AsmToken::EndOfStatement))
3460
0
        break;
3461
3462
0
      StringRef Name;
3463
0
      SMLoc Loc = getTok().getLoc();
3464
0
      if (parseIdentifier(Name)) {
3465
        //return TokError("unexpected token in '.loc' directive");
3466
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3467
0
        return true;
3468
0
      }
3469
3470
0
      if (Name == "basic_block")
3471
0
        Flags |= DWARF2_FLAG_BASIC_BLOCK;
3472
0
      else if (Name == "prologue_end")
3473
0
        Flags |= DWARF2_FLAG_PROLOGUE_END;
3474
0
      else if (Name == "epilogue_begin")
3475
0
        Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3476
0
      else if (Name == "is_stmt") {
3477
0
        Loc = getTok().getLoc();
3478
0
        const MCExpr *Value;
3479
0
        if (parseExpression(Value)) {
3480
0
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3481
0
          return true;
3482
0
        }
3483
        // The expression must be the constant 0 or 1.
3484
0
        if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3485
0
          int Value = MCE->getValue();
3486
0
          if (Value == 0)
3487
0
            Flags &= ~DWARF2_FLAG_IS_STMT;
3488
0
          else if (Value == 1)
3489
0
            Flags |= DWARF2_FLAG_IS_STMT;
3490
0
          else {
3491
            //return Error(Loc, "is_stmt value not 0 or 1");
3492
0
            KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3493
0
            return true;
3494
0
          }
3495
0
        } else {
3496
          //return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3497
0
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3498
0
          return true;
3499
0
        }
3500
0
      } else if (Name == "isa") {
3501
0
        Loc = getTok().getLoc();
3502
0
        const MCExpr *Value;
3503
0
        if (parseExpression(Value)) {
3504
0
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3505
0
          return true;
3506
0
        }
3507
        // The expression must be a constant greater or equal to 0.
3508
0
        if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3509
0
          int Value = MCE->getValue();
3510
0
          if (Value < 0) {
3511
            //return Error(Loc, "isa number less than zero");
3512
0
            KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3513
0
            return true;
3514
0
          }
3515
0
          Isa = Value;
3516
0
        } else {
3517
          //return Error(Loc, "isa number not a constant value");
3518
0
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3519
0
          return true;
3520
0
        }
3521
0
      } else if (Name == "discriminator") {
3522
0
        if (parseAbsoluteExpression(Discriminator)) {
3523
0
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3524
0
          return true;
3525
0
        }
3526
0
      } else {
3527
        //return Error(Loc, "unknown sub-directive in '.loc' directive");
3528
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
3529
0
        return true;
3530
0
      }
3531
3532
0
      if (getLexer().is(AsmToken::EndOfStatement))
3533
0
        break;
3534
0
    }
3535
0
  }
3536
3537
0
  getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3538
0
                                      Isa, Discriminator, StringRef());
3539
3540
0
  return false;
3541
0
}
3542
3543
/// parseDirectiveStabs
3544
/// ::= .stabs string, number, number, number
3545
bool AsmParser::parseDirectiveStabs()
3546
1
{
3547
  //return TokError("unsupported directive '.stabs'");
3548
1
  return true;
3549
1
}
3550
3551
/// parseDirectiveCVFile
3552
/// ::= .cv_file number filename
3553
bool AsmParser::parseDirectiveCVFile()
3554
0
{
3555
  //SMLoc FileNumberLoc = getLexer().getLoc();
3556
0
  if (getLexer().isNot(AsmToken::Integer))
3557
    //return TokError("expected file number in '.cv_file' directive");
3558
0
    return true;
3559
3560
0
  bool valid;
3561
0
  int64_t FileNumber = getTok().getIntVal(valid);
3562
0
  if (!valid) {
3563
0
      return true;
3564
0
  }
3565
0
  Lex();
3566
3567
0
  if (FileNumber < 1)
3568
    //return TokError("file number less than one");
3569
0
    return true;
3570
3571
0
  if (getLexer().isNot(AsmToken::String))
3572
    //return TokError("unexpected token in '.cv_file' directive");
3573
0
    return true;
3574
3575
  // Usually the directory and filename together, otherwise just the directory.
3576
  // Allow the strings to have escaped octal character sequence.
3577
0
  std::string Filename;
3578
0
  if (parseEscapedString(Filename))
3579
0
    return true;
3580
0
  Lex();
3581
3582
0
  if (getLexer().isNot(AsmToken::EndOfStatement))
3583
    //return TokError("unexpected token in '.cv_file' directive");
3584
0
    return true;
3585
3586
0
  if (getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0)
3587
    //Error(FileNumberLoc, "file number already allocated");
3588
0
    return true;
3589
3590
0
  return false;
3591
0
}
3592
3593
/// parseDirectiveCVLoc
3594
/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3595
///                                [is_stmt VALUE]
3596
/// The first number is a file number, must have been previously assigned with
3597
/// a .file directive, the second number is the line number and optionally the
3598
/// third number is a column position (zero if not specified).  The remaining
3599
/// optional items are .loc sub-directives.
3600
bool AsmParser::parseDirectiveCVLoc()
3601
0
{
3602
0
  if (getLexer().isNot(AsmToken::Integer))
3603
    //return TokError("unexpected token in '.cv_loc' directive");
3604
0
    return true;
3605
3606
0
  bool valid;
3607
0
  int64_t FunctionId = getTok().getIntVal(valid);
3608
0
  if (!valid) {
3609
0
      return true;
3610
0
  }
3611
0
  if (FunctionId < 0)
3612
    //return TokError("function id less than zero in '.cv_loc' directive");
3613
0
    return true;
3614
0
  Lex();
3615
3616
0
  int64_t FileNumber = getTok().getIntVal(valid);
3617
0
  if (!valid) {
3618
0
      return true;
3619
0
  }
3620
0
  if (FileNumber < 1)
3621
    //return TokError("file number less than one in '.cv_loc' directive");
3622
0
    return true;
3623
0
  if (!getContext().isValidCVFileNumber(FileNumber))
3624
    //return TokError("unassigned file number in '.cv_loc' directive");
3625
0
    return true;
3626
0
  Lex();
3627
3628
0
  int64_t LineNumber = 0;
3629
0
  if (getLexer().is(AsmToken::Integer)) {
3630
0
    LineNumber = getTok().getIntVal(valid);
3631
0
    if (!valid) {
3632
0
        return true;
3633
0
    }
3634
0
    if (LineNumber < 0)
3635
      //return TokError("line number less than zero in '.cv_loc' directive");
3636
0
      return true;
3637
0
    Lex();
3638
0
  }
3639
3640
0
  int64_t ColumnPos = 0;
3641
0
  if (getLexer().is(AsmToken::Integer)) {
3642
0
    ColumnPos = getTok().getIntVal(valid);
3643
0
    if (!valid) {
3644
0
        return true;
3645
0
    }
3646
0
    if (ColumnPos < 0)
3647
      //return TokError("column position less than zero in '.cv_loc' directive");
3648
0
      return true;
3649
0
    Lex();
3650
0
  }
3651
3652
0
  bool PrologueEnd = false;
3653
0
  uint64_t IsStmt = 0;
3654
0
  while (getLexer().isNot(AsmToken::EndOfStatement)) {
3655
0
    StringRef Name;
3656
0
    SMLoc Loc = getTok().getLoc();
3657
0
    if (parseIdentifier(Name))
3658
      //return TokError("unexpected token in '.cv_loc' directive");
3659
0
      return true;
3660
3661
0
    if (Name == "prologue_end")
3662
0
      PrologueEnd = true;
3663
0
    else if (Name == "is_stmt") {
3664
0
      Loc = getTok().getLoc();
3665
0
      const MCExpr *Value;
3666
0
      if (parseExpression(Value))
3667
0
        return true;
3668
      // The expression must be the constant 0 or 1.
3669
0
      IsStmt = ~0ULL;
3670
0
      if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3671
0
        IsStmt = MCE->getValue();
3672
3673
0
      if (IsStmt > 1)
3674
        //return Error(Loc, "is_stmt value not 0 or 1");
3675
0
        return true;
3676
0
    } else {
3677
      //return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3678
0
      return true;
3679
0
    }
3680
0
  }
3681
3682
0
  getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3683
0
                                   ColumnPos, PrologueEnd, IsStmt, StringRef());
3684
0
  return false;
3685
0
}
3686
3687
/// parseDirectiveCVLinetable
3688
/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3689
bool AsmParser::parseDirectiveCVLinetable()
3690
0
{
3691
0
  bool valid;
3692
0
  int64_t FunctionId = getTok().getIntVal(valid);
3693
0
  if (!valid) {
3694
0
      return true;
3695
0
  }
3696
0
  if (FunctionId < 0)
3697
    //return TokError("function id less than zero in '.cv_linetable' directive");
3698
0
    return true;
3699
0
  Lex();
3700
3701
0
  if (Lexer.isNot(AsmToken::Comma))
3702
    //return TokError("unexpected token in '.cv_linetable' directive");
3703
0
    return true;
3704
0
  Lex();
3705
3706
0
  SMLoc Loc = getLexer().getLoc();
3707
0
  StringRef FnStartName;
3708
0
  if (parseIdentifier(FnStartName))
3709
    //return Error(Loc, "expected identifier in directive");
3710
0
    return true;
3711
3712
0
  if (Lexer.isNot(AsmToken::Comma))
3713
    //return TokError("unexpected token in '.cv_linetable' directive");
3714
0
    return true;
3715
0
  Lex();
3716
3717
0
  Loc = getLexer().getLoc();
3718
0
  StringRef FnEndName;
3719
0
  if (parseIdentifier(FnEndName))
3720
    //return Error(Loc, "expected identifier in directive");
3721
0
    return true;
3722
3723
0
  if (FnStartName.empty() || FnEndName.empty()) {
3724
0
      return true;
3725
0
  }
3726
0
  MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3727
0
  MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3728
3729
0
  getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3730
0
  return false;
3731
0
}
3732
3733
/// parseDirectiveCVInlineLinetable
3734
/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum
3735
///          ("contains" SecondaryFunctionId+)?
3736
bool AsmParser::parseDirectiveCVInlineLinetable()
3737
0
{
3738
0
  bool valid;
3739
0
  int64_t PrimaryFunctionId = getTok().getIntVal(valid);
3740
0
  if (!valid) {
3741
0
      return true;
3742
0
  }
3743
0
  if (PrimaryFunctionId < 0)
3744
    //return TokError(
3745
    //    "function id less than zero in '.cv_inline_linetable' directive");
3746
0
    return true;
3747
0
  Lex();
3748
3749
0
  int64_t SourceFileId = getTok().getIntVal(valid);
3750
0
  if (!valid) {
3751
0
      return true;
3752
0
  }
3753
0
  if (SourceFileId <= 0)
3754
    //return TokError(
3755
    //    "File id less than zero in '.cv_inline_linetable' directive");
3756
0
    return true;
3757
0
  Lex();
3758
3759
0
  int64_t SourceLineNum = getTok().getIntVal(valid);
3760
0
  if (!valid) {
3761
0
      return true;
3762
0
  }
3763
0
  if (SourceLineNum < 0)
3764
    //return TokError(
3765
    //    "Line number less than zero in '.cv_inline_linetable' directive");
3766
0
    return true;
3767
0
  Lex();
3768
3769
0
  SmallVector<unsigned, 8> SecondaryFunctionIds;
3770
0
  if (getLexer().is(AsmToken::Identifier)) {
3771
0
    if (getTok().getIdentifier() != "contains")
3772
      //return TokError(
3773
      //    "unexpected identifier in '.cv_inline_linetable' directive");
3774
0
      return true;
3775
0
    Lex();
3776
3777
0
    while (getLexer().isNot(AsmToken::EndOfStatement)) {
3778
0
      int64_t SecondaryFunctionId = getTok().getIntVal(valid);
3779
0
      if (!valid) {
3780
0
          return true;
3781
0
      }
3782
0
      if (SecondaryFunctionId < 0)
3783
        //return TokError(
3784
        //    "function id less than zero in '.cv_inline_linetable' directive");
3785
0
        return true;
3786
0
      Lex();
3787
3788
0
      SecondaryFunctionIds.push_back(SecondaryFunctionId);
3789
0
    }
3790
0
  }
3791
3792
0
  getStreamer().EmitCVInlineLinetableDirective(
3793
0
      PrimaryFunctionId, SourceFileId, SourceLineNum, SecondaryFunctionIds);
3794
0
  return false;
3795
0
}
3796
3797
/// parseDirectiveCVStringTable
3798
/// ::= .cv_stringtable
3799
0
bool AsmParser::parseDirectiveCVStringTable() {
3800
0
  getStreamer().EmitCVStringTableDirective();
3801
0
  return false;
3802
0
}
3803
3804
/// parseDirectiveCVFileChecksums
3805
/// ::= .cv_filechecksums
3806
0
bool AsmParser::parseDirectiveCVFileChecksums() {
3807
0
  getStreamer().EmitCVFileChecksumsDirective();
3808
0
  return false;
3809
0
}
3810
3811
/// parseDirectiveCFISections
3812
/// ::= .cfi_sections section [, section]
3813
bool AsmParser::parseDirectiveCFISections()
3814
0
{
3815
0
  StringRef Name;
3816
0
  bool EH = false;
3817
0
  bool Debug = false;
3818
3819
0
  if (parseIdentifier(Name))
3820
    //return TokError("Expected an identifier");
3821
0
    return true;
3822
3823
0
  if (Name == ".eh_frame")
3824
0
    EH = true;
3825
0
  else if (Name == ".debug_frame")
3826
0
    Debug = true;
3827
3828
0
  if (getLexer().is(AsmToken::Comma)) {
3829
0
    Lex();
3830
3831
0
    if (parseIdentifier(Name))
3832
      //return TokError("Expected an identifier");
3833
0
      return true;
3834
3835
0
    if (Name == ".eh_frame")
3836
0
      EH = true;
3837
0
    else if (Name == ".debug_frame")
3838
0
      Debug = true;
3839
0
  }
3840
3841
0
  getStreamer().EmitCFISections(EH, Debug);
3842
0
  return false;
3843
0
}
3844
3845
/// parseDirectiveCFIStartProc
3846
/// ::= .cfi_startproc [simple]
3847
bool AsmParser::parseDirectiveCFIStartProc()
3848
0
{
3849
0
  StringRef Simple;
3850
0
  if (getLexer().isNot(AsmToken::EndOfStatement))
3851
0
    if (parseIdentifier(Simple) || Simple != "simple")
3852
      //return TokError("unexpected token in .cfi_startproc directive");
3853
0
      return true;
3854
3855
0
  getStreamer().EmitCFIStartProc(!Simple.empty());
3856
0
  return false;
3857
0
}
3858
3859
/// parseDirectiveCFIEndProc
3860
/// ::= .cfi_endproc
3861
0
bool AsmParser::parseDirectiveCFIEndProc() {
3862
0
  getStreamer().EmitCFIEndProc();
3863
0
  return false;
3864
0
}
3865
3866
/// \brief parse register name or number.
3867
bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3868
0
                                              SMLoc DirectiveLoc) {
3869
0
  unsigned RegNo;
3870
0
  unsigned int ErrorCode;
3871
3872
0
  if (getLexer().isNot(AsmToken::Integer)) {
3873
0
    if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc, ErrorCode))
3874
0
      return true;
3875
0
    Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3876
0
  } else
3877
0
    return parseAbsoluteExpression(Register);
3878
3879
0
  return false;
3880
0
}
3881
3882
/// parseDirectiveCFIDefCfa
3883
/// ::= .cfi_def_cfa register,  offset
3884
bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc)
3885
0
{
3886
0
  int64_t Register = 0;
3887
0
  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3888
0
    return true;
3889
3890
0
  if (getLexer().isNot(AsmToken::Comma))
3891
    //return TokError("unexpected token in directive");
3892
0
    return true;
3893
0
  Lex();
3894
3895
0
  int64_t Offset = 0;
3896
0
  if (parseAbsoluteExpression(Offset))
3897
0
    return true;
3898
3899
0
  getStreamer().EmitCFIDefCfa(Register, Offset);
3900
0
  return false;
3901
0
}
3902
3903
/// parseDirectiveCFIDefCfaOffset
3904
/// ::= .cfi_def_cfa_offset offset
3905
0
bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3906
0
  int64_t Offset = 0;
3907
0
  if (parseAbsoluteExpression(Offset))
3908
0
    return true;
3909
3910
0
  getStreamer().EmitCFIDefCfaOffset(Offset);
3911
0
  return false;
3912
0
}
3913
3914
/// parseDirectiveCFIRegister
3915
/// ::= .cfi_register register, register
3916
bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc)
3917
0
{
3918
0
  int64_t Register1 = 0;
3919
0
  if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3920
0
    return true;
3921
3922
0
  if (getLexer().isNot(AsmToken::Comma))
3923
    //return TokError("unexpected token in directive");
3924
0
    return true;
3925
0
  Lex();
3926
3927
0
  int64_t Register2 = 0;
3928
0
  if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3929
0
    return true;
3930
3931
0
  getStreamer().EmitCFIRegister(Register1, Register2);
3932
0
  return false;
3933
0
}
3934
3935
/// parseDirectiveCFIWindowSave
3936
/// ::= .cfi_window_save
3937
0
bool AsmParser::parseDirectiveCFIWindowSave() {
3938
0
  getStreamer().EmitCFIWindowSave();
3939
0
  return false;
3940
0
}
3941
3942
/// parseDirectiveCFIAdjustCfaOffset
3943
/// ::= .cfi_adjust_cfa_offset adjustment
3944
0
bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3945
0
  int64_t Adjustment = 0;
3946
0
  if (parseAbsoluteExpression(Adjustment))
3947
0
    return true;
3948
3949
0
  getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3950
0
  return false;
3951
0
}
3952
3953
/// parseDirectiveCFIDefCfaRegister
3954
/// ::= .cfi_def_cfa_register register
3955
0
bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3956
0
  int64_t Register = 0;
3957
0
  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3958
0
    return true;
3959
3960
0
  getStreamer().EmitCFIDefCfaRegister(Register);
3961
0
  return false;
3962
0
}
3963
3964
/// parseDirectiveCFIOffset
3965
/// ::= .cfi_offset register, offset
3966
bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc)
3967
0
{
3968
0
  int64_t Register = 0;
3969
0
  int64_t Offset = 0;
3970
3971
0
  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3972
0
    return true;
3973
3974
0
  if (getLexer().isNot(AsmToken::Comma))
3975
    //return TokError("unexpected token in directive");
3976
0
    return true;
3977
0
  Lex();
3978
3979
0
  if (parseAbsoluteExpression(Offset))
3980
0
    return true;
3981
3982
0
  getStreamer().EmitCFIOffset(Register, Offset);
3983
0
  return false;
3984
0
}
3985
3986
/// parseDirectiveCFIRelOffset
3987
/// ::= .cfi_rel_offset register, offset
3988
0
bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3989
0
  int64_t Register = 0;
3990
3991
0
  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3992
0
    return true;
3993
3994
0
  if (getLexer().isNot(AsmToken::Comma))
3995
    //return TokError("unexpected token in directive");
3996
0
    return true;
3997
0
  Lex();
3998
3999
0
  int64_t Offset = 0;
4000
0
  if (parseAbsoluteExpression(Offset))
4001
0
    return true;
4002
4003
0
  getStreamer().EmitCFIRelOffset(Register, Offset);
4004
0
  return false;
4005
0
}
4006
4007
0
static bool isValidEncoding(int64_t Encoding) {
4008
0
  if (Encoding & ~0xff)
4009
0
    return false;
4010
4011
0
  if (Encoding == dwarf::DW_EH_PE_omit)
4012
0
    return true;
4013
4014
0
  const unsigned Format = Encoding & 0xf;
4015
0
  if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4016
0
      Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4017
0
      Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4018
0
      Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4019
0
    return false;
4020
4021
0
  const unsigned Application = Encoding & 0x70;
4022
0
  if (Application != dwarf::DW_EH_PE_absptr &&
4023
0
      Application != dwarf::DW_EH_PE_pcrel)
4024
0
    return false;
4025
4026
0
  return true;
4027
0
}
4028
4029
/// parseDirectiveCFIPersonalityOrLsda
4030
/// IsPersonality true for cfi_personality, false for cfi_lsda
4031
/// ::= .cfi_personality encoding, [symbol_name]
4032
/// ::= .cfi_lsda encoding, [symbol_name]
4033
0
bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
4034
0
  int64_t Encoding = 0;
4035
0
  if (parseAbsoluteExpression(Encoding))
4036
0
    return true;
4037
0
  if (Encoding == dwarf::DW_EH_PE_omit)
4038
0
    return false;
4039
4040
0
  if (!isValidEncoding(Encoding))
4041
    //return TokError("unsupported encoding.");
4042
0
    return true;
4043
4044
0
  if (getLexer().isNot(AsmToken::Comma))
4045
    //return TokError("unexpected token in directive");
4046
0
    return true;
4047
0
  Lex();
4048
4049
0
  StringRef Name;
4050
0
  if (parseIdentifier(Name))
4051
    //return TokError("expected identifier in directive");
4052
0
    return true;
4053
4054
0
  if (Name.empty()) {
4055
0
      return true;
4056
0
  }
4057
0
  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4058
4059
0
  if (IsPersonality)
4060
0
    getStreamer().EmitCFIPersonality(Sym, Encoding);
4061
0
  else
4062
0
    getStreamer().EmitCFILsda(Sym, Encoding);
4063
0
  return false;
4064
0
}
4065
4066
/// parseDirectiveCFIRememberState
4067
/// ::= .cfi_remember_state
4068
0
bool AsmParser::parseDirectiveCFIRememberState() {
4069
0
  getStreamer().EmitCFIRememberState();
4070
0
  return false;
4071
0
}
4072
4073
/// parseDirectiveCFIRestoreState
4074
/// ::= .cfi_remember_state
4075
0
bool AsmParser::parseDirectiveCFIRestoreState() {
4076
0
  getStreamer().EmitCFIRestoreState();
4077
0
  return false;
4078
0
}
4079
4080
/// parseDirectiveCFISameValue
4081
/// ::= .cfi_same_value register
4082
0
bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
4083
0
  int64_t Register = 0;
4084
4085
0
  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4086
0
    return true;
4087
4088
0
  getStreamer().EmitCFISameValue(Register);
4089
0
  return false;
4090
0
}
4091
4092
/// parseDirectiveCFIRestore
4093
/// ::= .cfi_restore register
4094
0
bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
4095
0
  int64_t Register = 0;
4096
0
  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4097
0
    return true;
4098
4099
0
  getStreamer().EmitCFIRestore(Register);
4100
0
  return false;
4101
0
}
4102
4103
/// parseDirectiveCFIEscape
4104
/// ::= .cfi_escape expression[,...]
4105
0
bool AsmParser::parseDirectiveCFIEscape() {
4106
0
  std::string Values;
4107
0
  int64_t CurrValue;
4108
0
  if (parseAbsoluteExpression(CurrValue))
4109
0
    return true;
4110
4111
0
  Values.push_back((uint8_t)CurrValue);
4112
4113
0
  while (getLexer().is(AsmToken::Comma)) {
4114
0
    Lex();
4115
4116
0
    if (parseAbsoluteExpression(CurrValue))
4117
0
      return true;
4118
4119
0
    Values.push_back((uint8_t)CurrValue);
4120
0
  }
4121
4122
0
  getStreamer().EmitCFIEscape(Values);
4123
0
  return false;
4124
0
}
4125
4126
/// parseDirectiveCFISignalFrame
4127
/// ::= .cfi_signal_frame
4128
0
bool AsmParser::parseDirectiveCFISignalFrame() {
4129
0
  if (getLexer().isNot(AsmToken::EndOfStatement))
4130
    //return Error(getLexer().getLoc(),
4131
    //             "unexpected token in '.cfi_signal_frame'");
4132
0
    return true;
4133
4134
0
  getStreamer().EmitCFISignalFrame();
4135
0
  return false;
4136
0
}
4137
4138
/// parseDirectiveCFIUndefined
4139
/// ::= .cfi_undefined register
4140
0
bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
4141
0
  int64_t Register = 0;
4142
4143
0
  if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4144
0
    return true;
4145
4146
0
  getStreamer().EmitCFIUndefined(Register);
4147
0
  return false;
4148
0
}
4149
4150
/// parseDirectiveMacrosOnOff
4151
/// ::= .macros_on
4152
/// ::= .macros_off
4153
0
bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
4154
0
  if (getLexer().isNot(AsmToken::EndOfStatement))
4155
    //return Error(getLexer().getLoc(),
4156
    //             "unexpected token in '" + Directive + "' directive");
4157
0
    return true;
4158
4159
0
  setMacrosEnabled(Directive == ".macros_on");
4160
0
  return false;
4161
0
}
4162
4163
/// parseDirectiveMacro
4164
/// ::= .macro name[,] [parameters]
4165
bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc)
4166
32.7k
{
4167
32.7k
  StringRef Name;
4168
32.7k
  if (parseIdentifier(Name)) {
4169
    //return TokError("expected identifier in '.macro' directive");
4170
591
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4171
591
    return true;
4172
591
  }
4173
4174
32.1k
  if (getLexer().is(AsmToken::Comma))
4175
7.97k
    Lex();
4176
4177
32.1k
  MCAsmMacroParameters Parameters;
4178
124k
  while (getLexer().isNot(AsmToken::EndOfStatement)) {
4179
4180
94.1k
    if (!Parameters.empty() && Parameters.back().Vararg) {
4181
      //return Error(Lexer.getLoc(),
4182
      //             "Vararg parameter '" + Parameters.back().Name +
4183
      //             "' should be last one in the list of parameters.");
4184
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4185
0
      return true;
4186
0
    }
4187
4188
94.1k
    MCAsmMacroParameter Parameter;
4189
94.1k
    if (parseIdentifier(Parameter.Name)) {
4190
      //return TokError("expected identifier in '.macro' directive");
4191
780
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4192
780
      return true;
4193
780
    }
4194
4195
93.3k
    if (Lexer.is(AsmToken::Colon)) {
4196
952
      Lex();  // consume ':'
4197
4198
952
      SMLoc QualLoc;
4199
952
      StringRef Qualifier;
4200
4201
952
      QualLoc = Lexer.getLoc();
4202
952
      if (parseIdentifier(Qualifier)) {
4203
        //return Error(QualLoc, "missing parameter qualifier for "
4204
        //             "'" + Parameter.Name + "' in macro '" + Name + "'");
4205
682
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4206
682
        return true;
4207
682
      }
4208
4209
270
      if (Qualifier == "req")
4210
0
        Parameter.Required = true;
4211
270
      else if (Qualifier == "vararg")
4212
0
        Parameter.Vararg = true;
4213
270
      else {
4214
        //return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4215
        //             "for '" + Parameter.Name + "' in macro '" + Name + "'");
4216
270
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4217
270
        return true;
4218
270
      }
4219
270
    }
4220
4221
92.4k
    if (getLexer().is(AsmToken::Equal)) {
4222
7.30k
      Lex();
4223
4224
7.30k
      SMLoc ParamLoc;
4225
4226
7.30k
      ParamLoc = Lexer.getLoc();
4227
7.30k
      if (parseMacroArgument(Parameter.Value, /*Vararg=*/false )) {
4228
97
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4229
97
        return true;
4230
97
      }
4231
4232
7.20k
      if (Parameter.Required)
4233
0
        Warning(ParamLoc, "pointless default value for required parameter "
4234
0
                "'" + Parameter.Name + "' in macro '" + Name + "'");
4235
7.20k
    }
4236
4237
92.3k
    Parameters.push_back(std::move(Parameter));
4238
4239
92.3k
    if (getLexer().is(AsmToken::Comma))
4240
29.7k
      Lex();
4241
92.3k
  }
4242
4243
  // Eat the end of statement.
4244
30.3k
  Lex();
4245
4246
30.3k
  AsmToken EndToken, StartToken = getTok();
4247
30.3k
  unsigned MacroDepth = 0;
4248
4249
  // Lex the macro definition.
4250
123k
  for (;;) {
4251
    // Check whether we have reached the end of the file.
4252
123k
    if (getLexer().is(AsmToken::Eof)) {
4253
      //return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4254
860
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4255
860
      return true;
4256
860
    }
4257
4258
    // Otherwise, check whether we have reach the .endmacro.
4259
122k
    if (getLexer().is(AsmToken::Identifier)) {
4260
86.6k
      if (getTok().getIdentifier() == ".endm" ||
4261
86.6k
          getTok().getIdentifier() == ".endmacro") {
4262
36.4k
        if (MacroDepth == 0) { // Outermost macro.
4263
29.4k
          EndToken = getTok();
4264
29.4k
          Lex();
4265
29.4k
          if (getLexer().isNot(AsmToken::EndOfStatement)) {
4266
            //return TokError("unexpected token in '" + EndToken.getIdentifier() +
4267
            //                "' directive");
4268
5.49k
            KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4269
5.49k
            return true;
4270
5.49k
          }
4271
23.9k
          break;
4272
29.4k
        } else {
4273
          // Otherwise we just found the end of an inner macro.
4274
6.93k
          --MacroDepth;
4275
6.93k
        }
4276
50.2k
      } else if (getTok().getIdentifier() == ".macro") {
4277
        // We allow nested macros. Those aren't instantiated until the outermost
4278
        // macro is expanded so just ignore them for now.
4279
7.28k
        ++MacroDepth;
4280
7.28k
      }
4281
86.6k
    }
4282
4283
    // Otherwise, scan til the end of the statement.
4284
93.1k
    eatToEndOfStatement();
4285
93.1k
  }
4286
4287
23.9k
  if (lookupMacro(Name)) {
4288
    //return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4289
18.2k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4290
18.2k
    return true;
4291
18.2k
  }
4292
4293
5.72k
  const char *BodyStart = StartToken.getLoc().getPointer();
4294
5.72k
  const char *BodyEnd = EndToken.getLoc().getPointer();
4295
5.72k
  StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4296
5.72k
  checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
4297
5.72k
  defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
4298
5.72k
  return false;
4299
23.9k
}
4300
4301
/// checkForBadMacro
4302
///
4303
/// With the support added for named parameters there may be code out there that
4304
/// is transitioning from positional parameters.  In versions of gas that did
4305
/// not support named parameters they would be ignored on the macro definition.
4306
/// But to support both styles of parameters this is not possible so if a macro
4307
/// definition has named parameters but does not use them and has what appears
4308
/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4309
/// warning that the positional parameter found in body which have no effect.
4310
/// Hoping the developer will either remove the named parameters from the macro
4311
/// definition so the positional parameters get used if that was what was
4312
/// intended or change the macro to use the named parameters.  It is possible
4313
/// this warning will trigger when the none of the named parameters are used
4314
/// and the strings like $1 are infact to simply to be passed trough unchanged.
4315
void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
4316
                                 StringRef Body,
4317
5.72k
                                 ArrayRef<MCAsmMacroParameter> Parameters) {
4318
  // If this macro is not defined with named parameters the warning we are
4319
  // checking for here doesn't apply.
4320
5.72k
  unsigned NParameters = Parameters.size();
4321
5.72k
  if (NParameters == 0)
4322
1.91k
    return;
4323
4324
3.80k
  bool NamedParametersFound = false;
4325
3.80k
  bool PositionalParametersFound = false;
4326
4327
  // Look at the body of the macro for use of both the named parameters and what
4328
  // are likely to be positional parameters.  This is what expandMacro() is
4329
  // doing when it finds the parameters in the body.
4330
83.8k
  while (!Body.empty()) {
4331
    // Scan for the next possible parameter.
4332
82.3k
    std::size_t End = Body.size(), Pos = 0;
4333
425k
    for (; Pos != End; ++Pos) {
4334
      // Check for a substitution or escape.
4335
      // This macro is defined with parameters, look for \foo, \bar, etc.
4336
422k
      if (Body[Pos] == '\\' && Pos + 1 != End)
4337
61.8k
        break;
4338
4339
      // This macro should have parameters, but look for $0, $1, ..., $n too.
4340
361k
      if (Body[Pos] != '$' || Pos + 1 == End)
4341
328k
        continue;
4342
32.3k
      char Next = Body[Pos + 1];
4343
32.3k
      if (Next == '$' || Next == 'n' ||
4344
32.3k
          isdigit(static_cast<unsigned char>(Next)))
4345
18.2k
        break;
4346
32.3k
    }
4347
4348
    // Check if we reached the end.
4349
82.3k
    if (Pos == End)
4350
2.25k
      break;
4351
4352
80.0k
    if (Body[Pos] == '$') {
4353
18.2k
      switch (Body[Pos + 1]) {
4354
      // $$ => $
4355
9.58k
      case '$':
4356
9.58k
        break;
4357
4358
      // $n => number of arguments
4359
6.34k
      case 'n':
4360
6.34k
        PositionalParametersFound = true;
4361
6.34k
        break;
4362
4363
      // $[0-9] => argument
4364
2.29k
      default: {
4365
2.29k
        PositionalParametersFound = true;
4366
2.29k
        break;
4367
0
      }
4368
18.2k
      }
4369
18.2k
      Pos += 2;
4370
61.8k
    } else {
4371
61.8k
      unsigned I = Pos + 1;
4372
127k
      while (isIdentifierChar(Body[I]) && I + 1 != End)
4373
65.2k
        ++I;
4374
4375
61.8k
      const char *Begin = Body.data() + Pos + 1;
4376
61.8k
      StringRef Argument(Begin, I - (Pos + 1));
4377
61.8k
      unsigned Index = 0;
4378
152k
      for (; Index < NParameters; ++Index)
4379
98.0k
        if (Parameters[Index].Name == Argument)
4380
7.10k
          break;
4381
4382
61.8k
      if (Index == NParameters) {
4383
54.7k
        if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4384
1.14k
          Pos += 3;
4385
53.6k
        else {
4386
53.6k
          Pos = I;
4387
53.6k
        }
4388
54.7k
      } else {
4389
7.10k
        NamedParametersFound = true;
4390
7.10k
        Pos += 1 + Argument.size();
4391
7.10k
      }
4392
61.8k
    }
4393
    // Update the scan point.
4394
80.0k
    Body = Body.substr(Pos);
4395
80.0k
  }
4396
4397
3.80k
  if (!NamedParametersFound && PositionalParametersFound)
4398
391
    Warning(DirectiveLoc, "macro defined with named parameters which are not "
4399
391
                          "used in macro body, possible positional parameter "
4400
391
                          "found in body which will have no effect");
4401
3.80k
}
4402
4403
/// parseDirectiveExitMacro
4404
/// ::= .exitm
4405
bool AsmParser::parseDirectiveExitMacro(StringRef Directive)
4406
0
{
4407
0
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4408
    //return TokError("unexpected token in '" + Directive + "' directive");
4409
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4410
0
    return true;
4411
0
  }
4412
4413
0
  if (!isInsideMacroInstantiation()) {
4414
    //return TokError("unexpected '" + Directive + "' in file, "
4415
    //                                             "no current macro definition");
4416
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4417
0
    return true;
4418
0
  }
4419
4420
  // Exit all conditionals that are active in the current macro.
4421
0
  while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4422
0
    TheCondState = TheCondStack.back();
4423
0
    TheCondStack.pop_back();
4424
0
  }
4425
4426
0
  handleMacroExit();
4427
0
  return false;
4428
0
}
4429
4430
/// parseDirectiveEndMacro
4431
/// ::= .endm
4432
/// ::= .endmacro
4433
bool AsmParser::parseDirectiveEndMacro(StringRef Directive)
4434
305k
{
4435
305k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4436
    //return TokError("unexpected token in '" + Directive + "' directive");
4437
3.85k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4438
3.85k
    return true;
4439
3.85k
  }
4440
4441
  // If we are inside a macro instantiation, terminate the current
4442
  // instantiation.
4443
301k
  if (isInsideMacroInstantiation()) {
4444
298k
    handleMacroExit();
4445
298k
    return false;
4446
298k
  }
4447
4448
  // Otherwise, this .endmacro is a stray entry in the file; well formed
4449
  // .endmacro directives are handled during the macro definition parsing.
4450
  //return TokError("unexpected '" + Directive + "' in file, "
4451
  //                                             "no current macro definition");
4452
3.52k
  KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4453
3.52k
  return true;
4454
301k
}
4455
4456
/// parseDirectivePurgeMacro
4457
/// ::= .purgem
4458
bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc)
4459
44
{
4460
44
  StringRef Name;
4461
44
  if (parseIdentifier(Name)) {
4462
    //return TokError("expected identifier in '.purgem' directive");
4463
7
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4464
7
    return true;
4465
7
  }
4466
4467
37
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4468
    //return TokError("unexpected token in '.purgem' directive");
4469
25
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4470
25
    return true;
4471
25
  }
4472
4473
12
  if (!lookupMacro(Name)) {
4474
    //return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4475
12
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4476
12
    return true;
4477
12
  }
4478
4479
0
  undefineMacro(Name);
4480
0
  return false;
4481
12
}
4482
4483
/// parseDirectiveBundleAlignMode
4484
/// ::= {.bundle_align_mode} expression
4485
bool AsmParser::parseDirectiveBundleAlignMode()
4486
0
{
4487
0
  checkForValidSection();
4488
4489
  // Expect a single argument: an expression that evaluates to a constant
4490
  // in the inclusive range 0-30.
4491
  //SMLoc ExprLoc = getLexer().getLoc();
4492
0
  int64_t AlignSizePow2;
4493
0
  if (parseAbsoluteExpression(AlignSizePow2)) {
4494
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4495
0
    return true;
4496
0
  } else if (getLexer().isNot(AsmToken::EndOfStatement)) {
4497
    //return TokError("unexpected token after expression in"
4498
    //                " '.bundle_align_mode' directive");
4499
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4500
0
    return true;
4501
0
  } else if (AlignSizePow2 < 0 || AlignSizePow2 > 30) {
4502
    //return Error(ExprLoc,
4503
    //             "invalid bundle alignment size (expected between 0 and 30)");
4504
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4505
0
    return true;
4506
0
  }
4507
4508
0
  Lex();
4509
4510
  // Because of AlignSizePow2's verified range we can safely truncate it to
4511
  // unsigned.
4512
0
  getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4513
0
  return false;
4514
0
}
4515
4516
/// parseDirectiveBundleLock
4517
/// ::= {.bundle_lock} [align_to_end]
4518
bool AsmParser::parseDirectiveBundleLock()
4519
0
{
4520
0
  checkForValidSection();
4521
0
  bool AlignToEnd = false;
4522
4523
0
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4524
0
    StringRef Option;
4525
    //SMLoc Loc = getTok().getLoc();
4526
    //const char *kInvalidOptionError =
4527
    //    "invalid option for '.bundle_lock' directive";
4528
4529
0
    if (parseIdentifier(Option)) {
4530
      //return Error(Loc, kInvalidOptionError);
4531
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4532
0
      return true;
4533
0
    }
4534
4535
0
    if (Option != "align_to_end") {
4536
      //return Error(Loc, kInvalidOptionError);
4537
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4538
0
      return true;
4539
0
    } else if (getLexer().isNot(AsmToken::EndOfStatement)) {
4540
      //return Error(Loc,
4541
      //             "unexpected token after '.bundle_lock' directive option");
4542
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4543
0
      return true;
4544
0
    }
4545
0
    AlignToEnd = true;
4546
0
  }
4547
4548
0
  Lex();
4549
4550
0
  getStreamer().EmitBundleLock(AlignToEnd);
4551
0
  return false;
4552
0
}
4553
4554
/// parseDirectiveBundleLock
4555
/// ::= {.bundle_lock}
4556
bool AsmParser::parseDirectiveBundleUnlock()
4557
0
{
4558
0
  checkForValidSection();
4559
4560
0
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4561
    //return TokError("unexpected token in '.bundle_unlock' directive");
4562
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4563
0
    return true;
4564
0
  }
4565
0
  Lex();
4566
4567
0
  getStreamer().EmitBundleUnlock();
4568
0
  return false;
4569
0
}
4570
4571
/// parseDirectiveSpace
4572
/// ::= (.skip | .space) expression [ , expression ]
4573
bool AsmParser::parseDirectiveSpace(StringRef IDVal)
4574
16.9k
{
4575
16.9k
  checkForValidSection();
4576
4577
16.9k
  int64_t NumBytes;
4578
16.9k
  if (parseAbsoluteExpression(NumBytes)) {
4579
714
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4580
714
    return true;
4581
714
  }
4582
4583
16.2k
  int64_t FillExpr = 0;
4584
16.2k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4585
5.35k
    if (getLexer().isNot(AsmToken::Comma)) {
4586
      //return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4587
3.61k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4588
3.61k
      return true;
4589
3.61k
    }
4590
1.73k
    Lex();
4591
4592
1.73k
    if (parseAbsoluteExpression(FillExpr))
4593
95
      return true;
4594
4595
1.63k
    if (getLexer().isNot(AsmToken::EndOfStatement))
4596
      //return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4597
15
      return true;
4598
1.63k
  }
4599
4600
12.4k
  Lex();
4601
4602
12.4k
  if (NumBytes <= 0) {
4603
    //return TokError("invalid number of bytes in '" + Twine(IDVal) +
4604
    //                "' directive");
4605
6.31k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4606
6.31k
    return true;
4607
6.31k
  }
4608
4609
  // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4610
6.16k
  getStreamer().EmitFill(NumBytes, FillExpr);
4611
4612
6.16k
  return false;
4613
12.4k
}
4614
4615
/// parseDirectiveLEB128
4616
/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4617
bool AsmParser::parseDirectiveLEB128(bool Signed)
4618
0
{
4619
0
  checkForValidSection();
4620
0
  const MCExpr *Value;
4621
4622
0
  for (;;) {
4623
0
    if (parseExpression(Value)) {
4624
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4625
0
      return true;
4626
0
    }
4627
4628
0
    if (Signed)
4629
0
      getStreamer().EmitSLEB128Value(Value);
4630
0
    else
4631
0
      getStreamer().EmitULEB128Value(Value);
4632
4633
0
    if (getLexer().is(AsmToken::EndOfStatement))
4634
0
      break;
4635
4636
0
    if (getLexer().isNot(AsmToken::Comma)) {
4637
      //return TokError("unexpected token in directive");
4638
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4639
0
      return true;
4640
0
    }
4641
0
    Lex();
4642
0
  }
4643
4644
0
  return false;
4645
0
}
4646
4647
/// parseDirectiveSymbolAttribute
4648
///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4649
bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr)
4650
664
{
4651
664
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4652
873
    for (;;) {
4653
873
      StringRef Name;
4654
      //SMLoc Loc = getTok().getLoc();
4655
4656
873
      if (parseIdentifier(Name)) {
4657
        //return Error(Loc, "expected identifier in directive");
4658
55
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4659
55
        return true;
4660
55
      }
4661
4662
818
      if (Name.empty()) {
4663
16
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4664
16
          return true;
4665
16
      }
4666
802
      MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4667
4668
      // Assembler local symbols don't make any sense here. Complain loudly.
4669
802
      if (Sym->isTemporary()) {
4670
        //return Error(Loc, "non-local symbol required in directive");
4671
27
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4672
27
        return true;
4673
27
      }
4674
4675
775
      if (!getStreamer().EmitSymbolAttribute(Sym, Attr)) {
4676
        //return Error(Loc, "unable to emit symbol attribute");
4677
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4678
0
        return true;
4679
0
      }
4680
4681
775
      if (getLexer().is(AsmToken::EndOfStatement))
4682
216
        break;
4683
4684
559
      if (getLexer().isNot(AsmToken::Comma)) {
4685
        //return TokError("unexpected token in directive");
4686
218
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4687
218
        return true;
4688
218
      }
4689
341
      Lex();
4690
341
    }
4691
532
  }
4692
4693
348
  Lex();
4694
348
  return false;
4695
664
}
4696
4697
/// parseDirectiveComm
4698
///  ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4699
bool AsmParser::parseDirectiveComm(bool IsLocal)
4700
22.3k
{
4701
22.3k
  checkForValidSection();
4702
4703
  //SMLoc IDLoc = getLexer().getLoc();
4704
22.3k
  StringRef Name;
4705
22.3k
  if (parseIdentifier(Name)) {
4706
    //return TokError("expected identifier in directive");
4707
4.12k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4708
4.12k
    return true;
4709
4.12k
  }
4710
4711
18.2k
  if (Name.empty()) {
4712
127
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4713
127
      return true;
4714
127
  }
4715
  // Handle the identifier as the key symbol.
4716
18.1k
  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4717
4718
18.1k
  if (getLexer().isNot(AsmToken::Comma)) {
4719
    //return TokError("unexpected token in directive");
4720
1.74k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4721
1.74k
    return true;
4722
1.74k
  }
4723
16.3k
  Lex();
4724
4725
16.3k
  int64_t Size;
4726
  //SMLoc SizeLoc = getLexer().getLoc();
4727
16.3k
  if (parseAbsoluteExpression(Size)) {
4728
1.59k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4729
1.59k
    return true;
4730
1.59k
  }
4731
4732
14.7k
  int64_t Pow2Alignment = 0;
4733
14.7k
  SMLoc Pow2AlignmentLoc;
4734
14.7k
  if (getLexer().is(AsmToken::Comma)) {
4735
1.97k
    Lex();
4736
1.97k
    Pow2AlignmentLoc = getLexer().getLoc();
4737
1.97k
    if (parseAbsoluteExpression(Pow2Alignment)) {
4738
178
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4739
178
      return true;
4740
178
    }
4741
4742
1.79k
    LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4743
1.79k
    if (IsLocal && LCOMM == LCOMM::NoAlignment) {
4744
      //return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4745
228
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4746
228
      return true;
4747
228
    }
4748
4749
    // If this target takes alignments in bytes (not log) validate and convert.
4750
1.56k
    if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4751
1.56k
        (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4752
1.56k
      if (!isPowerOf2_64(Pow2Alignment)) {
4753
        //return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4754
1.51k
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4755
1.51k
        return true;
4756
1.51k
      }
4757
50
      Pow2Alignment = Log2_64(Pow2Alignment);
4758
50
    }
4759
1.56k
  }
4760
4761
12.8k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4762
    //return TokError("unexpected token in '.comm' or '.lcomm' directive");
4763
783
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4764
783
    return true;
4765
783
  }
4766
4767
12.0k
  Lex();
4768
4769
  // NOTE: a size of zero for a .comm should create a undefined symbol
4770
  // but a size of .lcomm creates a bss symbol of size zero.
4771
12.0k
  if (Size < 0) {
4772
    //return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4773
    //                      "be less than zero");
4774
695
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4775
695
    return true;
4776
695
  }
4777
4778
  // NOTE: The alignment in the directive is a power of 2 value, the assembler
4779
  // may internally end up wanting an alignment in bytes.
4780
  // FIXME: Diagnose overflow.
4781
11.3k
  if (Pow2Alignment < 0) {
4782
    //return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4783
    //                               "alignment, can't be less than zero");
4784
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4785
0
    return true;
4786
0
  }
4787
4788
11.3k
  if (!Sym->isUndefined()) {
4789
    //return Error(IDLoc, "invalid symbol redefinition");
4790
1.38k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4791
1.38k
    return true;
4792
1.38k
  }
4793
4794
  // Create the Symbol as a common or local common with Size and Pow2Alignment
4795
10.0k
  if (IsLocal) {
4796
419
    getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4797
419
    return false;
4798
419
  }
4799
4800
9.58k
  getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4801
9.58k
  return false;
4802
10.0k
}
4803
4804
/// parseDirectiveAbort
4805
///  ::= .abort [... message ...]
4806
bool AsmParser::parseDirectiveAbort()
4807
58
{
4808
  // FIXME: Use loc from directive.
4809
  //SMLoc Loc = getLexer().getLoc();
4810
4811
58
  StringRef Str = parseStringToEndOfStatement();
4812
58
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4813
    //return TokError("unexpected token in '.abort' directive");
4814
5
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4815
5
    return true;
4816
5
  }
4817
4818
53
  Lex();
4819
4820
53
  if (Str.empty()) {
4821
    //Error(Loc, ".abort detected. Assembly stopping.");
4822
30
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4823
30
    return true;
4824
30
  } else {
4825
    //Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4826
23
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4827
23
    return true;
4828
23
  }
4829
4830
  // FIXME: Actually abort assembly here.
4831
4832
0
  return false;
4833
53
}
4834
4835
/// parseDirectiveInclude
4836
///  ::= .include "filename"
4837
bool AsmParser::parseDirectiveInclude()
4838
1.52k
{
4839
1.52k
  if (getLexer().isNot(AsmToken::String)) {
4840
    //return TokError("expected string in '.include' directive");
4841
901
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4842
901
    return true;
4843
901
  }
4844
4845
  // Allow the strings to have escaped octal character sequence.
4846
625
  std::string Filename;
4847
625
  if (parseEscapedString(Filename)) {
4848
64
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4849
64
    return true;
4850
64
  }
4851
  //SMLoc IncludeLoc = getLexer().getLoc();
4852
561
  Lex();
4853
4854
561
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4855
    //return TokError("unexpected token in '.include' directive");
4856
516
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4857
516
    return true;
4858
516
  }
4859
4860
  // Attempt to switch the lexer to the included file before consuming the end
4861
  // of statement to avoid losing it when we switch.
4862
45
  if (enterIncludeFile(Filename)) {
4863
    //Error(IncludeLoc, "Could not find include file '" + Filename + "'");
4864
45
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4865
45
    return true;
4866
45
  }
4867
4868
0
  return false;
4869
45
}
4870
4871
/// parseDirectiveIncbin
4872
///  ::= .incbin "filename"
4873
bool AsmParser::parseDirectiveIncbin()
4874
0
{
4875
0
  if (getLexer().isNot(AsmToken::String)) {
4876
    //return TokError("expected string in '.incbin' directive");
4877
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4878
0
    return true;
4879
0
  }
4880
4881
  // Allow the strings to have escaped octal character sequence.
4882
0
  std::string Filename;
4883
0
  if (parseEscapedString(Filename)) {
4884
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4885
0
    return true;
4886
0
  }
4887
  //SMLoc IncbinLoc = getLexer().getLoc();
4888
0
  Lex();
4889
4890
0
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
4891
    //return TokError("unexpected token in '.incbin' directive");
4892
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4893
0
    return true;
4894
0
  }
4895
4896
  // Attempt to process the included file.
4897
0
  if (processIncbinFile(Filename)) {
4898
    //Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4899
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4900
0
    return true;
4901
0
  }
4902
4903
0
  return false;
4904
0
}
4905
4906
/// parseDirectiveIf
4907
/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4908
bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind)
4909
42.6k
{
4910
42.6k
  TheCondStack.push_back(TheCondState);
4911
42.6k
  TheCondState.TheCond = AsmCond::IfCond;
4912
42.6k
  if (TheCondState.Ignore) {
4913
9.50k
    eatToEndOfStatement();
4914
33.1k
  } else {
4915
33.1k
    int64_t ExprValue;
4916
33.1k
    if (parseAbsoluteExpression(ExprValue)) {
4917
11.0k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4918
11.0k
      return true;
4919
11.0k
    }
4920
4921
22.0k
    if (getLexer().isNot(AsmToken::EndOfStatement)) {
4922
      //return TokError("unexpected token in '.if' directive");
4923
4.47k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4924
4.47k
      return true;
4925
4.47k
    }
4926
4927
17.5k
    Lex();
4928
4929
17.5k
    switch (DirKind) {
4930
0
    default:
4931
0
      llvm_unreachable("unsupported directive");
4932
1.40k
    case DK_IF:
4933
2.61k
    case DK_IFNE:
4934
2.61k
      break;
4935
3.17k
    case DK_IFEQ:
4936
3.17k
      ExprValue = ExprValue == 0;
4937
3.17k
      break;
4938
2.77k
    case DK_IFGE:
4939
2.77k
      ExprValue = ExprValue >= 0;
4940
2.77k
      break;
4941
3.74k
    case DK_IFGT:
4942
3.74k
      ExprValue = ExprValue > 0;
4943
3.74k
      break;
4944
4.30k
    case DK_IFLE:
4945
4.30k
      ExprValue = ExprValue <= 0;
4946
4.30k
      break;
4947
921
    case DK_IFLT:
4948
921
      ExprValue = ExprValue < 0;
4949
921
      break;
4950
17.5k
    }
4951
4952
17.5k
    TheCondState.CondMet = ExprValue;
4953
17.5k
    TheCondState.Ignore = !TheCondState.CondMet;
4954
17.5k
  }
4955
4956
27.0k
  return false;
4957
42.6k
}
4958
4959
/// parseDirectiveIfb
4960
/// ::= .ifb string
4961
bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank)
4962
35.7k
{
4963
35.7k
  TheCondStack.push_back(TheCondState);
4964
35.7k
  TheCondState.TheCond = AsmCond::IfCond;
4965
4966
35.7k
  if (TheCondState.Ignore) {
4967
10.8k
    eatToEndOfStatement();
4968
24.8k
  } else {
4969
24.8k
    StringRef Str = parseStringToEndOfStatement();
4970
4971
24.8k
    if (getLexer().isNot(AsmToken::EndOfStatement)) {
4972
      //return TokError("unexpected token in '.ifb' directive");
4973
8
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
4974
8
      return true;
4975
8
    }
4976
4977
24.8k
    Lex();
4978
4979
24.8k
    TheCondState.CondMet = ExpectBlank == Str.empty();
4980
24.8k
    TheCondState.Ignore = !TheCondState.CondMet;
4981
24.8k
  }
4982
4983
35.7k
  return false;
4984
35.7k
}
4985
4986
/// parseDirectiveIfc
4987
/// ::= .ifc string1, string2
4988
/// ::= .ifnc string1, string2
4989
bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual)
4990
296k
{
4991
296k
  TheCondStack.push_back(TheCondState);
4992
296k
  TheCondState.TheCond = AsmCond::IfCond;
4993
4994
296k
  if (TheCondState.Ignore) {
4995
5.83k
    eatToEndOfStatement();
4996
290k
  } else {
4997
290k
    StringRef Str1 = parseStringToComma();
4998
4999
290k
    if (getLexer().isNot(AsmToken::Comma)) {
5000
      //return TokError("unexpected token in '.ifc' directive");
5001
205k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5002
205k
      return true;
5003
205k
    }
5004
5005
85.3k
    Lex();
5006
5007
85.3k
    StringRef Str2 = parseStringToEndOfStatement();
5008
5009
85.3k
    if (getLexer().isNot(AsmToken::EndOfStatement)) {
5010
      //return TokError("unexpected token in '.ifc' directive");
5011
8
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5012
8
      return true;
5013
8
    }
5014
5015
85.2k
    Lex();
5016
5017
85.2k
    TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
5018
85.2k
    TheCondState.Ignore = !TheCondState.CondMet;
5019
85.2k
  }
5020
5021
91.1k
  return false;
5022
296k
}
5023
5024
/// parseDirectiveIfeqs
5025
///   ::= .ifeqs string1, string2
5026
bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual)
5027
27.7k
{
5028
27.7k
  if (Lexer.isNot(AsmToken::String)) {
5029
    //if (ExpectEqual)
5030
    //  TokError("expected string parameter for '.ifeqs' directive");
5031
    //else
5032
    //  TokError("expected string parameter for '.ifnes' directive");
5033
4.85k
    eatToEndOfStatement();
5034
4.85k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5035
4.85k
    return true;
5036
4.85k
  }
5037
5038
22.9k
  bool valid;
5039
22.9k
  StringRef String1 = getTok().getStringContents(valid);
5040
22.9k
  if (!valid) {
5041
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5042
0
      return true;
5043
0
  }
5044
5045
22.9k
  Lex();
5046
5047
22.9k
  if (Lexer.isNot(AsmToken::Comma)) {
5048
    //if (ExpectEqual)
5049
    //  TokError("expected comma after first string for '.ifeqs' directive");
5050
    //else
5051
    //  TokError("expected comma after first string for '.ifnes' directive");
5052
69
    eatToEndOfStatement();
5053
69
    return true;
5054
69
  }
5055
5056
22.8k
  Lex();
5057
5058
22.8k
  if (Lexer.isNot(AsmToken::String)) {
5059
    //if (ExpectEqual)
5060
    //  TokError("expected string parameter for '.ifeqs' directive");
5061
    //else
5062
    //  TokError("expected string parameter for '.ifnes' directive");
5063
8.29k
    eatToEndOfStatement();
5064
8.29k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5065
8.29k
    return true;
5066
8.29k
  }
5067
5068
14.5k
  StringRef String2 = getTok().getStringContents(valid);
5069
14.5k
  if (!valid) {
5070
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5071
0
      return true;
5072
0
  }
5073
5074
14.5k
  Lex();
5075
5076
14.5k
  TheCondStack.push_back(TheCondState);
5077
14.5k
  TheCondState.TheCond = AsmCond::IfCond;
5078
14.5k
  TheCondState.CondMet = ExpectEqual == (String1 == String2);
5079
14.5k
  TheCondState.Ignore = !TheCondState.CondMet;
5080
5081
14.5k
  return false;
5082
14.5k
}
5083
5084
/// parseDirectiveIfdef
5085
/// ::= .ifdef symbol
5086
10.5k
bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
5087
10.5k
  StringRef Name;
5088
10.5k
  TheCondStack.push_back(TheCondState);
5089
10.5k
  TheCondState.TheCond = AsmCond::IfCond;
5090
5091
10.5k
  if (TheCondState.Ignore) {
5092
3.86k
    eatToEndOfStatement();
5093
6.64k
  } else {
5094
6.64k
    if (parseIdentifier(Name)) {
5095
      //return TokError("expected identifier after '.ifdef'");
5096
1.33k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5097
1.33k
      return true;
5098
1.33k
    }
5099
5100
5.31k
    Lex();
5101
5102
5.31k
    MCSymbol *Sym = getContext().lookupSymbol(Name);
5103
5104
5.31k
    if (expect_defined)
5105
141
      TheCondState.CondMet = (Sym && !Sym->isUndefined());
5106
5.17k
    else
5107
5.17k
      TheCondState.CondMet = (!Sym || Sym->isUndefined());
5108
5.31k
    TheCondState.Ignore = !TheCondState.CondMet;
5109
5.31k
  }
5110
5111
9.17k
  return false;
5112
10.5k
}
5113
5114
/// parseDirectiveElseIf
5115
/// ::= .elseif expression
5116
bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc)
5117
16.4k
{
5118
16.4k
  if (TheCondState.TheCond != AsmCond::IfCond &&
5119
16.4k
      TheCondState.TheCond != AsmCond::ElseIfCond) {
5120
    //Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
5121
    //                    " an .elseif");
5122
2.90k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5123
2.90k
    return true;
5124
2.90k
  }
5125
5126
13.5k
  TheCondState.TheCond = AsmCond::ElseIfCond;
5127
5128
13.5k
  bool LastIgnoreState = false;
5129
13.5k
  if (!TheCondStack.empty())
5130
13.5k
    LastIgnoreState = TheCondStack.back().Ignore;
5131
13.5k
  if (LastIgnoreState || TheCondState.CondMet) {
5132
11.2k
    TheCondState.Ignore = true;
5133
11.2k
    eatToEndOfStatement();
5134
11.2k
  } else {
5135
2.35k
    int64_t ExprValue;
5136
2.35k
    if (parseAbsoluteExpression(ExprValue)) {
5137
1.18k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5138
1.18k
      return true;
5139
1.18k
    }
5140
5141
1.16k
    if (getLexer().isNot(AsmToken::EndOfStatement))
5142
      //return TokError("unexpected token in '.elseif' directive");
5143
9
      return true;
5144
5145
1.16k
    Lex();
5146
1.16k
    TheCondState.CondMet = ExprValue;
5147
1.16k
    TheCondState.Ignore = !TheCondState.CondMet;
5148
1.16k
  }
5149
5150
12.3k
  return false;
5151
13.5k
}
5152
5153
/// parseDirectiveElse
5154
/// ::= .else
5155
bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc)
5156
14.7k
{
5157
14.7k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
5158
    //return TokError("unexpected token in '.else' directive");
5159
3.92k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5160
3.92k
    return true;
5161
3.92k
  }
5162
5163
10.8k
  Lex();
5164
5165
10.8k
  if (TheCondState.TheCond != AsmCond::IfCond &&
5166
10.8k
      TheCondState.TheCond != AsmCond::ElseIfCond) {
5167
    //Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
5168
    //                    ".elseif");
5169
985
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5170
985
    return true;
5171
985
  }
5172
9.83k
  TheCondState.TheCond = AsmCond::ElseCond;
5173
9.83k
  bool LastIgnoreState = false;
5174
9.83k
  if (!TheCondStack.empty())
5175
9.83k
    LastIgnoreState = TheCondStack.back().Ignore;
5176
9.83k
  if (LastIgnoreState || TheCondState.CondMet)
5177
4.91k
    TheCondState.Ignore = true;
5178
4.92k
  else
5179
4.92k
    TheCondState.Ignore = false;
5180
5181
9.83k
  return false;
5182
10.8k
}
5183
5184
/// parseDirectiveEnd
5185
/// ::= .end
5186
bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc)
5187
18.9k
{
5188
18.9k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
5189
    //return TokError("unexpected token in '.end' directive");
5190
18.7k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5191
18.7k
    return true;
5192
18.7k
  }
5193
5194
118
  Lex();
5195
5196
3.04k
  while (Lexer.isNot(AsmToken::Eof))
5197
2.92k
    Lex();
5198
5199
118
  return false;
5200
18.9k
}
5201
5202
/// parseDirectiveError
5203
///   ::= .err
5204
///   ::= .error [string]
5205
bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage)
5206
4.10k
{
5207
4.10k
  if (!TheCondStack.empty()) {
5208
857
    if (TheCondStack.back().Ignore) {
5209
8
      eatToEndOfStatement();
5210
8
      return false;
5211
8
    }
5212
857
  }
5213
5214
4.09k
  if (!WithMessage) {
5215
    //return Error(L, ".err encountered");
5216
1.91k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5217
1.91k
    return true;
5218
1.91k
  }
5219
5220
2.17k
  StringRef Message = ".error directive invoked in source file";
5221
2.17k
  if (Lexer.isNot(AsmToken::EndOfStatement)) {
5222
2.11k
    if (Lexer.isNot(AsmToken::String)) {
5223
      //TokError(".error argument must be a string");
5224
1.15k
      eatToEndOfStatement();
5225
1.15k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5226
1.15k
      return true;
5227
1.15k
    }
5228
5229
965
    bool valid;
5230
965
    Message = getTok().getStringContents(valid);
5231
965
    if (!valid) {
5232
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5233
0
        return true;
5234
0
    }
5235
965
    Lex();
5236
965
  }
5237
5238
  //Error(L, Message);
5239
1.02k
  KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5240
1.02k
  return true;
5241
2.17k
}
5242
5243
/// parseDirectiveWarning
5244
///   ::= .warning [string]
5245
bool AsmParser::parseDirectiveWarning(SMLoc L)
5246
4.35k
{
5247
4.35k
  if (!TheCondStack.empty()) {
5248
502
    if (TheCondStack.back().Ignore) {
5249
1
      eatToEndOfStatement();
5250
1
      return false;
5251
1
    }
5252
502
  }
5253
5254
4.35k
  StringRef Message = ".warning directive invoked in source file";
5255
4.35k
  if (Lexer.isNot(AsmToken::EndOfStatement)) {
5256
1.56k
    if (Lexer.isNot(AsmToken::String)) {
5257
      //TokError(".warning argument must be a string");
5258
1.39k
      eatToEndOfStatement();
5259
1.39k
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5260
1.39k
      return true;
5261
1.39k
    }
5262
5263
169
    bool valid;
5264
169
    Message = getTok().getStringContents(valid);
5265
169
    if (!valid) {
5266
0
        KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5267
0
        return true;
5268
0
    }
5269
169
    Lex();
5270
169
  }
5271
5272
2.95k
  Warning(L, Message);
5273
2.95k
  return false;
5274
4.35k
}
5275
5276
bool AsmParser::parseNasmDirectiveBits()
5277
0
{
5278
0
  int64_t bits = 0;
5279
5280
0
  if (parseAbsoluteExpression(bits)) {
5281
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5282
0
    return true;
5283
0
  }
5284
5285
0
  switch(bits) {
5286
0
      default:  // invalid parameter
5287
0
          KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5288
0
          return true;
5289
0
      case 16: {
5290
0
          AsmToken bits(AsmToken::Identifier, StringRef(".code16"), 0);
5291
0
          getTargetParser().ParseDirective(bits);
5292
0
          break;
5293
0
      }
5294
0
      case 32: {
5295
0
          AsmToken bits(AsmToken::Identifier, StringRef(".code32"), 0);
5296
0
          getTargetParser().ParseDirective(bits);
5297
0
          break;
5298
0
      }
5299
0
      case 64: {
5300
0
          AsmToken bits(AsmToken::Identifier, StringRef(".code64"), 0);
5301
0
          getTargetParser().ParseDirective(bits);
5302
0
          break;
5303
0
      }
5304
0
  }
5305
5306
0
  return false;
5307
0
}
5308
5309
bool AsmParser::parseNasmDirectiveUse32()
5310
0
{
5311
0
  AsmToken bits(AsmToken::Identifier, StringRef(".code32"), 0);
5312
0
  return getTargetParser().ParseDirective(bits);
5313
0
}
5314
5315
bool AsmParser::parseNasmDirectiveDefault()
5316
0
{
5317
0
  std::string flag = parseStringToEndOfStatement().lower();
5318
0
  if (flag == "rel") {
5319
0
    setNasmDefaultRel(true);
5320
0
    return false;
5321
0
  } else if (flag == "abs") {
5322
0
    setNasmDefaultRel(false);
5323
0
    return false;
5324
0
  }
5325
0
  KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5326
0
  return true;
5327
0
}
5328
5329
/// parseDirectiveEndIf
5330
/// ::= .endif
5331
bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc)
5332
8.06k
{
5333
8.06k
  if (getLexer().isNot(AsmToken::EndOfStatement)) {
5334
    //return TokError("unexpected token in '.endif' directive");
5335
997
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5336
997
    return true;
5337
997
  }
5338
5339
7.06k
  Lex();
5340
5341
7.06k
  if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty()) {
5342
    //Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
5343
    //                    ".else");
5344
3.49k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5345
3.49k
    return true;
5346
3.49k
  }
5347
3.57k
  if (!TheCondStack.empty()) {
5348
3.57k
    TheCondState = TheCondStack.back();
5349
3.57k
    TheCondStack.pop_back();
5350
3.57k
  }
5351
5352
3.57k
  return false;
5353
7.06k
}
5354
5355
void AsmParser::initializeDirectiveKindMap(int syntax)
5356
133k
{
5357
133k
    KsSyntax = syntax;
5358
133k
    if (syntax == KS_OPT_SYNTAX_NASM) {
5359
        // NASM syntax
5360
340
        DirectiveKindMap.clear();
5361
340
        DirectiveKindMap["db"] = DK_BYTE;
5362
340
        DirectiveKindMap["dw"] = DK_SHORT;
5363
340
        DirectiveKindMap["dd"] = DK_INT;
5364
340
        DirectiveKindMap["dq"] = DK_QUAD;
5365
340
        DirectiveKindMap["use16"] = DK_CODE16;
5366
340
        DirectiveKindMap["use32"] = DK_NASM_USE32;
5367
340
        DirectiveKindMap["global"] = DK_GLOBAL;
5368
340
        DirectiveKindMap["bits"] = DK_NASM_BITS;
5369
340
        DirectiveKindMap["default"] = DK_NASM_DEFAULT;
5370
132k
    } else {
5371
        // default LLVM syntax
5372
132k
        DirectiveKindMap.clear();
5373
132k
        DirectiveKindMap[".set"] = DK_SET;
5374
132k
        DirectiveKindMap[".equ"] = DK_EQU;
5375
132k
        DirectiveKindMap[".equiv"] = DK_EQUIV;
5376
132k
        DirectiveKindMap[".ascii"] = DK_ASCII;
5377
132k
        DirectiveKindMap[".asciz"] = DK_ASCIZ;
5378
132k
        DirectiveKindMap[".string"] = DK_STRING;
5379
132k
        DirectiveKindMap[".byte"] = DK_BYTE;
5380
132k
        DirectiveKindMap[".short"] = DK_SHORT;
5381
132k
        DirectiveKindMap[".value"] = DK_VALUE;
5382
132k
        DirectiveKindMap[".2byte"] = DK_2BYTE;
5383
132k
        DirectiveKindMap[".long"] = DK_LONG;
5384
132k
        DirectiveKindMap[".int"] = DK_INT;
5385
132k
        DirectiveKindMap[".4byte"] = DK_4BYTE;
5386
132k
        DirectiveKindMap[".quad"] = DK_QUAD;
5387
132k
        DirectiveKindMap[".8byte"] = DK_8BYTE;
5388
132k
        DirectiveKindMap[".octa"] = DK_OCTA;
5389
132k
        DirectiveKindMap[".single"] = DK_SINGLE;
5390
132k
        DirectiveKindMap[".float"] = DK_FLOAT;
5391
132k
        DirectiveKindMap[".double"] = DK_DOUBLE;
5392
132k
        DirectiveKindMap[".align"] = DK_ALIGN;
5393
132k
        DirectiveKindMap[".align32"] = DK_ALIGN32;
5394
132k
        DirectiveKindMap[".balign"] = DK_BALIGN;
5395
132k
        DirectiveKindMap[".balignw"] = DK_BALIGNW;
5396
132k
        DirectiveKindMap[".balignl"] = DK_BALIGNL;
5397
132k
        DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5398
132k
        DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5399
132k
        DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5400
132k
        DirectiveKindMap[".org"] = DK_ORG;
5401
132k
        DirectiveKindMap[".fill"] = DK_FILL;
5402
132k
        DirectiveKindMap[".zero"] = DK_ZERO;
5403
132k
        DirectiveKindMap[".extern"] = DK_EXTERN;
5404
132k
        DirectiveKindMap[".globl"] = DK_GLOBL;
5405
132k
        DirectiveKindMap[".global"] = DK_GLOBAL;
5406
132k
        DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5407
132k
        DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5408
132k
        DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5409
132k
        DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5410
132k
        DirectiveKindMap[".reference"] = DK_REFERENCE;
5411
132k
        DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5412
132k
        DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5413
132k
        DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5414
132k
        DirectiveKindMap[".comm"] = DK_COMM;
5415
132k
        DirectiveKindMap[".common"] = DK_COMMON;
5416
132k
        DirectiveKindMap[".lcomm"] = DK_LCOMM;
5417
132k
        DirectiveKindMap[".abort"] = DK_ABORT;
5418
132k
        DirectiveKindMap[".include"] = DK_INCLUDE;
5419
132k
        DirectiveKindMap[".incbin"] = DK_INCBIN;
5420
132k
        DirectiveKindMap[".code16"] = DK_CODE16;
5421
132k
        DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5422
132k
        DirectiveKindMap[".rept"] = DK_REPT;
5423
132k
        DirectiveKindMap[".rep"] = DK_REPT;
5424
132k
        DirectiveKindMap[".irp"] = DK_IRP;
5425
132k
        DirectiveKindMap[".irpc"] = DK_IRPC;
5426
132k
        DirectiveKindMap[".endr"] = DK_ENDR;
5427
132k
        DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5428
132k
        DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5429
132k
        DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5430
132k
        DirectiveKindMap[".if"] = DK_IF;
5431
132k
        DirectiveKindMap[".ifeq"] = DK_IFEQ;
5432
132k
        DirectiveKindMap[".ifge"] = DK_IFGE;
5433
132k
        DirectiveKindMap[".ifgt"] = DK_IFGT;
5434
132k
        DirectiveKindMap[".ifle"] = DK_IFLE;
5435
132k
        DirectiveKindMap[".iflt"] = DK_IFLT;
5436
132k
        DirectiveKindMap[".ifne"] = DK_IFNE;
5437
132k
        DirectiveKindMap[".ifb"] = DK_IFB;
5438
132k
        DirectiveKindMap[".ifnb"] = DK_IFNB;
5439
132k
        DirectiveKindMap[".ifc"] = DK_IFC;
5440
132k
        DirectiveKindMap[".ifeqs"] = DK_IFEQS;
5441
132k
        DirectiveKindMap[".ifnc"] = DK_IFNC;
5442
132k
        DirectiveKindMap[".ifnes"] = DK_IFNES;
5443
132k
        DirectiveKindMap[".ifdef"] = DK_IFDEF;
5444
132k
        DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5445
132k
        DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5446
132k
        DirectiveKindMap[".elseif"] = DK_ELSEIF;
5447
132k
        DirectiveKindMap[".else"] = DK_ELSE;
5448
132k
        DirectiveKindMap[".end"] = DK_END;
5449
132k
        DirectiveKindMap[".endif"] = DK_ENDIF;
5450
132k
        DirectiveKindMap[".skip"] = DK_SKIP;
5451
132k
        DirectiveKindMap[".space"] = DK_SPACE;
5452
132k
        DirectiveKindMap[".file"] = DK_FILE;
5453
132k
        DirectiveKindMap[".line"] = DK_LINE;
5454
132k
        DirectiveKindMap[".loc"] = DK_LOC;
5455
132k
        DirectiveKindMap[".stabs"] = DK_STABS;
5456
132k
        DirectiveKindMap[".cv_file"] = DK_CV_FILE;
5457
132k
        DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5458
132k
        DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
5459
132k
        DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
5460
132k
        DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5461
132k
        DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
5462
132k
        DirectiveKindMap[".sleb128"] = DK_SLEB128;
5463
132k
        DirectiveKindMap[".uleb128"] = DK_ULEB128;
5464
132k
        DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5465
132k
        DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5466
132k
        DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5467
132k
        DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5468
132k
        DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5469
132k
        DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5470
132k
        DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5471
132k
        DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5472
132k
        DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5473
132k
        DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5474
132k
        DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5475
132k
        DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5476
132k
        DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5477
132k
        DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5478
132k
        DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5479
132k
        DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5480
132k
        DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5481
132k
        DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5482
132k
        DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
5483
132k
        DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
5484
132k
        DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5485
132k
        DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5486
132k
        DirectiveKindMap[".macro"] = DK_MACRO;
5487
132k
        DirectiveKindMap[".exitm"] = DK_EXITM;
5488
132k
        DirectiveKindMap[".endm"] = DK_ENDM;
5489
132k
        DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5490
132k
        DirectiveKindMap[".purgem"] = DK_PURGEM;
5491
132k
        DirectiveKindMap[".err"] = DK_ERR;
5492
132k
        DirectiveKindMap[".error"] = DK_ERROR;
5493
132k
        DirectiveKindMap[".warning"] = DK_WARNING;
5494
132k
        DirectiveKindMap[".reloc"] = DK_RELOC;
5495
132k
    }
5496
133k
}
5497
5498
34.8k
MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
5499
34.8k
  AsmToken EndToken, StartToken = getTok();
5500
5501
34.8k
  unsigned NestLevel = 0;
5502
3.14M
  for (;;) {
5503
    // Check whether we have reached the end of the file.
5504
3.14M
    if (getLexer().is(AsmToken::Eof)) {
5505
      //Error(DirectiveLoc, "no matching '.endr' in definition");
5506
1.46k
      return nullptr;
5507
1.46k
    }
5508
5509
3.14M
    if (Lexer.is(AsmToken::Identifier) &&
5510
3.14M
        (getTok().getIdentifier() == ".rept")) {
5511
3.33k
      ++NestLevel;
5512
3.33k
    }
5513
5514
    // Otherwise, check whether we have reached the .endr.
5515
3.14M
    if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
5516
33.9k
      if (NestLevel == 0) {
5517
33.4k
        EndToken = getTok();
5518
33.4k
        Lex();
5519
33.4k
        if (Lexer.isNot(AsmToken::EndOfStatement)) {
5520
          //TokError("unexpected token in '.endr' directive");
5521
1.42k
          return nullptr;
5522
1.42k
        }
5523
32.0k
        break;
5524
33.4k
      }
5525
547
      --NestLevel;
5526
547
    }
5527
5528
    // Otherwise, scan till the end of the statement.
5529
3.11M
    eatToEndOfStatement();
5530
3.11M
  }
5531
5532
32.0k
  const char *BodyStart = StartToken.getLoc().getPointer();
5533
32.0k
  const char *BodyEnd = EndToken.getLoc().getPointer();
5534
32.0k
  StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5535
5536
  // We Are Anonymous.
5537
32.0k
  MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5538
32.0k
  return &MacroLikeBodies.back();
5539
34.8k
}
5540
5541
void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5542
32.0k
                                         raw_svector_ostream &OS) {
5543
32.0k
  OS << ".endr\n";
5544
5545
32.0k
  std::unique_ptr<MemoryBuffer> Instantiation =
5546
32.0k
      MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5547
5548
  // Create the macro instantiation object and add to the current macro
5549
  // instantiation stack.
5550
32.0k
  MacroInstantiation *MI = new MacroInstantiation(
5551
32.0k
      DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
5552
32.0k
  ActiveMacros.push_back(MI);
5553
5554
  // Jump to the macro instantiation and prime the lexer.
5555
32.0k
  CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5556
32.0k
  Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5557
32.0k
  Lex();
5558
32.0k
}
5559
5560
/// parseDirectiveRept
5561
///   ::= .rep | .rept count
5562
bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir)
5563
287k
{
5564
287k
  const MCExpr *CountExpr;
5565
  //SMLoc CountLoc = getTok().getLoc();
5566
287k
  if (parseExpression(CountExpr)) {
5567
178k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5568
178k
    return true;
5569
178k
  }
5570
5571
109k
  int64_t Count;
5572
109k
  if (!CountExpr->evaluateAsAbsolute(Count)) {
5573
24.0k
    eatToEndOfStatement();
5574
    //return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5575
24.0k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5576
24.0k
    return true;
5577
24.0k
  }
5578
5579
85.0k
  if (Count < 0) {
5580
    //return Error(CountLoc, "Count is negative");
5581
74.5k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5582
74.5k
    return true;
5583
74.5k
  }
5584
5585
10.5k
  if (Lexer.isNot(AsmToken::EndOfStatement)) {
5586
    //return TokError("unexpected token in '" + Dir + "' directive");
5587
2.33k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5588
2.33k
    return true;
5589
2.33k
  }
5590
5591
  // Eat the end of statement.
5592
8.22k
  Lex();
5593
5594
  // Lex the rept definition.
5595
8.22k
  MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5596
8.22k
  if (!M) {
5597
342
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5598
342
    return true;
5599
342
  }
5600
5601
  // Macro instantiation is lexical, unfortunately. We construct a new buffer
5602
  // to hold the macro body with substitutions.
5603
7.87k
  SmallString<256> Buf;
5604
7.87k
  raw_svector_ostream OS(Buf);
5605
158M
  while (Count--) {
5606
    // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5607
158M
    if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc())) {
5608
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5609
0
      return true;
5610
0
    }
5611
158M
  }
5612
7.87k
  instantiateMacroLikeBody(M, DirectiveLoc, OS);
5613
5614
7.87k
  return false;
5615
7.87k
}
5616
5617
/// parseDirectiveIrp
5618
/// ::= .irp symbol,values
5619
bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc)
5620
28.8k
{
5621
28.8k
  MCAsmMacroParameter Parameter;
5622
5623
28.8k
  if (parseIdentifier(Parameter.Name)) {
5624
    //return TokError("expected identifier in '.irp' directive");
5625
1.29k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5626
1.29k
    return true;
5627
1.29k
  }
5628
5629
27.5k
  if (Lexer.isNot(AsmToken::Comma)) {
5630
    //return TokError("expected comma in '.irp' directive");
5631
1.65k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5632
1.65k
    return true;
5633
1.65k
  }
5634
5635
25.9k
  Lex();
5636
5637
25.9k
  MCAsmMacroArguments A;
5638
25.9k
  if (parseMacroArguments(nullptr, A)) {
5639
2.39k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5640
2.39k
    return true;
5641
2.39k
  }
5642
5643
  // Eat the end of statement.
5644
23.5k
  Lex();
5645
5646
  // Lex the irp definition.
5647
23.5k
  MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5648
23.5k
  if (!M) {
5649
1.34k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5650
1.34k
    return true;
5651
1.34k
  }
5652
5653
  // Macro instantiation is lexical, unfortunately. We construct a new buffer
5654
  // to hold the macro body with substitutions.
5655
22.1k
  SmallString<256> Buf;
5656
22.1k
  raw_svector_ostream OS(Buf);
5657
5658
209k
  for (const MCAsmMacroArgument &Arg : A) {
5659
    // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5660
    // This is undocumented, but GAS seems to support it.
5661
209k
    if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) {
5662
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5663
0
      return true;
5664
0
    }
5665
209k
  }
5666
5667
22.1k
  instantiateMacroLikeBody(M, DirectiveLoc, OS);
5668
5669
22.1k
  return false;
5670
22.1k
}
5671
5672
/// parseDirectiveIrpc
5673
/// ::= .irpc symbol,values
5674
bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc)
5675
31.6k
{
5676
31.6k
  MCAsmMacroParameter Parameter;
5677
5678
31.6k
  if (parseIdentifier(Parameter.Name)) {
5679
    //return TokError("expected identifier in '.irpc' directive");
5680
1.62k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5681
1.62k
    return true;
5682
1.62k
  }
5683
5684
29.9k
  if (Lexer.isNot(AsmToken::Comma)) {
5685
    //return TokError("expected comma in '.irpc' directive");
5686
2.70k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5687
2.70k
    return true;
5688
2.70k
  }
5689
5690
27.2k
  Lex();
5691
5692
27.2k
  MCAsmMacroArguments A;
5693
27.2k
  if (parseMacroArguments(nullptr, A)) {
5694
7.82k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5695
7.82k
    return true;
5696
7.82k
  }
5697
5698
19.4k
  if (A.size() != 1 || A.front().size() != 1) {
5699
    //return TokError("unexpected token in '.irpc' directive");
5700
16.3k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5701
16.3k
    return true;
5702
16.3k
  }
5703
5704
  // Eat the end of statement.
5705
3.14k
  Lex();
5706
5707
  // Lex the irpc definition.
5708
3.14k
  MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5709
3.14k
  if (!M) {
5710
1.21k
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5711
1.21k
    return true;
5712
1.21k
  }
5713
5714
  // Macro instantiation is lexical, unfortunately. We construct a new buffer
5715
  // to hold the macro body with substitutions.
5716
1.93k
  SmallString<256> Buf;
5717
1.93k
  raw_svector_ostream OS(Buf);
5718
5719
1.93k
  StringRef Values = A.front().front().getString();
5720
110k
  for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5721
108k
    MCAsmMacroArgument Arg;
5722
108k
    Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5723
5724
    // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5725
    // This is undocumented, but GAS seems to support it.
5726
108k
    if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc())) {
5727
0
      KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5728
0
      return true;
5729
0
    }
5730
108k
  }
5731
5732
1.93k
  instantiateMacroLikeBody(M, DirectiveLoc, OS);
5733
5734
1.93k
  return false;
5735
1.93k
}
5736
5737
bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc)
5738
27.3k
{
5739
27.3k
  if (ActiveMacros.empty()) {
5740
    //return TokError("unmatched '.endr' directive");
5741
922
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5742
922
    return true;
5743
922
  }
5744
5745
  // The only .repl that should get here are the ones created by
5746
  // instantiateMacroLikeBody.
5747
26.4k
  assert(getLexer().is(AsmToken::EndOfStatement));
5748
5749
26.4k
  handleMacroExit();
5750
26.4k
  return false;
5751
26.4k
}
5752
5753
bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5754
                                     size_t Len)
5755
0
{
5756
0
  const MCExpr *Value;
5757
  //SMLoc ExprLoc = getLexer().getLoc();
5758
0
  if (parseExpression(Value)) {
5759
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5760
0
    return true;
5761
0
  }
5762
0
  const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5763
0
  if (!MCE) {
5764
    //return Error(ExprLoc, "unexpected expression in _emit");
5765
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5766
0
    return true;
5767
0
  }
5768
0
  uint64_t IntValue = MCE->getValue();
5769
0
  if (!isUInt<8>(IntValue) && !isInt<8>(IntValue)) {
5770
    //return Error(ExprLoc, "literal value out of range for directive");
5771
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5772
0
    return true;
5773
0
  }
5774
5775
0
  Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5776
0
  return false;
5777
0
}
5778
5779
bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info)
5780
0
{
5781
0
  const MCExpr *Value;
5782
  //SMLoc ExprLoc = getLexer().getLoc();
5783
0
  if (parseExpression(Value)) {
5784
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5785
0
    return true;
5786
0
  }
5787
0
  const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5788
0
  if (!MCE) {
5789
    //return Error(ExprLoc, "unexpected expression in align");
5790
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5791
0
    return true;
5792
0
  }
5793
0
  uint64_t IntValue = MCE->getValue();
5794
0
  if (!isPowerOf2_64(IntValue)) {
5795
    //return Error(ExprLoc, "literal value not a power of two greater then zero");
5796
0
    KsError = KS_ERR_ASM_DIRECTIVE_INVALID;
5797
0
    return true;
5798
0
  }
5799
5800
0
  Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5801
0
  return false;
5802
0
}
5803
5804
// We are comparing pointers, but the pointers are relative to a single string.
5805
// Thus, this should always be deterministic.
5806
static int rewritesSort(const AsmRewrite *AsmRewriteA,
5807
0
                        const AsmRewrite *AsmRewriteB) {
5808
0
  if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5809
0
    return -1;
5810
0
  if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5811
0
    return 1;
5812
5813
  // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5814
  // rewrite to the same location.  Make sure the SizeDirective rewrite is
5815
  // performed first, then the Imm/ImmPrefix and finally the Input/Output.  This
5816
  // ensures the sort algorithm is stable.
5817
0
  if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5818
0
      AsmRewritePrecedence[AsmRewriteB->Kind])
5819
0
    return -1;
5820
5821
0
  if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5822
0
      AsmRewritePrecedence[AsmRewriteB->Kind])
5823
0
    return 1;
5824
0
  llvm_unreachable("Unstable rewrite sort.");
5825
0
}
5826
5827
bool AsmParser::parseMSInlineAsm(
5828
    void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5829
    unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5830
    SmallVectorImpl<std::string> &Constraints,
5831
    SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5832
    MCAsmParserSemaCallback &SI, uint64_t &Address)
5833
0
{
5834
0
  SmallVector<void *, 4> InputDecls;
5835
0
  SmallVector<void *, 4> OutputDecls;
5836
0
  SmallVector<bool, 4> InputDeclsAddressOf;
5837
0
  SmallVector<bool, 4> OutputDeclsAddressOf;
5838
0
  SmallVector<std::string, 4> InputConstraints;
5839
0
  SmallVector<std::string, 4> OutputConstraints;
5840
0
  SmallVector<unsigned, 4> ClobberRegs;
5841
5842
0
  SmallVector<AsmRewrite, 4> AsmStrRewrites;
5843
5844
  // Prime the lexer.
5845
0
  Lex();
5846
5847
  // While we have input, parse each statement.
5848
0
  unsigned InputIdx = 0;
5849
0
  unsigned OutputIdx = 0;
5850
0
  while (getLexer().isNot(AsmToken::Eof)) {
5851
0
    ParseStatementInfo Info(&AsmStrRewrites);
5852
0
    if (parseStatement(Info, &SI, Address))
5853
0
      return true;
5854
5855
0
    if (Info.ParseError)
5856
0
      return true;
5857
5858
0
    if (Info.Opcode == ~0U)
5859
0
      continue;
5860
5861
0
    const MCInstrDesc &Desc = MII->get(Info.Opcode);
5862
5863
    // Build the list of clobbers, outputs and inputs.
5864
0
    for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5865
0
      MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5866
5867
      // Immediate.
5868
0
      if (Operand.isImm())
5869
0
        continue;
5870
5871
      // Register operand.
5872
0
      if (Operand.isReg() && !Operand.needAddressOf() &&
5873
0
          !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5874
0
        unsigned NumDefs = Desc.getNumDefs();
5875
        // Clobber.
5876
0
        if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5877
0
          ClobberRegs.push_back(Operand.getReg());
5878
0
        continue;
5879
0
      }
5880
5881
      // Expr/Input or Output.
5882
0
      StringRef SymName = Operand.getSymName();
5883
0
      if (SymName.empty())
5884
0
        continue;
5885
5886
0
      void *OpDecl = Operand.getOpDecl();
5887
0
      if (!OpDecl)
5888
0
        continue;
5889
5890
0
      bool isOutput = (i == 1) && Desc.mayStore();
5891
0
      SMLoc Start = SMLoc::getFromPointer(SymName.data());
5892
0
      if (isOutput) {
5893
0
        ++InputIdx;
5894
0
        OutputDecls.push_back(OpDecl);
5895
0
        OutputDeclsAddressOf.push_back(Operand.needAddressOf());
5896
0
        OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
5897
0
        AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
5898
0
      } else {
5899
0
        InputDecls.push_back(OpDecl);
5900
0
        InputDeclsAddressOf.push_back(Operand.needAddressOf());
5901
0
        InputConstraints.push_back(Operand.getConstraint().str());
5902
0
        AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
5903
0
      }
5904
0
    }
5905
5906
    // Consider implicit defs to be clobbers.  Think of cpuid and push.
5907
0
    ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5908
0
                                Desc.getNumImplicitDefs());
5909
0
    ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
5910
0
  }
5911
5912
  // Set the number of Outputs and Inputs.
5913
0
  NumOutputs = OutputDecls.size();
5914
0
  NumInputs = InputDecls.size();
5915
5916
  // Set the unique clobbers.
5917
0
  array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5918
0
  ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5919
0
                    ClobberRegs.end());
5920
0
  Clobbers.assign(ClobberRegs.size(), std::string());
5921
0
  for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5922
0
    raw_string_ostream OS(Clobbers[I]);
5923
    //IP->printRegName(OS, ClobberRegs[I]);
5924
0
  }
5925
5926
  // Merge the various outputs and inputs.  Output are expected first.
5927
0
  if (NumOutputs || NumInputs) {
5928
0
    unsigned NumExprs = NumOutputs + NumInputs;
5929
0
    OpDecls.resize(NumExprs);
5930
0
    Constraints.resize(NumExprs);
5931
0
    for (unsigned i = 0; i < NumOutputs; ++i) {
5932
0
      OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5933
0
      Constraints[i] = OutputConstraints[i];
5934
0
    }
5935
0
    for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5936
0
      OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5937
0
      Constraints[j] = InputConstraints[i];
5938
0
    }
5939
0
  }
5940
5941
  // Build the IR assembly string.
5942
0
  std::string AsmStringIR;
5943
0
  raw_string_ostream OS(AsmStringIR);
5944
0
  StringRef ASMString =
5945
0
      SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5946
0
  const char *AsmStart = ASMString.begin();
5947
0
  const char *AsmEnd = ASMString.end();
5948
0
  array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5949
0
  for (const AsmRewrite &AR : AsmStrRewrites) {
5950
0
    AsmRewriteKind Kind = AR.Kind;
5951
0
    if (Kind == AOK_Delete)
5952
0
      continue;
5953
5954
0
    const char *Loc = AR.Loc.getPointer();
5955
0
    assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
5956
5957
    // Emit everything up to the immediate/expression.
5958
0
    if (unsigned Len = Loc - AsmStart)
5959
0
      OS << StringRef(AsmStart, Len);
5960
5961
    // Skip the original expression.
5962
0
    if (Kind == AOK_Skip) {
5963
0
      AsmStart = Loc + AR.Len;
5964
0
      continue;
5965
0
    }
5966
5967
0
    unsigned AdditionalSkip = 0;
5968
    // Rewrite expressions in $N notation.
5969
0
    switch (Kind) {
5970
0
    default:
5971
0
      break;
5972
0
    case AOK_Imm:
5973
0
      OS << "$$" << AR.Val;
5974
0
      break;
5975
0
    case AOK_ImmPrefix:
5976
0
      OS << "$$";
5977
0
      break;
5978
0
    case AOK_Label:
5979
0
      OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5980
0
      break;
5981
0
    case AOK_Input:
5982
0
      OS << '$' << InputIdx++;
5983
0
      break;
5984
0
    case AOK_Output:
5985
0
      OS << '$' << OutputIdx++;
5986
0
      break;
5987
0
    case AOK_SizeDirective:
5988
0
      switch (AR.Val) {
5989
0
      default: break;
5990
0
      case 8:  OS << "byte ptr "; break;
5991
0
      case 16: OS << "word ptr "; break;
5992
0
      case 32: OS << "dword ptr "; break;
5993
0
      case 64: OS << "qword ptr "; break;
5994
0
      case 80: OS << "xword ptr "; break;
5995
0
      case 128: OS << "xmmword ptr "; break;
5996
0
      case 256: OS << "ymmword ptr "; break;
5997
0
      }
5998
0
      break;
5999
0
    case AOK_Emit:
6000
0
      OS << ".byte";
6001
0
      break;
6002
0
    case AOK_Align: {
6003
      // MS alignment directives are measured in bytes. If the native assembler
6004
      // measures alignment in bytes, we can pass it straight through.
6005
0
      OS << ".align";
6006
0
      if (getContext().getAsmInfo()->getAlignmentIsInBytes())
6007
0
        break;
6008
6009
      // Alignment is in log2 form, so print that instead and skip the original
6010
      // immediate.
6011
0
      unsigned Val = AR.Val;
6012
0
      OS << ' ' << Val;
6013
0
      assert(Val < 10 && "Expected alignment less then 2^10.");
6014
0
      AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
6015
0
      break;
6016
0
    }
6017
0
    case AOK_EVEN:
6018
0
      OS << ".even";
6019
0
      break;
6020
0
    case AOK_DotOperator:
6021
      // Insert the dot if the user omitted it.
6022
0
      OS.flush();
6023
0
      if (AsmStringIR.back() != '.')
6024
0
        OS << '.';
6025
0
      OS << AR.Val;
6026
0
      break;
6027
0
    }
6028
6029
    // Skip the original expression.
6030
0
    AsmStart = Loc + AR.Len + AdditionalSkip;
6031
0
  }
6032
6033
  // Emit the remainder of the asm string.
6034
0
  if (AsmStart != AsmEnd)
6035
0
    OS << StringRef(AsmStart, AsmEnd - AsmStart);
6036
6037
0
  AsmString = OS.str();
6038
0
  return false;
6039
0
}
6040
6041
namespace llvm_ks {
6042
namespace MCParserUtils {
6043
6044
/// Returns whether the given symbol is used anywhere in the given expression,
6045
/// or subexpressions.
6046
818k
static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
6047
818k
  switch (Value->getKind()) {
6048
87.3k
  case MCExpr::Binary: {
6049
87.3k
    const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
6050
87.3k
    return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
6051
87.3k
           isSymbolUsedInExpression(Sym, BE->getRHS());
6052
0
  }
6053
171
  case MCExpr::Target:
6054
67.1k
  case MCExpr::Constant:
6055
67.1k
    return false;
6056
612k
  case MCExpr::SymbolRef: {
6057
612k
    const MCSymbol &S =
6058
612k
        static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
6059
612k
    if (S.isVariable())
6060
34.9k
      return isSymbolUsedInExpression(Sym, S.getVariableValue());
6061
577k
    return &S == Sym;
6062
612k
  }
6063
51.5k
  case MCExpr::Unary:
6064
51.5k
    return isSymbolUsedInExpression(
6065
51.5k
        Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
6066
818k
  }
6067
6068
818k
  llvm_unreachable("Unknown expr kind!");
6069
818k
}
6070
6071
bool parseAssignmentExpression(StringRef Name, bool allow_redef,
6072
                               MCAsmParser &Parser, MCSymbol *&Sym,
6073
                               const MCExpr *&Value)
6074
1.57M
{
6075
1.57M
  MCAsmLexer &Lexer = Parser.getLexer();
6076
6077
  // FIXME: Use better location, we should use proper tokens.
6078
  //SMLoc EqualLoc = Lexer.getLoc();
6079
6080
1.57M
  if (Parser.parseExpression(Value)) {
6081
    //Parser.TokError("missing expression");
6082
645k
    Parser.eatToEndOfStatement();
6083
645k
    return true;
6084
645k
  }
6085
6086
  // Note: we don't count b as used in "a = b". This is to allow
6087
  // a = b
6088
  // b = c
6089
6090
929k
  if (Lexer.isNot(AsmToken::EndOfStatement))
6091
    //return Parser.TokError("unexpected token in assignment");
6092
54.7k
    return true;
6093
6094
  // Eat the end of statement marker.
6095
874k
  Parser.Lex();
6096
6097
  // Validate that the LHS is allowed to be a variable (either it has not been
6098
  // used as a symbol, or it is an absolute symbol).
6099
874k
  Sym = Parser.getContext().lookupSymbol(Name);
6100
874k
  if (Sym) {
6101
    // Diagnose assignment to a label.
6102
    //
6103
    // FIXME: Diagnostics. Note the location of the definition as a label.
6104
    // FIXME: Diagnose assignment to protected identifier (e.g., register name).
6105
560k
    if (isSymbolUsedInExpression(Sym, Value))
6106
      //return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
6107
5.89k
      return true;
6108
554k
    else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
6109
554k
             !Sym->isVariable())
6110
2.08k
      ; // Allow redefinitions of undefined symbols only used in directives.
6111
552k
    else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
6112
507k
      ; // Allow redefinitions of variables that haven't yet been used.
6113
45.4k
    else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
6114
      //return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
6115
2.45k
      return true;
6116
42.9k
    else if (!Sym->isVariable())
6117
      //return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
6118
0
      return true;
6119
42.9k
    else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
6120
      //return Parser.Error(EqualLoc,
6121
      //                    "invalid reassignment of non-absolute variable '" +
6122
      //                        Name + "'");
6123
41.6k
      return true;
6124
560k
  } else if (Name == ".") {
6125
299k
    Parser.getStreamer().emitValueToOffset(Value, 0);
6126
299k
    return false;
6127
299k
  } else {
6128
14.6k
    if (Name.empty()) {
6129
530
        return true;
6130
530
    }
6131
14.1k
    Sym = Parser.getContext().getOrCreateSymbol(Name);
6132
14.1k
  }
6133
6134
524k
  Sym->setRedefinable(allow_redef);
6135
6136
524k
  return false;
6137
874k
}
6138
6139
} // namespace MCParserUtils
6140
} // namespace llvm_ks
6141
6142
/// \brief Create an MCAsmParser instance.
6143
MCAsmParser *llvm_ks::createMCAsmParser(SourceMgr &SM, MCContext &C,
6144
132k
                                     MCStreamer &Out, const MCAsmInfo &MAI) {
6145
132k
  return new AsmParser(SM, C, Out, MAI);
6146
132k
}