[MachO] Stop generating *coal* sections.
[oota-llvm.git] / lib / MC / MCParser / DarwinAsmParser.cpp
1 //===- DarwinAsmParser.cpp - Darwin (Mach-O) Assembly Parser --------------===//
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 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
11 #include "llvm/ADT/StringRef.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/ADT/Triple.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCObjectFileInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCSectionMachO.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/SourceMgr.h"
25 using namespace llvm;
26
27 namespace {
28
29 /// \brief Implementation of directive handling which is shared across all
30 /// Darwin targets.
31 class DarwinAsmParser : public MCAsmParserExtension {
32   template<bool (DarwinAsmParser::*HandlerMethod)(StringRef, SMLoc)>
33   void addDirectiveHandler(StringRef Directive) {
34     MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
35         this, HandleDirective<DarwinAsmParser, HandlerMethod>);
36     getParser().addDirectiveHandler(Directive, Handler);
37   }
38
39   bool parseSectionSwitch(const char *Segment, const char *Section,
40                           unsigned TAA = 0, unsigned ImplicitAlign = 0,
41                           unsigned StubSize = 0);
42
43 public:
44   DarwinAsmParser() {}
45
46   void Initialize(MCAsmParser &Parser) override {
47     // Call the base implementation.
48     this->MCAsmParserExtension::Initialize(Parser);
49
50     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDesc>(".desc");
51     addDirectiveHandler<&DarwinAsmParser::parseDirectiveIndirectSymbol>(
52       ".indirect_symbol");
53     addDirectiveHandler<&DarwinAsmParser::parseDirectiveLsym>(".lsym");
54     addDirectiveHandler<&DarwinAsmParser::parseDirectiveSubsectionsViaSymbols>(
55       ".subsections_via_symbols");
56     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDumpOrLoad>(".dump");
57     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDumpOrLoad>(".load");
58     addDirectiveHandler<&DarwinAsmParser::parseDirectiveSection>(".section");
59     addDirectiveHandler<&DarwinAsmParser::parseDirectivePushSection>(
60       ".pushsection");
61     addDirectiveHandler<&DarwinAsmParser::parseDirectivePopSection>(
62       ".popsection");
63     addDirectiveHandler<&DarwinAsmParser::parseDirectivePrevious>(".previous");
64     addDirectiveHandler<&DarwinAsmParser::parseDirectiveSecureLogUnique>(
65       ".secure_log_unique");
66     addDirectiveHandler<&DarwinAsmParser::parseDirectiveSecureLogReset>(
67       ".secure_log_reset");
68     addDirectiveHandler<&DarwinAsmParser::parseDirectiveTBSS>(".tbss");
69     addDirectiveHandler<&DarwinAsmParser::parseDirectiveZerofill>(".zerofill");
70
71     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDataRegion>(
72       ".data_region");
73     addDirectiveHandler<&DarwinAsmParser::parseDirectiveDataRegionEnd>(
74       ".end_data_region");
75
76     // Special section directives.
77     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveBss>(".bss");
78     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConst>(".const");
79     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConstData>(
80       ".const_data");
81     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveConstructor>(
82       ".constructor");
83     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveCString>(
84       ".cstring");
85     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveData>(".data");
86     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveDestructor>(
87       ".destructor");
88     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveDyld>(".dyld");
89     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveFVMLibInit0>(
90       ".fvmlib_init0");
91     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveFVMLibInit1>(
92       ".fvmlib_init1");
93     addDirectiveHandler<
94       &DarwinAsmParser::parseSectionDirectiveLazySymbolPointers>(
95         ".lazy_symbol_pointer");
96     addDirectiveHandler<&DarwinAsmParser::parseDirectiveLinkerOption>(
97       ".linker_option");
98     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral16>(
99       ".literal16");
100     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral4>(
101       ".literal4");
102     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveLiteral8>(
103       ".literal8");
104     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveModInitFunc>(
105       ".mod_init_func");
106     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveModTermFunc>(
107       ".mod_term_func");
108     addDirectiveHandler<
109       &DarwinAsmParser::parseSectionDirectiveNonLazySymbolPointers>(
110         ".non_lazy_symbol_pointer");
111     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCatClsMeth>(
112       ".objc_cat_cls_meth");
113     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCatInstMeth>(
114       ".objc_cat_inst_meth");
115     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCCategory>(
116       ".objc_category");
117     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClass>(
118       ".objc_class");
119     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClassNames>(
120       ".objc_class_names");
121     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClassVars>(
122       ".objc_class_vars");
123     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClsMeth>(
124       ".objc_cls_meth");
125     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCClsRefs>(
126       ".objc_cls_refs");
127     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCInstMeth>(
128       ".objc_inst_meth");
129     addDirectiveHandler<
130       &DarwinAsmParser::parseSectionDirectiveObjCInstanceVars>(
131         ".objc_instance_vars");
132     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCMessageRefs>(
133       ".objc_message_refs");
134     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCMetaClass>(
135       ".objc_meta_class");
136     addDirectiveHandler<
137       &DarwinAsmParser::parseSectionDirectiveObjCMethVarNames>(
138         ".objc_meth_var_names");
139     addDirectiveHandler<
140       &DarwinAsmParser::parseSectionDirectiveObjCMethVarTypes>(
141         ".objc_meth_var_types");
142     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCModuleInfo>(
143       ".objc_module_info");
144     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCProtocol>(
145       ".objc_protocol");
146     addDirectiveHandler<
147       &DarwinAsmParser::parseSectionDirectiveObjCSelectorStrs>(
148         ".objc_selector_strs");
149     addDirectiveHandler<
150       &DarwinAsmParser::parseSectionDirectiveObjCStringObject>(
151         ".objc_string_object");
152     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveObjCSymbols>(
153       ".objc_symbols");
154     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectivePICSymbolStub>(
155       ".picsymbol_stub");
156     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveStaticConst>(
157       ".static_const");
158     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveStaticData>(
159       ".static_data");
160     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveSymbolStub>(
161       ".symbol_stub");
162     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveTData>(".tdata");
163     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveText>(".text");
164     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveThreadInitFunc>(
165       ".thread_init_func");
166     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveTLV>(".tlv");
167
168     addDirectiveHandler<&DarwinAsmParser::parseSectionDirectiveIdent>(".ident");
169     addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(".ios_version_min");
170     addDirectiveHandler<&DarwinAsmParser::parseVersionMin>(
171       ".macosx_version_min");
172   }
173
174   bool parseDirectiveDesc(StringRef, SMLoc);
175   bool parseDirectiveIndirectSymbol(StringRef, SMLoc);
176   bool parseDirectiveDumpOrLoad(StringRef, SMLoc);
177   bool parseDirectiveLsym(StringRef, SMLoc);
178   bool parseDirectiveLinkerOption(StringRef, SMLoc);
179   bool parseDirectiveSection(StringRef, SMLoc);
180   bool parseDirectivePushSection(StringRef, SMLoc);
181   bool parseDirectivePopSection(StringRef, SMLoc);
182   bool parseDirectivePrevious(StringRef, SMLoc);
183   bool parseDirectiveSecureLogReset(StringRef, SMLoc);
184   bool parseDirectiveSecureLogUnique(StringRef, SMLoc);
185   bool parseDirectiveSubsectionsViaSymbols(StringRef, SMLoc);
186   bool parseDirectiveTBSS(StringRef, SMLoc);
187   bool parseDirectiveZerofill(StringRef, SMLoc);
188   bool parseDirectiveDataRegion(StringRef, SMLoc);
189   bool parseDirectiveDataRegionEnd(StringRef, SMLoc);
190
191   // Named Section Directive
192   bool parseSectionDirectiveBss(StringRef, SMLoc) {
193     return parseSectionSwitch("__DATA", "__bss");
194   }
195
196   bool parseSectionDirectiveConst(StringRef, SMLoc) {
197     return parseSectionSwitch("__TEXT", "__const");
198   }
199   bool parseSectionDirectiveStaticConst(StringRef, SMLoc) {
200     return parseSectionSwitch("__TEXT", "__static_const");
201   }
202   bool parseSectionDirectiveCString(StringRef, SMLoc) {
203     return parseSectionSwitch("__TEXT","__cstring",
204                               MachO::S_CSTRING_LITERALS);
205   }
206   bool parseSectionDirectiveLiteral4(StringRef, SMLoc) {
207     return parseSectionSwitch("__TEXT", "__literal4",
208                               MachO::S_4BYTE_LITERALS, 4);
209   }
210   bool parseSectionDirectiveLiteral8(StringRef, SMLoc) {
211     return parseSectionSwitch("__TEXT", "__literal8",
212                               MachO::S_8BYTE_LITERALS, 8);
213   }
214   bool parseSectionDirectiveLiteral16(StringRef, SMLoc) {
215     return parseSectionSwitch("__TEXT","__literal16",
216                               MachO::S_16BYTE_LITERALS, 16);
217   }
218   bool parseSectionDirectiveConstructor(StringRef, SMLoc) {
219     return parseSectionSwitch("__TEXT","__constructor");
220   }
221   bool parseSectionDirectiveDestructor(StringRef, SMLoc) {
222     return parseSectionSwitch("__TEXT","__destructor");
223   }
224   bool parseSectionDirectiveFVMLibInit0(StringRef, SMLoc) {
225     return parseSectionSwitch("__TEXT","__fvmlib_init0");
226   }
227   bool parseSectionDirectiveFVMLibInit1(StringRef, SMLoc) {
228     return parseSectionSwitch("__TEXT","__fvmlib_init1");
229   }
230   bool parseSectionDirectiveSymbolStub(StringRef, SMLoc) {
231     return parseSectionSwitch("__TEXT","__symbol_stub",
232                               MachO::S_SYMBOL_STUBS |
233                               MachO::S_ATTR_PURE_INSTRUCTIONS,
234                               // FIXME: Different on PPC and ARM.
235                               0, 16);
236   }
237   bool parseSectionDirectivePICSymbolStub(StringRef, SMLoc) {
238     return parseSectionSwitch("__TEXT","__picsymbol_stub",
239                               MachO::S_SYMBOL_STUBS |
240                               MachO::S_ATTR_PURE_INSTRUCTIONS, 0, 26);
241   }
242   bool parseSectionDirectiveData(StringRef, SMLoc) {
243     return parseSectionSwitch("__DATA", "__data");
244   }
245   bool parseSectionDirectiveStaticData(StringRef, SMLoc) {
246     return parseSectionSwitch("__DATA", "__static_data");
247   }
248   bool parseSectionDirectiveNonLazySymbolPointers(StringRef, SMLoc) {
249     return parseSectionSwitch("__DATA", "__nl_symbol_ptr",
250                               MachO::S_NON_LAZY_SYMBOL_POINTERS, 4);
251   }
252   bool parseSectionDirectiveLazySymbolPointers(StringRef, SMLoc) {
253     return parseSectionSwitch("__DATA", "__la_symbol_ptr",
254                               MachO::S_LAZY_SYMBOL_POINTERS, 4);
255   }
256   bool parseSectionDirectiveDyld(StringRef, SMLoc) {
257     return parseSectionSwitch("__DATA", "__dyld");
258   }
259   bool parseSectionDirectiveModInitFunc(StringRef, SMLoc) {
260     return parseSectionSwitch("__DATA", "__mod_init_func",
261                               MachO::S_MOD_INIT_FUNC_POINTERS, 4);
262   }
263   bool parseSectionDirectiveModTermFunc(StringRef, SMLoc) {
264     return parseSectionSwitch("__DATA", "__mod_term_func",
265                               MachO::S_MOD_TERM_FUNC_POINTERS, 4);
266   }
267   bool parseSectionDirectiveConstData(StringRef, SMLoc) {
268     return parseSectionSwitch("__DATA", "__const");
269   }
270   bool parseSectionDirectiveObjCClass(StringRef, SMLoc) {
271     return parseSectionSwitch("__OBJC", "__class",
272                               MachO::S_ATTR_NO_DEAD_STRIP);
273   }
274   bool parseSectionDirectiveObjCMetaClass(StringRef, SMLoc) {
275     return parseSectionSwitch("__OBJC", "__meta_class",
276                               MachO::S_ATTR_NO_DEAD_STRIP);
277   }
278   bool parseSectionDirectiveObjCCatClsMeth(StringRef, SMLoc) {
279     return parseSectionSwitch("__OBJC", "__cat_cls_meth",
280                               MachO::S_ATTR_NO_DEAD_STRIP);
281   }
282   bool parseSectionDirectiveObjCCatInstMeth(StringRef, SMLoc) {
283     return parseSectionSwitch("__OBJC", "__cat_inst_meth",
284                               MachO::S_ATTR_NO_DEAD_STRIP);
285   }
286   bool parseSectionDirectiveObjCProtocol(StringRef, SMLoc) {
287     return parseSectionSwitch("__OBJC", "__protocol",
288                               MachO::S_ATTR_NO_DEAD_STRIP);
289   }
290   bool parseSectionDirectiveObjCStringObject(StringRef, SMLoc) {
291     return parseSectionSwitch("__OBJC", "__string_object",
292                               MachO::S_ATTR_NO_DEAD_STRIP);
293   }
294   bool parseSectionDirectiveObjCClsMeth(StringRef, SMLoc) {
295     return parseSectionSwitch("__OBJC", "__cls_meth",
296                               MachO::S_ATTR_NO_DEAD_STRIP);
297   }
298   bool parseSectionDirectiveObjCInstMeth(StringRef, SMLoc) {
299     return parseSectionSwitch("__OBJC", "__inst_meth",
300                               MachO::S_ATTR_NO_DEAD_STRIP);
301   }
302   bool parseSectionDirectiveObjCClsRefs(StringRef, SMLoc) {
303     return parseSectionSwitch("__OBJC", "__cls_refs",
304                               MachO::S_ATTR_NO_DEAD_STRIP |
305                               MachO::S_LITERAL_POINTERS, 4);
306   }
307   bool parseSectionDirectiveObjCMessageRefs(StringRef, SMLoc) {
308     return parseSectionSwitch("__OBJC", "__message_refs",
309                               MachO::S_ATTR_NO_DEAD_STRIP |
310                               MachO::S_LITERAL_POINTERS, 4);
311   }
312   bool parseSectionDirectiveObjCSymbols(StringRef, SMLoc) {
313     return parseSectionSwitch("__OBJC", "__symbols",
314                               MachO::S_ATTR_NO_DEAD_STRIP);
315   }
316   bool parseSectionDirectiveObjCCategory(StringRef, SMLoc) {
317     return parseSectionSwitch("__OBJC", "__category",
318                               MachO::S_ATTR_NO_DEAD_STRIP);
319   }
320   bool parseSectionDirectiveObjCClassVars(StringRef, SMLoc) {
321     return parseSectionSwitch("__OBJC", "__class_vars",
322                               MachO::S_ATTR_NO_DEAD_STRIP);
323   }
324   bool parseSectionDirectiveObjCInstanceVars(StringRef, SMLoc) {
325     return parseSectionSwitch("__OBJC", "__instance_vars",
326                               MachO::S_ATTR_NO_DEAD_STRIP);
327   }
328   bool parseSectionDirectiveObjCModuleInfo(StringRef, SMLoc) {
329     return parseSectionSwitch("__OBJC", "__module_info",
330                               MachO::S_ATTR_NO_DEAD_STRIP);
331   }
332   bool parseSectionDirectiveObjCClassNames(StringRef, SMLoc) {
333     return parseSectionSwitch("__TEXT", "__cstring",
334                               MachO::S_CSTRING_LITERALS);
335   }
336   bool parseSectionDirectiveObjCMethVarTypes(StringRef, SMLoc) {
337     return parseSectionSwitch("__TEXT", "__cstring",
338                               MachO::S_CSTRING_LITERALS);
339   }
340   bool parseSectionDirectiveObjCMethVarNames(StringRef, SMLoc) {
341     return parseSectionSwitch("__TEXT", "__cstring",
342                               MachO::S_CSTRING_LITERALS);
343   }
344   bool parseSectionDirectiveObjCSelectorStrs(StringRef, SMLoc) {
345     return parseSectionSwitch("__OBJC", "__selector_strs",
346                               MachO::S_CSTRING_LITERALS);
347   }
348   bool parseSectionDirectiveTData(StringRef, SMLoc) {
349     return parseSectionSwitch("__DATA", "__thread_data",
350                               MachO::S_THREAD_LOCAL_REGULAR);
351   }
352   bool parseSectionDirectiveText(StringRef, SMLoc) {
353     return parseSectionSwitch("__TEXT", "__text",
354                               MachO::S_ATTR_PURE_INSTRUCTIONS);
355   }
356   bool parseSectionDirectiveTLV(StringRef, SMLoc) {
357     return parseSectionSwitch("__DATA", "__thread_vars",
358                               MachO::S_THREAD_LOCAL_VARIABLES);
359   }
360   bool parseSectionDirectiveIdent(StringRef, SMLoc) {
361     // Darwin silently ignores the .ident directive.
362     getParser().eatToEndOfStatement();
363     return false;
364   }
365   bool parseSectionDirectiveThreadInitFunc(StringRef, SMLoc) {
366     return parseSectionSwitch("__DATA", "__thread_init",
367                          MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS);
368   }
369   bool parseVersionMin(StringRef, SMLoc);
370
371 };
372
373 } // end anonymous namespace
374
375 bool DarwinAsmParser::parseSectionSwitch(const char *Segment,
376                                          const char *Section,
377                                          unsigned TAA, unsigned Align,
378                                          unsigned StubSize) {
379   if (getLexer().isNot(AsmToken::EndOfStatement))
380     return TokError("unexpected token in section switching directive");
381   Lex();
382
383   // FIXME: Arch specific.
384   bool isText = TAA & MachO::S_ATTR_PURE_INSTRUCTIONS;
385   getStreamer().SwitchSection(getContext().getMachOSection(
386                                 Segment, Section, TAA, StubSize,
387                                 isText ? SectionKind::getText()
388                                        : SectionKind::getDataRel()));
389
390   // Set the implicit alignment, if any.
391   //
392   // FIXME: This isn't really what 'as' does; I think it just uses the implicit
393   // alignment on the section (e.g., if one manually inserts bytes into the
394   // section, then just issuing the section switch directive will not realign
395   // the section. However, this is arguably more reasonable behavior, and there
396   // is no good reason for someone to intentionally emit incorrectly sized
397   // values into the implicitly aligned sections.
398   if (Align)
399     getStreamer().EmitValueToAlignment(Align);
400
401   return false;
402 }
403
404 /// parseDirectiveDesc
405 ///  ::= .desc identifier , expression
406 bool DarwinAsmParser::parseDirectiveDesc(StringRef, SMLoc) {
407   StringRef Name;
408   if (getParser().parseIdentifier(Name))
409     return TokError("expected identifier in directive");
410
411   // Handle the identifier as the key symbol.
412   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
413
414   if (getLexer().isNot(AsmToken::Comma))
415     return TokError("unexpected token in '.desc' directive");
416   Lex();
417
418   int64_t DescValue;
419   if (getParser().parseAbsoluteExpression(DescValue))
420     return true;
421
422   if (getLexer().isNot(AsmToken::EndOfStatement))
423     return TokError("unexpected token in '.desc' directive");
424
425   Lex();
426
427   // Set the n_desc field of this Symbol to this DescValue
428   getStreamer().EmitSymbolDesc(Sym, DescValue);
429
430   return false;
431 }
432
433 /// parseDirectiveIndirectSymbol
434 ///  ::= .indirect_symbol identifier
435 bool DarwinAsmParser::parseDirectiveIndirectSymbol(StringRef, SMLoc Loc) {
436   const MCSectionMachO *Current = static_cast<const MCSectionMachO*>(
437                                        getStreamer().getCurrentSection().first);
438   MachO::SectionType SectionType = Current->getType();
439   if (SectionType != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
440       SectionType != MachO::S_LAZY_SYMBOL_POINTERS &&
441       SectionType != MachO::S_SYMBOL_STUBS)
442     return Error(Loc, "indirect symbol not in a symbol pointer or stub "
443                       "section");
444
445   StringRef Name;
446   if (getParser().parseIdentifier(Name))
447     return TokError("expected identifier in .indirect_symbol directive");
448
449   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
450
451   // Assembler local symbols don't make any sense here. Complain loudly.
452   if (Sym->isTemporary())
453     return TokError("non-local symbol required in directive");
454
455   if (!getStreamer().EmitSymbolAttribute(Sym, MCSA_IndirectSymbol))
456     return TokError("unable to emit indirect symbol attribute for: " + Name);
457
458   if (getLexer().isNot(AsmToken::EndOfStatement))
459     return TokError("unexpected token in '.indirect_symbol' directive");
460
461   Lex();
462
463   return false;
464 }
465
466 /// parseDirectiveDumpOrLoad
467 ///  ::= ( .dump | .load ) "filename"
468 bool DarwinAsmParser::parseDirectiveDumpOrLoad(StringRef Directive,
469                                                SMLoc IDLoc) {
470   bool IsDump = Directive == ".dump";
471   if (getLexer().isNot(AsmToken::String))
472     return TokError("expected string in '.dump' or '.load' directive");
473
474   Lex();
475
476   if (getLexer().isNot(AsmToken::EndOfStatement))
477     return TokError("unexpected token in '.dump' or '.load' directive");
478
479   Lex();
480
481   // FIXME: If/when .dump and .load are implemented they will be done in the
482   // the assembly parser and not have any need for an MCStreamer API.
483   if (IsDump)
484     return Warning(IDLoc, "ignoring directive .dump for now");
485   else
486     return Warning(IDLoc, "ignoring directive .load for now");
487 }
488
489 /// ParseDirectiveLinkerOption
490 ///  ::= .linker_option "string" ( , "string" )*
491 bool DarwinAsmParser::parseDirectiveLinkerOption(StringRef IDVal, SMLoc) {
492   SmallVector<std::string, 4> Args;
493   for (;;) {
494     if (getLexer().isNot(AsmToken::String))
495       return TokError("expected string in '" + Twine(IDVal) + "' directive");
496
497     std::string Data;
498     if (getParser().parseEscapedString(Data))
499       return true;
500
501     Args.push_back(Data);
502
503     Lex();
504     if (getLexer().is(AsmToken::EndOfStatement))
505       break;
506
507     if (getLexer().isNot(AsmToken::Comma))
508       return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
509     Lex();
510   }
511
512   getStreamer().EmitLinkerOptions(Args);
513   return false;
514 }
515
516 /// parseDirectiveLsym
517 ///  ::= .lsym identifier , expression
518 bool DarwinAsmParser::parseDirectiveLsym(StringRef, SMLoc) {
519   StringRef Name;
520   if (getParser().parseIdentifier(Name))
521     return TokError("expected identifier in directive");
522
523   // Handle the identifier as the key symbol.
524   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
525
526   if (getLexer().isNot(AsmToken::Comma))
527     return TokError("unexpected token in '.lsym' directive");
528   Lex();
529
530   const MCExpr *Value;
531   if (getParser().parseExpression(Value))
532     return true;
533
534   if (getLexer().isNot(AsmToken::EndOfStatement))
535     return TokError("unexpected token in '.lsym' directive");
536
537   Lex();
538
539   // We don't currently support this directive.
540   //
541   // FIXME: Diagnostic location!
542   (void) Sym;
543   return TokError("directive '.lsym' is unsupported");
544 }
545
546 /// parseDirectiveSection:
547 ///   ::= .section identifier (',' identifier)*
548 bool DarwinAsmParser::parseDirectiveSection(StringRef, SMLoc) {
549   SMLoc Loc = getLexer().getLoc();
550
551   StringRef SectionName;
552   if (getParser().parseIdentifier(SectionName))
553     return Error(Loc, "expected identifier after '.section' directive");
554
555   // Verify there is a following comma.
556   if (!getLexer().is(AsmToken::Comma))
557     return TokError("unexpected token in '.section' directive");
558
559   std::string SectionSpec = SectionName;
560   SectionSpec += ",";
561
562   // Add all the tokens until the end of the line, ParseSectionSpecifier will
563   // handle this.
564   StringRef EOL = getLexer().LexUntilEndOfStatement();
565   SectionSpec.append(EOL.begin(), EOL.end());
566
567   Lex();
568   if (getLexer().isNot(AsmToken::EndOfStatement))
569     return TokError("unexpected token in '.section' directive");
570   Lex();
571
572
573   StringRef Segment, Section;
574   unsigned StubSize;
575   unsigned TAA;
576   bool TAAParsed;
577   std::string ErrorStr =
578     MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
579                                           TAA, TAAParsed, StubSize);
580
581   if (!ErrorStr.empty())
582     return Error(Loc, ErrorStr.c_str());
583
584   // Issue a warning if the target is not powerpc and Section is a *coal* section.
585   Triple TT = getParser().getContext().getObjectFileInfo()->getTargetTriple();
586   Triple::ArchType ArchTy = TT.getArch();
587
588   if (ArchTy != Triple::ppc && ArchTy != Triple::ppc64) {
589     StringRef NonCoalSection = StringSwitch<StringRef>(Section)
590                                    .Case("__textcoal_nt", "__text")
591                                    .Case("__const_coal", "__const")
592                                    .Case("__datacoal_nt", "__data")
593                                    .Default(Section);
594
595     if (!Section.equals(NonCoalSection)) {
596       StringRef SectionVal(Loc.getPointer());
597       size_t B = SectionVal.find(',') + 1, E = SectionVal.find(',', B);
598       SMLoc BLoc = SMLoc::getFromPointer(SectionVal.data() + B);
599       SMLoc ELoc = SMLoc::getFromPointer(SectionVal.data() + E);
600       getParser().Warning(Loc, "section \"" + Section + "\" is deprecated",
601                           SMRange(BLoc, ELoc));
602       getParser().Note(Loc, "change section name to \"" + NonCoalSection +
603                        "\"", SMRange(BLoc, ELoc));
604     }
605   }
606
607   // FIXME: Arch specific.
608   bool isText = Segment == "__TEXT";  // FIXME: Hack.
609   getStreamer().SwitchSection(getContext().getMachOSection(
610                                 Segment, Section, TAA, StubSize,
611                                 isText ? SectionKind::getText()
612                                 : SectionKind::getDataRel()));
613   return false;
614 }
615
616 /// ParseDirectivePushSection:
617 ///   ::= .pushsection identifier (',' identifier)*
618 bool DarwinAsmParser::parseDirectivePushSection(StringRef S, SMLoc Loc) {
619   getStreamer().PushSection();
620
621   if (parseDirectiveSection(S, Loc)) {
622     getStreamer().PopSection();
623     return true;
624   }
625
626   return false;
627 }
628
629 /// ParseDirectivePopSection:
630 ///   ::= .popsection
631 bool DarwinAsmParser::parseDirectivePopSection(StringRef, SMLoc) {
632   if (!getStreamer().PopSection())
633     return TokError(".popsection without corresponding .pushsection");
634   return false;
635 }
636
637 /// ParseDirectivePrevious:
638 ///   ::= .previous
639 bool DarwinAsmParser::parseDirectivePrevious(StringRef DirName, SMLoc) {
640   MCSectionSubPair PreviousSection = getStreamer().getPreviousSection();
641   if (!PreviousSection.first)
642     return TokError(".previous without corresponding .section");
643   getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second);
644   return false;
645 }
646
647 /// ParseDirectiveSecureLogUnique
648 ///  ::= .secure_log_unique ... message ...
649 bool DarwinAsmParser::parseDirectiveSecureLogUnique(StringRef, SMLoc IDLoc) {
650   StringRef LogMessage = getParser().parseStringToEndOfStatement();
651   if (getLexer().isNot(AsmToken::EndOfStatement))
652     return TokError("unexpected token in '.secure_log_unique' directive");
653
654   if (getContext().getSecureLogUsed())
655     return Error(IDLoc, ".secure_log_unique specified multiple times");
656
657   // Get the secure log path.
658   const char *SecureLogFile = getContext().getSecureLogFile();
659   if (!SecureLogFile)
660     return Error(IDLoc, ".secure_log_unique used but AS_SECURE_LOG_FILE "
661                  "environment variable unset.");
662
663   // Open the secure log file if we haven't already.
664   raw_ostream *OS = getContext().getSecureLog();
665   if (!OS) {
666     std::error_code EC;
667     OS = new raw_fd_ostream(SecureLogFile, EC,
668                             sys::fs::F_Append | sys::fs::F_Text);
669     if (EC) {
670        delete OS;
671        return Error(IDLoc, Twine("can't open secure log file: ") +
672                                SecureLogFile + " (" + EC.message() + ")");
673     }
674     getContext().setSecureLog(OS);
675   }
676
677   // Write the message.
678   unsigned CurBuf = getSourceManager().FindBufferContainingLoc(IDLoc);
679   *OS << getSourceManager().getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
680       << ":" << getSourceManager().FindLineNumber(IDLoc, CurBuf) << ":"
681       << LogMessage + "\n";
682
683   getContext().setSecureLogUsed(true);
684
685   return false;
686 }
687
688 /// ParseDirectiveSecureLogReset
689 ///  ::= .secure_log_reset
690 bool DarwinAsmParser::parseDirectiveSecureLogReset(StringRef, SMLoc IDLoc) {
691   if (getLexer().isNot(AsmToken::EndOfStatement))
692     return TokError("unexpected token in '.secure_log_reset' directive");
693
694   Lex();
695
696   getContext().setSecureLogUsed(false);
697
698   return false;
699 }
700
701 /// parseDirectiveSubsectionsViaSymbols
702 ///  ::= .subsections_via_symbols
703 bool DarwinAsmParser::parseDirectiveSubsectionsViaSymbols(StringRef, SMLoc) {
704   if (getLexer().isNot(AsmToken::EndOfStatement))
705     return TokError("unexpected token in '.subsections_via_symbols' directive");
706
707   Lex();
708
709   getStreamer().EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
710
711   return false;
712 }
713
714 /// ParseDirectiveTBSS
715 ///  ::= .tbss identifier, size, align
716 bool DarwinAsmParser::parseDirectiveTBSS(StringRef, SMLoc) {
717   SMLoc IDLoc = getLexer().getLoc();
718   StringRef Name;
719   if (getParser().parseIdentifier(Name))
720     return TokError("expected identifier in directive");
721
722   // Handle the identifier as the key symbol.
723   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
724
725   if (getLexer().isNot(AsmToken::Comma))
726     return TokError("unexpected token in directive");
727   Lex();
728
729   int64_t Size;
730   SMLoc SizeLoc = getLexer().getLoc();
731   if (getParser().parseAbsoluteExpression(Size))
732     return true;
733
734   int64_t Pow2Alignment = 0;
735   SMLoc Pow2AlignmentLoc;
736   if (getLexer().is(AsmToken::Comma)) {
737     Lex();
738     Pow2AlignmentLoc = getLexer().getLoc();
739     if (getParser().parseAbsoluteExpression(Pow2Alignment))
740       return true;
741   }
742
743   if (getLexer().isNot(AsmToken::EndOfStatement))
744     return TokError("unexpected token in '.tbss' directive");
745
746   Lex();
747
748   if (Size < 0)
749     return Error(SizeLoc, "invalid '.tbss' directive size, can't be less than"
750                  "zero");
751
752   // FIXME: Diagnose overflow.
753   if (Pow2Alignment < 0)
754     return Error(Pow2AlignmentLoc, "invalid '.tbss' alignment, can't be less"
755                  "than zero");
756
757   if (!Sym->isUndefined())
758     return Error(IDLoc, "invalid symbol redefinition");
759
760   getStreamer().EmitTBSSSymbol(getContext().getMachOSection(
761                                  "__DATA", "__thread_bss",
762                                  MachO::S_THREAD_LOCAL_ZEROFILL,
763                                  0, SectionKind::getThreadBSS()),
764                                Sym, Size, 1 << Pow2Alignment);
765
766   return false;
767 }
768
769 /// ParseDirectiveZerofill
770 ///  ::= .zerofill segname , sectname [, identifier , size_expression [
771 ///      , align_expression ]]
772 bool DarwinAsmParser::parseDirectiveZerofill(StringRef, SMLoc) {
773   StringRef Segment;
774   if (getParser().parseIdentifier(Segment))
775     return TokError("expected segment name after '.zerofill' directive");
776
777   if (getLexer().isNot(AsmToken::Comma))
778     return TokError("unexpected token in directive");
779   Lex();
780
781   StringRef Section;
782   if (getParser().parseIdentifier(Section))
783     return TokError("expected section name after comma in '.zerofill' "
784                     "directive");
785
786   // If this is the end of the line all that was wanted was to create the
787   // the section but with no symbol.
788   if (getLexer().is(AsmToken::EndOfStatement)) {
789     // Create the zerofill section but no symbol
790     getStreamer().EmitZerofill(getContext().getMachOSection(
791                                  Segment, Section, MachO::S_ZEROFILL,
792                                  0, SectionKind::getBSS()));
793     return false;
794   }
795
796   if (getLexer().isNot(AsmToken::Comma))
797     return TokError("unexpected token in directive");
798   Lex();
799
800   SMLoc IDLoc = getLexer().getLoc();
801   StringRef IDStr;
802   if (getParser().parseIdentifier(IDStr))
803     return TokError("expected identifier in directive");
804
805   // handle the identifier as the key symbol.
806   MCSymbol *Sym = getContext().getOrCreateSymbol(IDStr);
807
808   if (getLexer().isNot(AsmToken::Comma))
809     return TokError("unexpected token in directive");
810   Lex();
811
812   int64_t Size;
813   SMLoc SizeLoc = getLexer().getLoc();
814   if (getParser().parseAbsoluteExpression(Size))
815     return true;
816
817   int64_t Pow2Alignment = 0;
818   SMLoc Pow2AlignmentLoc;
819   if (getLexer().is(AsmToken::Comma)) {
820     Lex();
821     Pow2AlignmentLoc = getLexer().getLoc();
822     if (getParser().parseAbsoluteExpression(Pow2Alignment))
823       return true;
824   }
825
826   if (getLexer().isNot(AsmToken::EndOfStatement))
827     return TokError("unexpected token in '.zerofill' directive");
828
829   Lex();
830
831   if (Size < 0)
832     return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
833                  "than zero");
834
835   // NOTE: The alignment in the directive is a power of 2 value, the assembler
836   // may internally end up wanting an alignment in bytes.
837   // FIXME: Diagnose overflow.
838   if (Pow2Alignment < 0)
839     return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
840                  "can't be less than zero");
841
842   if (!Sym->isUndefined())
843     return Error(IDLoc, "invalid symbol redefinition");
844
845   // Create the zerofill Symbol with Size and Pow2Alignment
846   //
847   // FIXME: Arch specific.
848   getStreamer().EmitZerofill(getContext().getMachOSection(
849                                Segment, Section, MachO::S_ZEROFILL,
850                                0, SectionKind::getBSS()),
851                              Sym, Size, 1 << Pow2Alignment);
852
853   return false;
854 }
855
856 /// ParseDirectiveDataRegion
857 ///  ::= .data_region [ ( jt8 | jt16 | jt32 ) ]
858 bool DarwinAsmParser::parseDirectiveDataRegion(StringRef, SMLoc) {
859   if (getLexer().is(AsmToken::EndOfStatement)) {
860     Lex();
861     getStreamer().EmitDataRegion(MCDR_DataRegion);
862     return false;
863   }
864   StringRef RegionType;
865   SMLoc Loc = getParser().getTok().getLoc();
866   if (getParser().parseIdentifier(RegionType))
867     return TokError("expected region type after '.data_region' directive");
868   int Kind = StringSwitch<int>(RegionType)
869     .Case("jt8", MCDR_DataRegionJT8)
870     .Case("jt16", MCDR_DataRegionJT16)
871     .Case("jt32", MCDR_DataRegionJT32)
872     .Default(-1);
873   if (Kind == -1)
874     return Error(Loc, "unknown region type in '.data_region' directive");
875   Lex();
876
877   getStreamer().EmitDataRegion((MCDataRegionType)Kind);
878   return false;
879 }
880
881 /// ParseDirectiveDataRegionEnd
882 ///  ::= .end_data_region
883 bool DarwinAsmParser::parseDirectiveDataRegionEnd(StringRef, SMLoc) {
884   if (getLexer().isNot(AsmToken::EndOfStatement))
885     return TokError("unexpected token in '.end_data_region' directive");
886
887   Lex();
888   getStreamer().EmitDataRegion(MCDR_DataRegionEnd);
889   return false;
890 }
891
892 /// parseVersionMin
893 ///  ::= .ios_version_min major,minor[,update]
894 ///  ::= .macosx_version_min major,minor[,update]
895 bool DarwinAsmParser::parseVersionMin(StringRef Directive, SMLoc) {
896   int64_t Major = 0, Minor = 0, Update = 0;
897   int Kind = StringSwitch<int>(Directive)
898     .Case(".ios_version_min", MCVM_IOSVersionMin)
899     .Case(".macosx_version_min", MCVM_OSXVersionMin);
900   // Get the major version number.
901   if (getLexer().isNot(AsmToken::Integer))
902     return TokError("invalid OS major version number");
903   Major = getLexer().getTok().getIntVal();
904   if (Major > 65535 || Major <= 0)
905     return TokError("invalid OS major version number");
906   Lex();
907   if (getLexer().isNot(AsmToken::Comma))
908     return TokError("minor OS version number required, comma expected");
909   Lex();
910   // Get the minor version number.
911   if (getLexer().isNot(AsmToken::Integer))
912     return TokError("invalid OS minor version number");
913   Minor = getLexer().getTok().getIntVal();
914   if (Minor > 255 || Minor < 0)
915     return TokError("invalid OS minor version number");
916   Lex();
917   // Get the update level, if specified
918   if (getLexer().isNot(AsmToken::EndOfStatement)) {
919     if (getLexer().isNot(AsmToken::Comma))
920       return TokError("invalid update specifier, comma expected");
921     Lex();
922     if (getLexer().isNot(AsmToken::Integer))
923       return TokError("invalid OS update number");
924     Update = getLexer().getTok().getIntVal();
925   if (Update > 255 || Update < 0)
926     return TokError("invalid OS update number");
927     Lex();
928   }
929
930   // We've parsed a correct version specifier, so send it to the streamer.
931   getStreamer().EmitVersionMin((MCVersionMinType)Kind, Major, Minor, Update);
932
933   return false;
934 }
935
936 namespace llvm {
937
938 MCAsmParserExtension *createDarwinAsmParser() {
939   return new DarwinAsmParser;
940 }
941
942 } // end llvm namespace