1a2e1f85e8109d69d94480aace3d6a42f42f3f7e
[oota-llvm.git] / lib / AsmParser / LLParser.cpp
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
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 file defines the parser class for .ll files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLParser.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/SaveAndRestore.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33
34 static std::string getTypeString(Type *T) {
35   std::string Result;
36   raw_string_ostream Tmp(Result);
37   Tmp << *T;
38   return Tmp.str();
39 }
40
41 /// Run: module ::= toplevelentity*
42 bool LLParser::Run() {
43   // Prime the lexer.
44   Lex.Lex();
45
46   return ParseTopLevelEntities() ||
47          ValidateEndOfModule();
48 }
49
50 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
51 /// module.
52 bool LLParser::ValidateEndOfModule() {
53   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
54     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
55
56   // Handle any function attribute group forward references.
57   for (std::map<Value*, std::vector<unsigned> >::iterator
58          I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
59          I != E; ++I) {
60     Value *V = I->first;
61     std::vector<unsigned> &Vec = I->second;
62     AttrBuilder B;
63
64     for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
65          VI != VE; ++VI)
66       B.merge(NumberedAttrBuilders[*VI]);
67
68     if (Function *Fn = dyn_cast<Function>(V)) {
69       AttributeSet AS = Fn->getAttributes();
70       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
71       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
72                                AS.getFnAttributes());
73
74       FnAttrs.merge(B);
75
76       // If the alignment was parsed as an attribute, move to the alignment
77       // field.
78       if (FnAttrs.hasAlignmentAttr()) {
79         Fn->setAlignment(FnAttrs.getAlignment());
80         FnAttrs.removeAttribute(Attribute::Alignment);
81       }
82
83       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
84                             AttributeSet::get(Context,
85                                               AttributeSet::FunctionIndex,
86                                               FnAttrs));
87       Fn->setAttributes(AS);
88     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
89       AttributeSet AS = CI->getAttributes();
90       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
91       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
92                                AS.getFnAttributes());
93       FnAttrs.merge(B);
94       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
95                             AttributeSet::get(Context,
96                                               AttributeSet::FunctionIndex,
97                                               FnAttrs));
98       CI->setAttributes(AS);
99     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
100       AttributeSet AS = II->getAttributes();
101       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
102       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
103                                AS.getFnAttributes());
104       FnAttrs.merge(B);
105       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
106                             AttributeSet::get(Context,
107                                               AttributeSet::FunctionIndex,
108                                               FnAttrs));
109       II->setAttributes(AS);
110     } else {
111       llvm_unreachable("invalid object with forward attribute group reference");
112     }
113   }
114
115   // If there are entries in ForwardRefBlockAddresses at this point, the
116   // function was never defined.
117   if (!ForwardRefBlockAddresses.empty())
118     return Error(ForwardRefBlockAddresses.begin()->first.Loc,
119                  "expected function name in blockaddress");
120
121   for (const auto &NT : NumberedTypes)
122     if (NT.second.second.isValid())
123       return Error(NT.second.second,
124                    "use of undefined type '%" + Twine(NT.first) + "'");
125
126   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
127        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
128     if (I->second.second.isValid())
129       return Error(I->second.second,
130                    "use of undefined type named '" + I->getKey() + "'");
131
132   if (!ForwardRefComdats.empty())
133     return Error(ForwardRefComdats.begin()->second,
134                  "use of undefined comdat '$" +
135                      ForwardRefComdats.begin()->first + "'");
136
137   if (!ForwardRefVals.empty())
138     return Error(ForwardRefVals.begin()->second.second,
139                  "use of undefined value '@" + ForwardRefVals.begin()->first +
140                  "'");
141
142   if (!ForwardRefValIDs.empty())
143     return Error(ForwardRefValIDs.begin()->second.second,
144                  "use of undefined value '@" +
145                  Twine(ForwardRefValIDs.begin()->first) + "'");
146
147   if (!ForwardRefMDNodes.empty())
148     return Error(ForwardRefMDNodes.begin()->second.second,
149                  "use of undefined metadata '!" +
150                  Twine(ForwardRefMDNodes.begin()->first) + "'");
151
152   // Resolve metadata cycles.
153   for (auto &N : NumberedMetadata) {
154     if (N.second && !N.second->isResolved())
155       N.second->resolveCycles();
156   }
157
158   // Look for intrinsic functions and CallInst that need to be upgraded
159   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
160     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
161
162   UpgradeDebugInfo(*M);
163
164   return false;
165 }
166
167 //===----------------------------------------------------------------------===//
168 // Top-Level Entities
169 //===----------------------------------------------------------------------===//
170
171 bool LLParser::ParseTopLevelEntities() {
172   while (1) {
173     switch (Lex.getKind()) {
174     default:         return TokError("expected top-level entity");
175     case lltok::Eof: return false;
176     case lltok::kw_declare: if (ParseDeclare()) return true; break;
177     case lltok::kw_define:  if (ParseDefine()) return true; break;
178     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
179     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
180     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
181     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
182     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
183     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
184     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
185     case lltok::ComdatVar:  if (parseComdat()) return true; break;
186     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
187     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
188
189     // The Global variable production with no name can have many different
190     // optional leading prefixes, the production is:
191     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
192     //               OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
193     //               ('constant'|'global') ...
194     case lltok::kw_private:             // OptionalLinkage
195     case lltok::kw_internal:            // OptionalLinkage
196     case lltok::kw_weak:                // OptionalLinkage
197     case lltok::kw_weak_odr:            // OptionalLinkage
198     case lltok::kw_linkonce:            // OptionalLinkage
199     case lltok::kw_linkonce_odr:        // OptionalLinkage
200     case lltok::kw_appending:           // OptionalLinkage
201     case lltok::kw_common:              // OptionalLinkage
202     case lltok::kw_extern_weak:         // OptionalLinkage
203     case lltok::kw_external:            // OptionalLinkage
204     case lltok::kw_default:             // OptionalVisibility
205     case lltok::kw_hidden:              // OptionalVisibility
206     case lltok::kw_protected:           // OptionalVisibility
207     case lltok::kw_dllimport:           // OptionalDLLStorageClass
208     case lltok::kw_dllexport:           // OptionalDLLStorageClass
209     case lltok::kw_thread_local:        // OptionalThreadLocal
210     case lltok::kw_addrspace:           // OptionalAddrSpace
211     case lltok::kw_constant:            // GlobalType
212     case lltok::kw_global: {            // GlobalType
213       unsigned Linkage, Visibility, DLLStorageClass;
214       bool UnnamedAddr;
215       GlobalVariable::ThreadLocalMode TLM;
216       bool HasLinkage;
217       if (ParseOptionalLinkage(Linkage, HasLinkage) ||
218           ParseOptionalVisibility(Visibility) ||
219           ParseOptionalDLLStorageClass(DLLStorageClass) ||
220           ParseOptionalThreadLocal(TLM) ||
221           parseOptionalUnnamedAddr(UnnamedAddr) ||
222           ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
223                       DLLStorageClass, TLM, UnnamedAddr))
224         return true;
225       break;
226     }
227
228     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
229     case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
230     case lltok::kw_uselistorder_bb:
231                                  if (ParseUseListOrderBB()) return true; break;
232     }
233   }
234 }
235
236
237 /// toplevelentity
238 ///   ::= 'module' 'asm' STRINGCONSTANT
239 bool LLParser::ParseModuleAsm() {
240   assert(Lex.getKind() == lltok::kw_module);
241   Lex.Lex();
242
243   std::string AsmStr;
244   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
245       ParseStringConstant(AsmStr)) return true;
246
247   M->appendModuleInlineAsm(AsmStr);
248   return false;
249 }
250
251 /// toplevelentity
252 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
253 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
254 bool LLParser::ParseTargetDefinition() {
255   assert(Lex.getKind() == lltok::kw_target);
256   std::string Str;
257   switch (Lex.Lex()) {
258   default: return TokError("unknown target property");
259   case lltok::kw_triple:
260     Lex.Lex();
261     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
262         ParseStringConstant(Str))
263       return true;
264     M->setTargetTriple(Str);
265     return false;
266   case lltok::kw_datalayout:
267     Lex.Lex();
268     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
269         ParseStringConstant(Str))
270       return true;
271     M->setDataLayout(Str);
272     return false;
273   }
274 }
275
276 /// toplevelentity
277 ///   ::= 'deplibs' '=' '[' ']'
278 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
279 /// FIXME: Remove in 4.0. Currently parse, but ignore.
280 bool LLParser::ParseDepLibs() {
281   assert(Lex.getKind() == lltok::kw_deplibs);
282   Lex.Lex();
283   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
284       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
285     return true;
286
287   if (EatIfPresent(lltok::rsquare))
288     return false;
289
290   do {
291     std::string Str;
292     if (ParseStringConstant(Str)) return true;
293   } while (EatIfPresent(lltok::comma));
294
295   return ParseToken(lltok::rsquare, "expected ']' at end of list");
296 }
297
298 /// ParseUnnamedType:
299 ///   ::= LocalVarID '=' 'type' type
300 bool LLParser::ParseUnnamedType() {
301   LocTy TypeLoc = Lex.getLoc();
302   unsigned TypeID = Lex.getUIntVal();
303   Lex.Lex(); // eat LocalVarID;
304
305   if (ParseToken(lltok::equal, "expected '=' after name") ||
306       ParseToken(lltok::kw_type, "expected 'type' after '='"))
307     return true;
308
309   Type *Result = nullptr;
310   if (ParseStructDefinition(TypeLoc, "",
311                             NumberedTypes[TypeID], Result)) return true;
312
313   if (!isa<StructType>(Result)) {
314     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
315     if (Entry.first)
316       return Error(TypeLoc, "non-struct types may not be recursive");
317     Entry.first = Result;
318     Entry.second = SMLoc();
319   }
320
321   return false;
322 }
323
324
325 /// toplevelentity
326 ///   ::= LocalVar '=' 'type' type
327 bool LLParser::ParseNamedType() {
328   std::string Name = Lex.getStrVal();
329   LocTy NameLoc = Lex.getLoc();
330   Lex.Lex();  // eat LocalVar.
331
332   if (ParseToken(lltok::equal, "expected '=' after name") ||
333       ParseToken(lltok::kw_type, "expected 'type' after name"))
334     return true;
335
336   Type *Result = nullptr;
337   if (ParseStructDefinition(NameLoc, Name,
338                             NamedTypes[Name], Result)) return true;
339
340   if (!isa<StructType>(Result)) {
341     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
342     if (Entry.first)
343       return Error(NameLoc, "non-struct types may not be recursive");
344     Entry.first = Result;
345     Entry.second = SMLoc();
346   }
347
348   return false;
349 }
350
351
352 /// toplevelentity
353 ///   ::= 'declare' FunctionHeader
354 bool LLParser::ParseDeclare() {
355   assert(Lex.getKind() == lltok::kw_declare);
356   Lex.Lex();
357
358   Function *F;
359   return ParseFunctionHeader(F, false);
360 }
361
362 /// toplevelentity
363 ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
364 bool LLParser::ParseDefine() {
365   assert(Lex.getKind() == lltok::kw_define);
366   Lex.Lex();
367
368   Function *F;
369   return ParseFunctionHeader(F, true) ||
370          ParseOptionalFunctionMetadata(*F) ||
371          ParseFunctionBody(*F);
372 }
373
374 /// ParseGlobalType
375 ///   ::= 'constant'
376 ///   ::= 'global'
377 bool LLParser::ParseGlobalType(bool &IsConstant) {
378   if (Lex.getKind() == lltok::kw_constant)
379     IsConstant = true;
380   else if (Lex.getKind() == lltok::kw_global)
381     IsConstant = false;
382   else {
383     IsConstant = false;
384     return TokError("expected 'global' or 'constant'");
385   }
386   Lex.Lex();
387   return false;
388 }
389
390 /// ParseUnnamedGlobal:
391 ///   OptionalVisibility ALIAS ...
392 ///   OptionalLinkage OptionalVisibility OptionalDLLStorageClass
393 ///                                                     ...   -> global variable
394 ///   GlobalID '=' OptionalVisibility ALIAS ...
395 ///   GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
396 ///                                                     ...   -> global variable
397 bool LLParser::ParseUnnamedGlobal() {
398   unsigned VarID = NumberedVals.size();
399   std::string Name;
400   LocTy NameLoc = Lex.getLoc();
401
402   // Handle the GlobalID form.
403   if (Lex.getKind() == lltok::GlobalID) {
404     if (Lex.getUIntVal() != VarID)
405       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
406                    Twine(VarID) + "'");
407     Lex.Lex(); // eat GlobalID;
408
409     if (ParseToken(lltok::equal, "expected '=' after name"))
410       return true;
411   }
412
413   bool HasLinkage;
414   unsigned Linkage, Visibility, DLLStorageClass;
415   GlobalVariable::ThreadLocalMode TLM;
416   bool UnnamedAddr;
417   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
418       ParseOptionalVisibility(Visibility) ||
419       ParseOptionalDLLStorageClass(DLLStorageClass) ||
420       ParseOptionalThreadLocal(TLM) ||
421       parseOptionalUnnamedAddr(UnnamedAddr))
422     return true;
423
424   if (Lex.getKind() != lltok::kw_alias)
425     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
426                        DLLStorageClass, TLM, UnnamedAddr);
427   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
428                     UnnamedAddr);
429 }
430
431 /// ParseNamedGlobal:
432 ///   GlobalVar '=' OptionalVisibility ALIAS ...
433 ///   GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
434 ///                                                     ...   -> global variable
435 bool LLParser::ParseNamedGlobal() {
436   assert(Lex.getKind() == lltok::GlobalVar);
437   LocTy NameLoc = Lex.getLoc();
438   std::string Name = Lex.getStrVal();
439   Lex.Lex();
440
441   bool HasLinkage;
442   unsigned Linkage, Visibility, DLLStorageClass;
443   GlobalVariable::ThreadLocalMode TLM;
444   bool UnnamedAddr;
445   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
446       ParseOptionalLinkage(Linkage, HasLinkage) ||
447       ParseOptionalVisibility(Visibility) ||
448       ParseOptionalDLLStorageClass(DLLStorageClass) ||
449       ParseOptionalThreadLocal(TLM) ||
450       parseOptionalUnnamedAddr(UnnamedAddr))
451     return true;
452
453   if (Lex.getKind() != lltok::kw_alias)
454     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
455                        DLLStorageClass, TLM, UnnamedAddr);
456
457   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
458                     UnnamedAddr);
459 }
460
461 bool LLParser::parseComdat() {
462   assert(Lex.getKind() == lltok::ComdatVar);
463   std::string Name = Lex.getStrVal();
464   LocTy NameLoc = Lex.getLoc();
465   Lex.Lex();
466
467   if (ParseToken(lltok::equal, "expected '=' here"))
468     return true;
469
470   if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
471     return TokError("expected comdat type");
472
473   Comdat::SelectionKind SK;
474   switch (Lex.getKind()) {
475   default:
476     return TokError("unknown selection kind");
477   case lltok::kw_any:
478     SK = Comdat::Any;
479     break;
480   case lltok::kw_exactmatch:
481     SK = Comdat::ExactMatch;
482     break;
483   case lltok::kw_largest:
484     SK = Comdat::Largest;
485     break;
486   case lltok::kw_noduplicates:
487     SK = Comdat::NoDuplicates;
488     break;
489   case lltok::kw_samesize:
490     SK = Comdat::SameSize;
491     break;
492   }
493   Lex.Lex();
494
495   // See if the comdat was forward referenced, if so, use the comdat.
496   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
497   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
498   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
499     return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
500
501   Comdat *C;
502   if (I != ComdatSymTab.end())
503     C = &I->second;
504   else
505     C = M->getOrInsertComdat(Name);
506   C->setSelectionKind(SK);
507
508   return false;
509 }
510
511 // MDString:
512 //   ::= '!' STRINGCONSTANT
513 bool LLParser::ParseMDString(MDString *&Result) {
514   std::string Str;
515   if (ParseStringConstant(Str)) return true;
516   llvm::UpgradeMDStringConstant(Str);
517   Result = MDString::get(Context, Str);
518   return false;
519 }
520
521 // MDNode:
522 //   ::= '!' MDNodeNumber
523 bool LLParser::ParseMDNodeID(MDNode *&Result) {
524   // !{ ..., !42, ... }
525   unsigned MID = 0;
526   if (ParseUInt32(MID))
527     return true;
528
529   // If not a forward reference, just return it now.
530   if (NumberedMetadata.count(MID)) {
531     Result = NumberedMetadata[MID];
532     return false;
533   }
534
535   // Otherwise, create MDNode forward reference.
536   auto &FwdRef = ForwardRefMDNodes[MID];
537   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
538
539   Result = FwdRef.first.get();
540   NumberedMetadata[MID].reset(Result);
541   return false;
542 }
543
544 /// ParseNamedMetadata:
545 ///   !foo = !{ !1, !2 }
546 bool LLParser::ParseNamedMetadata() {
547   assert(Lex.getKind() == lltok::MetadataVar);
548   std::string Name = Lex.getStrVal();
549   Lex.Lex();
550
551   if (ParseToken(lltok::equal, "expected '=' here") ||
552       ParseToken(lltok::exclaim, "Expected '!' here") ||
553       ParseToken(lltok::lbrace, "Expected '{' here"))
554     return true;
555
556   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
557   if (Lex.getKind() != lltok::rbrace)
558     do {
559       if (ParseToken(lltok::exclaim, "Expected '!' here"))
560         return true;
561
562       MDNode *N = nullptr;
563       if (ParseMDNodeID(N)) return true;
564       NMD->addOperand(N);
565     } while (EatIfPresent(lltok::comma));
566
567   if (ParseToken(lltok::rbrace, "expected end of metadata node"))
568     return true;
569
570   return false;
571 }
572
573 /// ParseStandaloneMetadata:
574 ///   !42 = !{...}
575 bool LLParser::ParseStandaloneMetadata() {
576   assert(Lex.getKind() == lltok::exclaim);
577   Lex.Lex();
578   unsigned MetadataID = 0;
579
580   MDNode *Init;
581   if (ParseUInt32(MetadataID) ||
582       ParseToken(lltok::equal, "expected '=' here"))
583     return true;
584
585   // Detect common error, from old metadata syntax.
586   if (Lex.getKind() == lltok::Type)
587     return TokError("unexpected type in metadata definition");
588
589   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
590   if (Lex.getKind() == lltok::MetadataVar) {
591     if (ParseSpecializedMDNode(Init, IsDistinct))
592       return true;
593   } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
594              ParseMDTuple(Init, IsDistinct))
595     return true;
596
597   // See if this was forward referenced, if so, handle it.
598   auto FI = ForwardRefMDNodes.find(MetadataID);
599   if (FI != ForwardRefMDNodes.end()) {
600     FI->second.first->replaceAllUsesWith(Init);
601     ForwardRefMDNodes.erase(FI);
602
603     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
604   } else {
605     if (NumberedMetadata.count(MetadataID))
606       return TokError("Metadata id is already used");
607     NumberedMetadata[MetadataID].reset(Init);
608   }
609
610   return false;
611 }
612
613 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
614   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
615          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
616 }
617
618 /// ParseAlias:
619 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility
620 ///                     OptionalDLLStorageClass OptionalThreadLocal
621 ///                     OptionalUnNammedAddr 'alias' Aliasee
622 ///
623 /// Aliasee
624 ///   ::= TypeAndValue
625 ///
626 /// Everything through OptionalUnNammedAddr has already been parsed.
627 ///
628 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
629                           unsigned Visibility, unsigned DLLStorageClass,
630                           GlobalVariable::ThreadLocalMode TLM,
631                           bool UnnamedAddr) {
632   assert(Lex.getKind() == lltok::kw_alias);
633   Lex.Lex();
634
635   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
636
637   if(!GlobalAlias::isValidLinkage(Linkage))
638     return Error(NameLoc, "invalid linkage type for alias");
639
640   if (!isValidVisibilityForLinkage(Visibility, L))
641     return Error(NameLoc,
642                  "symbol with local linkage must have default visibility");
643
644   Constant *Aliasee;
645   LocTy AliaseeLoc = Lex.getLoc();
646   if (Lex.getKind() != lltok::kw_bitcast &&
647       Lex.getKind() != lltok::kw_getelementptr &&
648       Lex.getKind() != lltok::kw_addrspacecast &&
649       Lex.getKind() != lltok::kw_inttoptr) {
650     if (ParseGlobalTypeAndValue(Aliasee))
651       return true;
652   } else {
653     // The bitcast dest type is not present, it is implied by the dest type.
654     ValID ID;
655     if (ParseValID(ID))
656       return true;
657     if (ID.Kind != ValID::t_Constant)
658       return Error(AliaseeLoc, "invalid aliasee");
659     Aliasee = ID.ConstantVal;
660   }
661
662   Type *AliaseeType = Aliasee->getType();
663   auto *PTy = dyn_cast<PointerType>(AliaseeType);
664   if (!PTy)
665     return Error(AliaseeLoc, "An alias must have pointer type");
666   Type *Ty = PTy->getElementType();
667   unsigned AddrSpace = PTy->getAddressSpace();
668
669   // Okay, create the alias but do not insert it into the module yet.
670   std::unique_ptr<GlobalAlias> GA(
671       GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
672                           Name, Aliasee, /*Parent*/ nullptr));
673   GA->setThreadLocalMode(TLM);
674   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
675   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
676   GA->setUnnamedAddr(UnnamedAddr);
677
678   // See if this value already exists in the symbol table.  If so, it is either
679   // a redefinition or a definition of a forward reference.
680   if (GlobalValue *Val = M->getNamedValue(Name)) {
681     // See if this was a redefinition.  If so, there is no entry in
682     // ForwardRefVals.
683     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
684       I = ForwardRefVals.find(Name);
685     if (I == ForwardRefVals.end())
686       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
687
688     // Otherwise, this was a definition of forward ref.  Verify that types
689     // agree.
690     if (Val->getType() != GA->getType())
691       return Error(NameLoc,
692               "forward reference and definition of alias have different types");
693
694     // If they agree, just RAUW the old value with the alias and remove the
695     // forward ref info.
696     Val->replaceAllUsesWith(GA.get());
697     Val->eraseFromParent();
698     ForwardRefVals.erase(I);
699   }
700
701   // Insert into the module, we know its name won't collide now.
702   M->getAliasList().push_back(GA.get());
703   assert(GA->getName() == Name && "Should not be a name conflict!");
704
705   // The module owns this now
706   GA.release();
707
708   return false;
709 }
710
711 /// ParseGlobal
712 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
713 ///       OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
714 ///       OptionalExternallyInitialized GlobalType Type Const
715 ///   ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
716 ///       OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
717 ///       OptionalExternallyInitialized GlobalType Type Const
718 ///
719 /// Everything up to and including OptionalUnNammedAddr has been parsed
720 /// already.
721 ///
722 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
723                            unsigned Linkage, bool HasLinkage,
724                            unsigned Visibility, unsigned DLLStorageClass,
725                            GlobalVariable::ThreadLocalMode TLM,
726                            bool UnnamedAddr) {
727   if (!isValidVisibilityForLinkage(Visibility, Linkage))
728     return Error(NameLoc,
729                  "symbol with local linkage must have default visibility");
730
731   unsigned AddrSpace;
732   bool IsConstant, IsExternallyInitialized;
733   LocTy IsExternallyInitializedLoc;
734   LocTy TyLoc;
735
736   Type *Ty = nullptr;
737   if (ParseOptionalAddrSpace(AddrSpace) ||
738       ParseOptionalToken(lltok::kw_externally_initialized,
739                          IsExternallyInitialized,
740                          &IsExternallyInitializedLoc) ||
741       ParseGlobalType(IsConstant) ||
742       ParseType(Ty, TyLoc))
743     return true;
744
745   // If the linkage is specified and is external, then no initializer is
746   // present.
747   Constant *Init = nullptr;
748   if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
749                       Linkage != GlobalValue::ExternalLinkage)) {
750     if (ParseGlobalValue(Ty, Init))
751       return true;
752   }
753
754   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
755     return Error(TyLoc, "invalid type for global variable");
756
757   GlobalValue *GVal = nullptr;
758
759   // See if the global was forward referenced, if so, use the global.
760   if (!Name.empty()) {
761     GVal = M->getNamedValue(Name);
762     if (GVal) {
763       if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
764         return Error(NameLoc, "redefinition of global '@" + Name + "'");
765     }
766   } else {
767     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
768       I = ForwardRefValIDs.find(NumberedVals.size());
769     if (I != ForwardRefValIDs.end()) {
770       GVal = I->second.first;
771       ForwardRefValIDs.erase(I);
772     }
773   }
774
775   GlobalVariable *GV;
776   if (!GVal) {
777     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
778                             Name, nullptr, GlobalVariable::NotThreadLocal,
779                             AddrSpace);
780   } else {
781     if (GVal->getType()->getElementType() != Ty)
782       return Error(TyLoc,
783             "forward reference and definition of global have different types");
784
785     GV = cast<GlobalVariable>(GVal);
786
787     // Move the forward-reference to the correct spot in the module.
788     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
789   }
790
791   if (Name.empty())
792     NumberedVals.push_back(GV);
793
794   // Set the parsed properties on the global.
795   if (Init)
796     GV->setInitializer(Init);
797   GV->setConstant(IsConstant);
798   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
799   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
800   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
801   GV->setExternallyInitialized(IsExternallyInitialized);
802   GV->setThreadLocalMode(TLM);
803   GV->setUnnamedAddr(UnnamedAddr);
804
805   // Parse attributes on the global.
806   while (Lex.getKind() == lltok::comma) {
807     Lex.Lex();
808
809     if (Lex.getKind() == lltok::kw_section) {
810       Lex.Lex();
811       GV->setSection(Lex.getStrVal());
812       if (ParseToken(lltok::StringConstant, "expected global section string"))
813         return true;
814     } else if (Lex.getKind() == lltok::kw_align) {
815       unsigned Alignment;
816       if (ParseOptionalAlignment(Alignment)) return true;
817       GV->setAlignment(Alignment);
818     } else {
819       Comdat *C;
820       if (parseOptionalComdat(Name, C))
821         return true;
822       if (C)
823         GV->setComdat(C);
824       else
825         return TokError("unknown global variable property!");
826     }
827   }
828
829   return false;
830 }
831
832 /// ParseUnnamedAttrGrp
833 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
834 bool LLParser::ParseUnnamedAttrGrp() {
835   assert(Lex.getKind() == lltok::kw_attributes);
836   LocTy AttrGrpLoc = Lex.getLoc();
837   Lex.Lex();
838
839   if (Lex.getKind() != lltok::AttrGrpID)
840     return TokError("expected attribute group id");
841
842   unsigned VarID = Lex.getUIntVal();
843   std::vector<unsigned> unused;
844   LocTy BuiltinLoc;
845   Lex.Lex();
846
847   if (ParseToken(lltok::equal, "expected '=' here") ||
848       ParseToken(lltok::lbrace, "expected '{' here") ||
849       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
850                                  BuiltinLoc) ||
851       ParseToken(lltok::rbrace, "expected end of attribute group"))
852     return true;
853
854   if (!NumberedAttrBuilders[VarID].hasAttributes())
855     return Error(AttrGrpLoc, "attribute group has no attributes");
856
857   return false;
858 }
859
860 /// ParseFnAttributeValuePairs
861 ///   ::= <attr> | <attr> '=' <value>
862 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
863                                           std::vector<unsigned> &FwdRefAttrGrps,
864                                           bool inAttrGrp, LocTy &BuiltinLoc) {
865   bool HaveError = false;
866
867   B.clear();
868
869   while (true) {
870     lltok::Kind Token = Lex.getKind();
871     if (Token == lltok::kw_builtin)
872       BuiltinLoc = Lex.getLoc();
873     switch (Token) {
874     default:
875       if (!inAttrGrp) return HaveError;
876       return Error(Lex.getLoc(), "unterminated attribute group");
877     case lltok::rbrace:
878       // Finished.
879       return false;
880
881     case lltok::AttrGrpID: {
882       // Allow a function to reference an attribute group:
883       //
884       //   define void @foo() #1 { ... }
885       if (inAttrGrp)
886         HaveError |=
887           Error(Lex.getLoc(),
888               "cannot have an attribute group reference in an attribute group");
889
890       unsigned AttrGrpNum = Lex.getUIntVal();
891       if (inAttrGrp) break;
892
893       // Save the reference to the attribute group. We'll fill it in later.
894       FwdRefAttrGrps.push_back(AttrGrpNum);
895       break;
896     }
897     // Target-dependent attributes:
898     case lltok::StringConstant: {
899       std::string Attr = Lex.getStrVal();
900       Lex.Lex();
901       std::string Val;
902       if (EatIfPresent(lltok::equal) &&
903           ParseStringConstant(Val))
904         return true;
905
906       B.addAttribute(Attr, Val);
907       continue;
908     }
909
910     // Target-independent attributes:
911     case lltok::kw_align: {
912       // As a hack, we allow function alignment to be initially parsed as an
913       // attribute on a function declaration/definition or added to an attribute
914       // group and later moved to the alignment field.
915       unsigned Alignment;
916       if (inAttrGrp) {
917         Lex.Lex();
918         if (ParseToken(lltok::equal, "expected '=' here") ||
919             ParseUInt32(Alignment))
920           return true;
921       } else {
922         if (ParseOptionalAlignment(Alignment))
923           return true;
924       }
925       B.addAlignmentAttr(Alignment);
926       continue;
927     }
928     case lltok::kw_alignstack: {
929       unsigned Alignment;
930       if (inAttrGrp) {
931         Lex.Lex();
932         if (ParseToken(lltok::equal, "expected '=' here") ||
933             ParseUInt32(Alignment))
934           return true;
935       } else {
936         if (ParseOptionalStackAlignment(Alignment))
937           return true;
938       }
939       B.addStackAlignmentAttr(Alignment);
940       continue;
941     }
942     case lltok::kw_alwaysinline:      B.addAttribute(Attribute::AlwaysInline); break;
943     case lltok::kw_builtin:           B.addAttribute(Attribute::Builtin); break;
944     case lltok::kw_cold:              B.addAttribute(Attribute::Cold); break;
945     case lltok::kw_inlinehint:        B.addAttribute(Attribute::InlineHint); break;
946     case lltok::kw_jumptable:         B.addAttribute(Attribute::JumpTable); break;
947     case lltok::kw_minsize:           B.addAttribute(Attribute::MinSize); break;
948     case lltok::kw_naked:             B.addAttribute(Attribute::Naked); break;
949     case lltok::kw_nobuiltin:         B.addAttribute(Attribute::NoBuiltin); break;
950     case lltok::kw_noduplicate:       B.addAttribute(Attribute::NoDuplicate); break;
951     case lltok::kw_noimplicitfloat:   B.addAttribute(Attribute::NoImplicitFloat); break;
952     case lltok::kw_noinline:          B.addAttribute(Attribute::NoInline); break;
953     case lltok::kw_nonlazybind:       B.addAttribute(Attribute::NonLazyBind); break;
954     case lltok::kw_noredzone:         B.addAttribute(Attribute::NoRedZone); break;
955     case lltok::kw_noreturn:          B.addAttribute(Attribute::NoReturn); break;
956     case lltok::kw_nounwind:          B.addAttribute(Attribute::NoUnwind); break;
957     case lltok::kw_optnone:           B.addAttribute(Attribute::OptimizeNone); break;
958     case lltok::kw_optsize:           B.addAttribute(Attribute::OptimizeForSize); break;
959     case lltok::kw_readnone:          B.addAttribute(Attribute::ReadNone); break;
960     case lltok::kw_readonly:          B.addAttribute(Attribute::ReadOnly); break;
961     case lltok::kw_returns_twice:     B.addAttribute(Attribute::ReturnsTwice); break;
962     case lltok::kw_ssp:               B.addAttribute(Attribute::StackProtect); break;
963     case lltok::kw_sspreq:            B.addAttribute(Attribute::StackProtectReq); break;
964     case lltok::kw_sspstrong:         B.addAttribute(Attribute::StackProtectStrong); break;
965     case lltok::kw_sanitize_address:  B.addAttribute(Attribute::SanitizeAddress); break;
966     case lltok::kw_sanitize_thread:   B.addAttribute(Attribute::SanitizeThread); break;
967     case lltok::kw_sanitize_memory:   B.addAttribute(Attribute::SanitizeMemory); break;
968     case lltok::kw_uwtable:           B.addAttribute(Attribute::UWTable); break;
969
970     // Error handling.
971     case lltok::kw_inreg:
972     case lltok::kw_signext:
973     case lltok::kw_zeroext:
974       HaveError |=
975         Error(Lex.getLoc(),
976               "invalid use of attribute on a function");
977       break;
978     case lltok::kw_byval:
979     case lltok::kw_dereferenceable:
980     case lltok::kw_dereferenceable_or_null:
981     case lltok::kw_inalloca:
982     case lltok::kw_nest:
983     case lltok::kw_noalias:
984     case lltok::kw_nocapture:
985     case lltok::kw_nonnull:
986     case lltok::kw_returned:
987     case lltok::kw_sret:
988       HaveError |=
989         Error(Lex.getLoc(),
990               "invalid use of parameter-only attribute on a function");
991       break;
992     }
993
994     Lex.Lex();
995   }
996 }
997
998 //===----------------------------------------------------------------------===//
999 // GlobalValue Reference/Resolution Routines.
1000 //===----------------------------------------------------------------------===//
1001
1002 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1003 /// forward reference record if needed.  This can return null if the value
1004 /// exists but does not have the right type.
1005 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1006                                     LocTy Loc) {
1007   PointerType *PTy = dyn_cast<PointerType>(Ty);
1008   if (!PTy) {
1009     Error(Loc, "global variable reference must have pointer type");
1010     return nullptr;
1011   }
1012
1013   // Look this name up in the normal function symbol table.
1014   GlobalValue *Val =
1015     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1016
1017   // If this is a forward reference for the value, see if we already created a
1018   // forward ref record.
1019   if (!Val) {
1020     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1021       I = ForwardRefVals.find(Name);
1022     if (I != ForwardRefVals.end())
1023       Val = I->second.first;
1024   }
1025
1026   // If we have the value in the symbol table or fwd-ref table, return it.
1027   if (Val) {
1028     if (Val->getType() == Ty) return Val;
1029     Error(Loc, "'@" + Name + "' defined with type '" +
1030           getTypeString(Val->getType()) + "'");
1031     return nullptr;
1032   }
1033
1034   // Otherwise, create a new forward reference for this value and remember it.
1035   GlobalValue *FwdVal;
1036   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1037     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1038   else
1039     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1040                                 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1041                                 nullptr, GlobalVariable::NotThreadLocal,
1042                                 PTy->getAddressSpace());
1043
1044   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1045   return FwdVal;
1046 }
1047
1048 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1049   PointerType *PTy = dyn_cast<PointerType>(Ty);
1050   if (!PTy) {
1051     Error(Loc, "global variable reference must have pointer type");
1052     return nullptr;
1053   }
1054
1055   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1056
1057   // If this is a forward reference for the value, see if we already created a
1058   // forward ref record.
1059   if (!Val) {
1060     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1061       I = ForwardRefValIDs.find(ID);
1062     if (I != ForwardRefValIDs.end())
1063       Val = I->second.first;
1064   }
1065
1066   // If we have the value in the symbol table or fwd-ref table, return it.
1067   if (Val) {
1068     if (Val->getType() == Ty) return Val;
1069     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1070           getTypeString(Val->getType()) + "'");
1071     return nullptr;
1072   }
1073
1074   // Otherwise, create a new forward reference for this value and remember it.
1075   GlobalValue *FwdVal;
1076   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1077     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1078   else
1079     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1080                                 GlobalValue::ExternalWeakLinkage, nullptr, "");
1081
1082   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1083   return FwdVal;
1084 }
1085
1086
1087 //===----------------------------------------------------------------------===//
1088 // Comdat Reference/Resolution Routines.
1089 //===----------------------------------------------------------------------===//
1090
1091 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1092   // Look this name up in the comdat symbol table.
1093   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1094   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1095   if (I != ComdatSymTab.end())
1096     return &I->second;
1097
1098   // Otherwise, create a new forward reference for this value and remember it.
1099   Comdat *C = M->getOrInsertComdat(Name);
1100   ForwardRefComdats[Name] = Loc;
1101   return C;
1102 }
1103
1104
1105 //===----------------------------------------------------------------------===//
1106 // Helper Routines.
1107 //===----------------------------------------------------------------------===//
1108
1109 /// ParseToken - If the current token has the specified kind, eat it and return
1110 /// success.  Otherwise, emit the specified error and return failure.
1111 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1112   if (Lex.getKind() != T)
1113     return TokError(ErrMsg);
1114   Lex.Lex();
1115   return false;
1116 }
1117
1118 /// ParseStringConstant
1119 ///   ::= StringConstant
1120 bool LLParser::ParseStringConstant(std::string &Result) {
1121   if (Lex.getKind() != lltok::StringConstant)
1122     return TokError("expected string constant");
1123   Result = Lex.getStrVal();
1124   Lex.Lex();
1125   return false;
1126 }
1127
1128 /// ParseUInt32
1129 ///   ::= uint32
1130 bool LLParser::ParseUInt32(unsigned &Val) {
1131   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1132     return TokError("expected integer");
1133   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1134   if (Val64 != unsigned(Val64))
1135     return TokError("expected 32-bit integer (too large)");
1136   Val = Val64;
1137   Lex.Lex();
1138   return false;
1139 }
1140
1141 /// ParseUInt64
1142 ///   ::= uint64
1143 bool LLParser::ParseUInt64(uint64_t &Val) {
1144   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1145     return TokError("expected integer");
1146   Val = Lex.getAPSIntVal().getLimitedValue();
1147   Lex.Lex();
1148   return false;
1149 }
1150
1151 /// ParseTLSModel
1152 ///   := 'localdynamic'
1153 ///   := 'initialexec'
1154 ///   := 'localexec'
1155 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1156   switch (Lex.getKind()) {
1157     default:
1158       return TokError("expected localdynamic, initialexec or localexec");
1159     case lltok::kw_localdynamic:
1160       TLM = GlobalVariable::LocalDynamicTLSModel;
1161       break;
1162     case lltok::kw_initialexec:
1163       TLM = GlobalVariable::InitialExecTLSModel;
1164       break;
1165     case lltok::kw_localexec:
1166       TLM = GlobalVariable::LocalExecTLSModel;
1167       break;
1168   }
1169
1170   Lex.Lex();
1171   return false;
1172 }
1173
1174 /// ParseOptionalThreadLocal
1175 ///   := /*empty*/
1176 ///   := 'thread_local'
1177 ///   := 'thread_local' '(' tlsmodel ')'
1178 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1179   TLM = GlobalVariable::NotThreadLocal;
1180   if (!EatIfPresent(lltok::kw_thread_local))
1181     return false;
1182
1183   TLM = GlobalVariable::GeneralDynamicTLSModel;
1184   if (Lex.getKind() == lltok::lparen) {
1185     Lex.Lex();
1186     return ParseTLSModel(TLM) ||
1187       ParseToken(lltok::rparen, "expected ')' after thread local model");
1188   }
1189   return false;
1190 }
1191
1192 /// ParseOptionalAddrSpace
1193 ///   := /*empty*/
1194 ///   := 'addrspace' '(' uint32 ')'
1195 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1196   AddrSpace = 0;
1197   if (!EatIfPresent(lltok::kw_addrspace))
1198     return false;
1199   return ParseToken(lltok::lparen, "expected '(' in address space") ||
1200          ParseUInt32(AddrSpace) ||
1201          ParseToken(lltok::rparen, "expected ')' in address space");
1202 }
1203
1204 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1205 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1206   bool HaveError = false;
1207
1208   B.clear();
1209
1210   while (1) {
1211     lltok::Kind Token = Lex.getKind();
1212     switch (Token) {
1213     default:  // End of attributes.
1214       return HaveError;
1215     case lltok::kw_align: {
1216       unsigned Alignment;
1217       if (ParseOptionalAlignment(Alignment))
1218         return true;
1219       B.addAlignmentAttr(Alignment);
1220       continue;
1221     }
1222     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1223     case lltok::kw_dereferenceable: {
1224       uint64_t Bytes;
1225       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1226         return true;
1227       B.addDereferenceableAttr(Bytes);
1228       continue;
1229     }
1230     case lltok::kw_dereferenceable_or_null: {
1231       uint64_t Bytes;
1232       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1233         return true;
1234       B.addDereferenceableOrNullAttr(Bytes);
1235       continue;
1236     }
1237     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
1238     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1239     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1240     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1241     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1242     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1243     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1244     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1245     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1246     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1247     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1248     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1249
1250     case lltok::kw_alignstack:
1251     case lltok::kw_alwaysinline:
1252     case lltok::kw_builtin:
1253     case lltok::kw_inlinehint:
1254     case lltok::kw_jumptable:
1255     case lltok::kw_minsize:
1256     case lltok::kw_naked:
1257     case lltok::kw_nobuiltin:
1258     case lltok::kw_noduplicate:
1259     case lltok::kw_noimplicitfloat:
1260     case lltok::kw_noinline:
1261     case lltok::kw_nonlazybind:
1262     case lltok::kw_noredzone:
1263     case lltok::kw_noreturn:
1264     case lltok::kw_nounwind:
1265     case lltok::kw_optnone:
1266     case lltok::kw_optsize:
1267     case lltok::kw_returns_twice:
1268     case lltok::kw_sanitize_address:
1269     case lltok::kw_sanitize_memory:
1270     case lltok::kw_sanitize_thread:
1271     case lltok::kw_ssp:
1272     case lltok::kw_sspreq:
1273     case lltok::kw_sspstrong:
1274     case lltok::kw_uwtable:
1275       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1276       break;
1277     }
1278
1279     Lex.Lex();
1280   }
1281 }
1282
1283 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1284 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1285   bool HaveError = false;
1286
1287   B.clear();
1288
1289   while (1) {
1290     lltok::Kind Token = Lex.getKind();
1291     switch (Token) {
1292     default:  // End of attributes.
1293       return HaveError;
1294     case lltok::kw_dereferenceable: {
1295       uint64_t Bytes;
1296       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1297         return true;
1298       B.addDereferenceableAttr(Bytes);
1299       continue;
1300     }
1301     case lltok::kw_dereferenceable_or_null: {
1302       uint64_t Bytes;
1303       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1304         return true;
1305       B.addDereferenceableOrNullAttr(Bytes);
1306       continue;
1307     }
1308     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1309     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1310     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1311     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1312     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1313
1314     // Error handling.
1315     case lltok::kw_align:
1316     case lltok::kw_byval:
1317     case lltok::kw_inalloca:
1318     case lltok::kw_nest:
1319     case lltok::kw_nocapture:
1320     case lltok::kw_returned:
1321     case lltok::kw_sret:
1322       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1323       break;
1324
1325     case lltok::kw_alignstack:
1326     case lltok::kw_alwaysinline:
1327     case lltok::kw_builtin:
1328     case lltok::kw_cold:
1329     case lltok::kw_inlinehint:
1330     case lltok::kw_jumptable:
1331     case lltok::kw_minsize:
1332     case lltok::kw_naked:
1333     case lltok::kw_nobuiltin:
1334     case lltok::kw_noduplicate:
1335     case lltok::kw_noimplicitfloat:
1336     case lltok::kw_noinline:
1337     case lltok::kw_nonlazybind:
1338     case lltok::kw_noredzone:
1339     case lltok::kw_noreturn:
1340     case lltok::kw_nounwind:
1341     case lltok::kw_optnone:
1342     case lltok::kw_optsize:
1343     case lltok::kw_returns_twice:
1344     case lltok::kw_sanitize_address:
1345     case lltok::kw_sanitize_memory:
1346     case lltok::kw_sanitize_thread:
1347     case lltok::kw_ssp:
1348     case lltok::kw_sspreq:
1349     case lltok::kw_sspstrong:
1350     case lltok::kw_uwtable:
1351       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1352       break;
1353
1354     case lltok::kw_readnone:
1355     case lltok::kw_readonly:
1356       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1357     }
1358
1359     Lex.Lex();
1360   }
1361 }
1362
1363 /// ParseOptionalLinkage
1364 ///   ::= /*empty*/
1365 ///   ::= 'private'
1366 ///   ::= 'internal'
1367 ///   ::= 'weak'
1368 ///   ::= 'weak_odr'
1369 ///   ::= 'linkonce'
1370 ///   ::= 'linkonce_odr'
1371 ///   ::= 'available_externally'
1372 ///   ::= 'appending'
1373 ///   ::= 'common'
1374 ///   ::= 'extern_weak'
1375 ///   ::= 'external'
1376 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1377   HasLinkage = false;
1378   switch (Lex.getKind()) {
1379   default:                       Res=GlobalValue::ExternalLinkage; return false;
1380   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
1381   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
1382   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
1383   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
1384   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
1385   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
1386   case lltok::kw_available_externally:
1387     Res = GlobalValue::AvailableExternallyLinkage;
1388     break;
1389   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
1390   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
1391   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
1392   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1393   }
1394   Lex.Lex();
1395   HasLinkage = true;
1396   return false;
1397 }
1398
1399 /// ParseOptionalVisibility
1400 ///   ::= /*empty*/
1401 ///   ::= 'default'
1402 ///   ::= 'hidden'
1403 ///   ::= 'protected'
1404 ///
1405 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1406   switch (Lex.getKind()) {
1407   default:                  Res = GlobalValue::DefaultVisibility; return false;
1408   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1409   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1410   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1411   }
1412   Lex.Lex();
1413   return false;
1414 }
1415
1416 /// ParseOptionalDLLStorageClass
1417 ///   ::= /*empty*/
1418 ///   ::= 'dllimport'
1419 ///   ::= 'dllexport'
1420 ///
1421 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1422   switch (Lex.getKind()) {
1423   default:                  Res = GlobalValue::DefaultStorageClass; return false;
1424   case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1425   case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1426   }
1427   Lex.Lex();
1428   return false;
1429 }
1430
1431 /// ParseOptionalCallingConv
1432 ///   ::= /*empty*/
1433 ///   ::= 'ccc'
1434 ///   ::= 'fastcc'
1435 ///   ::= 'intel_ocl_bicc'
1436 ///   ::= 'coldcc'
1437 ///   ::= 'x86_stdcallcc'
1438 ///   ::= 'x86_fastcallcc'
1439 ///   ::= 'x86_thiscallcc'
1440 ///   ::= 'x86_vectorcallcc'
1441 ///   ::= 'arm_apcscc'
1442 ///   ::= 'arm_aapcscc'
1443 ///   ::= 'arm_aapcs_vfpcc'
1444 ///   ::= 'msp430_intrcc'
1445 ///   ::= 'ptx_kernel'
1446 ///   ::= 'ptx_device'
1447 ///   ::= 'spir_func'
1448 ///   ::= 'spir_kernel'
1449 ///   ::= 'x86_64_sysvcc'
1450 ///   ::= 'x86_64_win64cc'
1451 ///   ::= 'webkit_jscc'
1452 ///   ::= 'anyregcc'
1453 ///   ::= 'preserve_mostcc'
1454 ///   ::= 'preserve_allcc'
1455 ///   ::= 'ghccc'
1456 ///   ::= 'cc' UINT
1457 ///
1458 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1459   switch (Lex.getKind()) {
1460   default:                       CC = CallingConv::C; return false;
1461   case lltok::kw_ccc:            CC = CallingConv::C; break;
1462   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1463   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1464   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1465   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1466   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1467   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1468   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1469   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1470   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1471   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1472   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1473   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1474   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1475   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1476   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1477   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1478   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1479   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
1480   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
1481   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1482   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1483   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
1484   case lltok::kw_cc: {
1485       Lex.Lex();
1486       return ParseUInt32(CC);
1487     }
1488   }
1489
1490   Lex.Lex();
1491   return false;
1492 }
1493
1494 /// ParseMetadataAttachment
1495 ///   ::= !dbg !42
1496 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1497   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1498
1499   std::string Name = Lex.getStrVal();
1500   Kind = M->getMDKindID(Name);
1501   Lex.Lex();
1502
1503   return ParseMDNode(MD);
1504 }
1505
1506 /// ParseInstructionMetadata
1507 ///   ::= !dbg !42 (',' !dbg !57)*
1508 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1509   do {
1510     if (Lex.getKind() != lltok::MetadataVar)
1511       return TokError("expected metadata after comma");
1512
1513     unsigned MDK;
1514     MDNode *N;
1515     if (ParseMetadataAttachment(MDK, N))
1516       return true;
1517
1518     Inst.setMetadata(MDK, N);
1519     if (MDK == LLVMContext::MD_tbaa)
1520       InstsWithTBAATag.push_back(&Inst);
1521
1522     // If this is the end of the list, we're done.
1523   } while (EatIfPresent(lltok::comma));
1524   return false;
1525 }
1526
1527 /// ParseOptionalFunctionMetadata
1528 ///   ::= (!dbg !57)*
1529 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1530   while (Lex.getKind() == lltok::MetadataVar) {
1531     unsigned MDK;
1532     MDNode *N;
1533     if (ParseMetadataAttachment(MDK, N))
1534       return true;
1535
1536     F.setMetadata(MDK, N);
1537   }
1538   return false;
1539 }
1540
1541 /// ParseOptionalAlignment
1542 ///   ::= /* empty */
1543 ///   ::= 'align' 4
1544 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1545   Alignment = 0;
1546   if (!EatIfPresent(lltok::kw_align))
1547     return false;
1548   LocTy AlignLoc = Lex.getLoc();
1549   if (ParseUInt32(Alignment)) return true;
1550   if (!isPowerOf2_32(Alignment))
1551     return Error(AlignLoc, "alignment is not a power of two");
1552   if (Alignment > Value::MaximumAlignment)
1553     return Error(AlignLoc, "huge alignments are not supported yet");
1554   return false;
1555 }
1556
1557 /// ParseOptionalDerefAttrBytes
1558 ///   ::= /* empty */
1559 ///   ::= AttrKind '(' 4 ')'
1560 ///
1561 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1562 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1563                                            uint64_t &Bytes) {
1564   assert((AttrKind == lltok::kw_dereferenceable ||
1565           AttrKind == lltok::kw_dereferenceable_or_null) &&
1566          "contract!");
1567
1568   Bytes = 0;
1569   if (!EatIfPresent(AttrKind))
1570     return false;
1571   LocTy ParenLoc = Lex.getLoc();
1572   if (!EatIfPresent(lltok::lparen))
1573     return Error(ParenLoc, "expected '('");
1574   LocTy DerefLoc = Lex.getLoc();
1575   if (ParseUInt64(Bytes)) return true;
1576   ParenLoc = Lex.getLoc();
1577   if (!EatIfPresent(lltok::rparen))
1578     return Error(ParenLoc, "expected ')'");
1579   if (!Bytes)
1580     return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1581   return false;
1582 }
1583
1584 /// ParseOptionalCommaAlign
1585 ///   ::=
1586 ///   ::= ',' align 4
1587 ///
1588 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1589 /// end.
1590 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1591                                        bool &AteExtraComma) {
1592   AteExtraComma = false;
1593   while (EatIfPresent(lltok::comma)) {
1594     // Metadata at the end is an early exit.
1595     if (Lex.getKind() == lltok::MetadataVar) {
1596       AteExtraComma = true;
1597       return false;
1598     }
1599
1600     if (Lex.getKind() != lltok::kw_align)
1601       return Error(Lex.getLoc(), "expected metadata or 'align'");
1602
1603     if (ParseOptionalAlignment(Alignment)) return true;
1604   }
1605
1606   return false;
1607 }
1608
1609 /// ParseScopeAndOrdering
1610 ///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1611 ///   else: ::=
1612 ///
1613 /// This sets Scope and Ordering to the parsed values.
1614 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1615                                      AtomicOrdering &Ordering) {
1616   if (!isAtomic)
1617     return false;
1618
1619   Scope = CrossThread;
1620   if (EatIfPresent(lltok::kw_singlethread))
1621     Scope = SingleThread;
1622
1623   return ParseOrdering(Ordering);
1624 }
1625
1626 /// ParseOrdering
1627 ///   ::= AtomicOrdering
1628 ///
1629 /// This sets Ordering to the parsed value.
1630 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1631   switch (Lex.getKind()) {
1632   default: return TokError("Expected ordering on atomic instruction");
1633   case lltok::kw_unordered: Ordering = Unordered; break;
1634   case lltok::kw_monotonic: Ordering = Monotonic; break;
1635   case lltok::kw_acquire: Ordering = Acquire; break;
1636   case lltok::kw_release: Ordering = Release; break;
1637   case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1638   case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1639   }
1640   Lex.Lex();
1641   return false;
1642 }
1643
1644 /// ParseOptionalStackAlignment
1645 ///   ::= /* empty */
1646 ///   ::= 'alignstack' '(' 4 ')'
1647 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1648   Alignment = 0;
1649   if (!EatIfPresent(lltok::kw_alignstack))
1650     return false;
1651   LocTy ParenLoc = Lex.getLoc();
1652   if (!EatIfPresent(lltok::lparen))
1653     return Error(ParenLoc, "expected '('");
1654   LocTy AlignLoc = Lex.getLoc();
1655   if (ParseUInt32(Alignment)) return true;
1656   ParenLoc = Lex.getLoc();
1657   if (!EatIfPresent(lltok::rparen))
1658     return Error(ParenLoc, "expected ')'");
1659   if (!isPowerOf2_32(Alignment))
1660     return Error(AlignLoc, "stack alignment is not a power of two");
1661   return false;
1662 }
1663
1664 /// ParseIndexList - This parses the index list for an insert/extractvalue
1665 /// instruction.  This sets AteExtraComma in the case where we eat an extra
1666 /// comma at the end of the line and find that it is followed by metadata.
1667 /// Clients that don't allow metadata can call the version of this function that
1668 /// only takes one argument.
1669 ///
1670 /// ParseIndexList
1671 ///    ::=  (',' uint32)+
1672 ///
1673 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1674                               bool &AteExtraComma) {
1675   AteExtraComma = false;
1676
1677   if (Lex.getKind() != lltok::comma)
1678     return TokError("expected ',' as start of index list");
1679
1680   while (EatIfPresent(lltok::comma)) {
1681     if (Lex.getKind() == lltok::MetadataVar) {
1682       if (Indices.empty()) return TokError("expected index");
1683       AteExtraComma = true;
1684       return false;
1685     }
1686     unsigned Idx = 0;
1687     if (ParseUInt32(Idx)) return true;
1688     Indices.push_back(Idx);
1689   }
1690
1691   return false;
1692 }
1693
1694 //===----------------------------------------------------------------------===//
1695 // Type Parsing.
1696 //===----------------------------------------------------------------------===//
1697
1698 /// ParseType - Parse a type.
1699 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1700   SMLoc TypeLoc = Lex.getLoc();
1701   switch (Lex.getKind()) {
1702   default:
1703     return TokError(Msg);
1704   case lltok::Type:
1705     // Type ::= 'float' | 'void' (etc)
1706     Result = Lex.getTyVal();
1707     Lex.Lex();
1708     break;
1709   case lltok::lbrace:
1710     // Type ::= StructType
1711     if (ParseAnonStructType(Result, false))
1712       return true;
1713     break;
1714   case lltok::lsquare:
1715     // Type ::= '[' ... ']'
1716     Lex.Lex(); // eat the lsquare.
1717     if (ParseArrayVectorType(Result, false))
1718       return true;
1719     break;
1720   case lltok::less: // Either vector or packed struct.
1721     // Type ::= '<' ... '>'
1722     Lex.Lex();
1723     if (Lex.getKind() == lltok::lbrace) {
1724       if (ParseAnonStructType(Result, true) ||
1725           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1726         return true;
1727     } else if (ParseArrayVectorType(Result, true))
1728       return true;
1729     break;
1730   case lltok::LocalVar: {
1731     // Type ::= %foo
1732     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1733
1734     // If the type hasn't been defined yet, create a forward definition and
1735     // remember where that forward def'n was seen (in case it never is defined).
1736     if (!Entry.first) {
1737       Entry.first = StructType::create(Context, Lex.getStrVal());
1738       Entry.second = Lex.getLoc();
1739     }
1740     Result = Entry.first;
1741     Lex.Lex();
1742     break;
1743   }
1744
1745   case lltok::LocalVarID: {
1746     // Type ::= %4
1747     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1748
1749     // If the type hasn't been defined yet, create a forward definition and
1750     // remember where that forward def'n was seen (in case it never is defined).
1751     if (!Entry.first) {
1752       Entry.first = StructType::create(Context);
1753       Entry.second = Lex.getLoc();
1754     }
1755     Result = Entry.first;
1756     Lex.Lex();
1757     break;
1758   }
1759   }
1760
1761   // Parse the type suffixes.
1762   while (1) {
1763     switch (Lex.getKind()) {
1764     // End of type.
1765     default:
1766       if (!AllowVoid && Result->isVoidTy())
1767         return Error(TypeLoc, "void type only allowed for function results");
1768       return false;
1769
1770     // Type ::= Type '*'
1771     case lltok::star:
1772       if (Result->isLabelTy())
1773         return TokError("basic block pointers are invalid");
1774       if (Result->isVoidTy())
1775         return TokError("pointers to void are invalid - use i8* instead");
1776       if (!PointerType::isValidElementType(Result))
1777         return TokError("pointer to this type is invalid");
1778       Result = PointerType::getUnqual(Result);
1779       Lex.Lex();
1780       break;
1781
1782     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1783     case lltok::kw_addrspace: {
1784       if (Result->isLabelTy())
1785         return TokError("basic block pointers are invalid");
1786       if (Result->isVoidTy())
1787         return TokError("pointers to void are invalid; use i8* instead");
1788       if (!PointerType::isValidElementType(Result))
1789         return TokError("pointer to this type is invalid");
1790       unsigned AddrSpace;
1791       if (ParseOptionalAddrSpace(AddrSpace) ||
1792           ParseToken(lltok::star, "expected '*' in address space"))
1793         return true;
1794
1795       Result = PointerType::get(Result, AddrSpace);
1796       break;
1797     }
1798
1799     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1800     case lltok::lparen:
1801       if (ParseFunctionType(Result))
1802         return true;
1803       break;
1804     }
1805   }
1806 }
1807
1808 /// ParseParameterList
1809 ///    ::= '(' ')'
1810 ///    ::= '(' Arg (',' Arg)* ')'
1811 ///  Arg
1812 ///    ::= Type OptionalAttributes Value OptionalAttributes
1813 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1814                                   PerFunctionState &PFS, bool IsMustTailCall,
1815                                   bool InVarArgsFunc) {
1816   if (ParseToken(lltok::lparen, "expected '(' in call"))
1817     return true;
1818
1819   unsigned AttrIndex = 1;
1820   while (Lex.getKind() != lltok::rparen) {
1821     // If this isn't the first argument, we need a comma.
1822     if (!ArgList.empty() &&
1823         ParseToken(lltok::comma, "expected ',' in argument list"))
1824       return true;
1825
1826     // Parse an ellipsis if this is a musttail call in a variadic function.
1827     if (Lex.getKind() == lltok::dotdotdot) {
1828       const char *Msg = "unexpected ellipsis in argument list for ";
1829       if (!IsMustTailCall)
1830         return TokError(Twine(Msg) + "non-musttail call");
1831       if (!InVarArgsFunc)
1832         return TokError(Twine(Msg) + "musttail call in non-varargs function");
1833       Lex.Lex();  // Lex the '...', it is purely for readability.
1834       return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1835     }
1836
1837     // Parse the argument.
1838     LocTy ArgLoc;
1839     Type *ArgTy = nullptr;
1840     AttrBuilder ArgAttrs;
1841     Value *V;
1842     if (ParseType(ArgTy, ArgLoc))
1843       return true;
1844
1845     if (ArgTy->isMetadataTy()) {
1846       if (ParseMetadataAsValue(V, PFS))
1847         return true;
1848     } else {
1849       // Otherwise, handle normal operands.
1850       if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1851         return true;
1852     }
1853     ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1854                                                              AttrIndex++,
1855                                                              ArgAttrs)));
1856   }
1857
1858   if (IsMustTailCall && InVarArgsFunc)
1859     return TokError("expected '...' at end of argument list for musttail call "
1860                     "in varargs function");
1861
1862   Lex.Lex();  // Lex the ')'.
1863   return false;
1864 }
1865
1866
1867
1868 /// ParseArgumentList - Parse the argument list for a function type or function
1869 /// prototype.
1870 ///   ::= '(' ArgTypeListI ')'
1871 /// ArgTypeListI
1872 ///   ::= /*empty*/
1873 ///   ::= '...'
1874 ///   ::= ArgTypeList ',' '...'
1875 ///   ::= ArgType (',' ArgType)*
1876 ///
1877 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1878                                  bool &isVarArg){
1879   isVarArg = false;
1880   assert(Lex.getKind() == lltok::lparen);
1881   Lex.Lex(); // eat the (.
1882
1883   if (Lex.getKind() == lltok::rparen) {
1884     // empty
1885   } else if (Lex.getKind() == lltok::dotdotdot) {
1886     isVarArg = true;
1887     Lex.Lex();
1888   } else {
1889     LocTy TypeLoc = Lex.getLoc();
1890     Type *ArgTy = nullptr;
1891     AttrBuilder Attrs;
1892     std::string Name;
1893
1894     if (ParseType(ArgTy) ||
1895         ParseOptionalParamAttrs(Attrs)) return true;
1896
1897     if (ArgTy->isVoidTy())
1898       return Error(TypeLoc, "argument can not have void type");
1899
1900     if (Lex.getKind() == lltok::LocalVar) {
1901       Name = Lex.getStrVal();
1902       Lex.Lex();
1903     }
1904
1905     if (!FunctionType::isValidArgumentType(ArgTy))
1906       return Error(TypeLoc, "invalid type for function argument");
1907
1908     unsigned AttrIndex = 1;
1909     ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1910                               AttributeSet::get(ArgTy->getContext(),
1911                                                 AttrIndex++, Attrs), Name));
1912
1913     while (EatIfPresent(lltok::comma)) {
1914       // Handle ... at end of arg list.
1915       if (EatIfPresent(lltok::dotdotdot)) {
1916         isVarArg = true;
1917         break;
1918       }
1919
1920       // Otherwise must be an argument type.
1921       TypeLoc = Lex.getLoc();
1922       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1923
1924       if (ArgTy->isVoidTy())
1925         return Error(TypeLoc, "argument can not have void type");
1926
1927       if (Lex.getKind() == lltok::LocalVar) {
1928         Name = Lex.getStrVal();
1929         Lex.Lex();
1930       } else {
1931         Name = "";
1932       }
1933
1934       if (!ArgTy->isFirstClassType())
1935         return Error(TypeLoc, "invalid type for function argument");
1936
1937       ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1938                                 AttributeSet::get(ArgTy->getContext(),
1939                                                   AttrIndex++, Attrs),
1940                                 Name));
1941     }
1942   }
1943
1944   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1945 }
1946
1947 /// ParseFunctionType
1948 ///  ::= Type ArgumentList OptionalAttrs
1949 bool LLParser::ParseFunctionType(Type *&Result) {
1950   assert(Lex.getKind() == lltok::lparen);
1951
1952   if (!FunctionType::isValidReturnType(Result))
1953     return TokError("invalid function return type");
1954
1955   SmallVector<ArgInfo, 8> ArgList;
1956   bool isVarArg;
1957   if (ParseArgumentList(ArgList, isVarArg))
1958     return true;
1959
1960   // Reject names on the arguments lists.
1961   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1962     if (!ArgList[i].Name.empty())
1963       return Error(ArgList[i].Loc, "argument name invalid in function type");
1964     if (ArgList[i].Attrs.hasAttributes(i + 1))
1965       return Error(ArgList[i].Loc,
1966                    "argument attributes invalid in function type");
1967   }
1968
1969   SmallVector<Type*, 16> ArgListTy;
1970   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1971     ArgListTy.push_back(ArgList[i].Ty);
1972
1973   Result = FunctionType::get(Result, ArgListTy, isVarArg);
1974   return false;
1975 }
1976
1977 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1978 /// other structs.
1979 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1980   SmallVector<Type*, 8> Elts;
1981   if (ParseStructBody(Elts)) return true;
1982
1983   Result = StructType::get(Context, Elts, Packed);
1984   return false;
1985 }
1986
1987 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1988 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1989                                      std::pair<Type*, LocTy> &Entry,
1990                                      Type *&ResultTy) {
1991   // If the type was already defined, diagnose the redefinition.
1992   if (Entry.first && !Entry.second.isValid())
1993     return Error(TypeLoc, "redefinition of type");
1994
1995   // If we have opaque, just return without filling in the definition for the
1996   // struct.  This counts as a definition as far as the .ll file goes.
1997   if (EatIfPresent(lltok::kw_opaque)) {
1998     // This type is being defined, so clear the location to indicate this.
1999     Entry.second = SMLoc();
2000
2001     // If this type number has never been uttered, create it.
2002     if (!Entry.first)
2003       Entry.first = StructType::create(Context, Name);
2004     ResultTy = Entry.first;
2005     return false;
2006   }
2007
2008   // If the type starts with '<', then it is either a packed struct or a vector.
2009   bool isPacked = EatIfPresent(lltok::less);
2010
2011   // If we don't have a struct, then we have a random type alias, which we
2012   // accept for compatibility with old files.  These types are not allowed to be
2013   // forward referenced and not allowed to be recursive.
2014   if (Lex.getKind() != lltok::lbrace) {
2015     if (Entry.first)
2016       return Error(TypeLoc, "forward references to non-struct type");
2017
2018     ResultTy = nullptr;
2019     if (isPacked)
2020       return ParseArrayVectorType(ResultTy, true);
2021     return ParseType(ResultTy);
2022   }
2023
2024   // This type is being defined, so clear the location to indicate this.
2025   Entry.second = SMLoc();
2026
2027   // If this type number has never been uttered, create it.
2028   if (!Entry.first)
2029     Entry.first = StructType::create(Context, Name);
2030
2031   StructType *STy = cast<StructType>(Entry.first);
2032
2033   SmallVector<Type*, 8> Body;
2034   if (ParseStructBody(Body) ||
2035       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2036     return true;
2037
2038   STy->setBody(Body, isPacked);
2039   ResultTy = STy;
2040   return false;
2041 }
2042
2043
2044 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2045 ///   StructType
2046 ///     ::= '{' '}'
2047 ///     ::= '{' Type (',' Type)* '}'
2048 ///     ::= '<' '{' '}' '>'
2049 ///     ::= '<' '{' Type (',' Type)* '}' '>'
2050 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2051   assert(Lex.getKind() == lltok::lbrace);
2052   Lex.Lex(); // Consume the '{'
2053
2054   // Handle the empty struct.
2055   if (EatIfPresent(lltok::rbrace))
2056     return false;
2057
2058   LocTy EltTyLoc = Lex.getLoc();
2059   Type *Ty = nullptr;
2060   if (ParseType(Ty)) return true;
2061   Body.push_back(Ty);
2062
2063   if (!StructType::isValidElementType(Ty))
2064     return Error(EltTyLoc, "invalid element type for struct");
2065
2066   while (EatIfPresent(lltok::comma)) {
2067     EltTyLoc = Lex.getLoc();
2068     if (ParseType(Ty)) return true;
2069
2070     if (!StructType::isValidElementType(Ty))
2071       return Error(EltTyLoc, "invalid element type for struct");
2072
2073     Body.push_back(Ty);
2074   }
2075
2076   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2077 }
2078
2079 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2080 /// token has already been consumed.
2081 ///   Type
2082 ///     ::= '[' APSINTVAL 'x' Types ']'
2083 ///     ::= '<' APSINTVAL 'x' Types '>'
2084 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2085   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2086       Lex.getAPSIntVal().getBitWidth() > 64)
2087     return TokError("expected number in address space");
2088
2089   LocTy SizeLoc = Lex.getLoc();
2090   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2091   Lex.Lex();
2092
2093   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2094       return true;
2095
2096   LocTy TypeLoc = Lex.getLoc();
2097   Type *EltTy = nullptr;
2098   if (ParseType(EltTy)) return true;
2099
2100   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2101                  "expected end of sequential type"))
2102     return true;
2103
2104   if (isVector) {
2105     if (Size == 0)
2106       return Error(SizeLoc, "zero element vector is illegal");
2107     if ((unsigned)Size != Size)
2108       return Error(SizeLoc, "size too large for vector");
2109     if (!VectorType::isValidElementType(EltTy))
2110       return Error(TypeLoc, "invalid vector element type");
2111     Result = VectorType::get(EltTy, unsigned(Size));
2112   } else {
2113     if (!ArrayType::isValidElementType(EltTy))
2114       return Error(TypeLoc, "invalid array element type");
2115     Result = ArrayType::get(EltTy, Size);
2116   }
2117   return false;
2118 }
2119
2120 //===----------------------------------------------------------------------===//
2121 // Function Semantic Analysis.
2122 //===----------------------------------------------------------------------===//
2123
2124 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2125                                              int functionNumber)
2126   : P(p), F(f), FunctionNumber(functionNumber) {
2127
2128   // Insert unnamed arguments into the NumberedVals list.
2129   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2130        AI != E; ++AI)
2131     if (!AI->hasName())
2132       NumberedVals.push_back(AI);
2133 }
2134
2135 LLParser::PerFunctionState::~PerFunctionState() {
2136   // If there were any forward referenced non-basicblock values, delete them.
2137   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2138        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2139     if (!isa<BasicBlock>(I->second.first)) {
2140       I->second.first->replaceAllUsesWith(
2141                            UndefValue::get(I->second.first->getType()));
2142       delete I->second.first;
2143       I->second.first = nullptr;
2144     }
2145
2146   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2147        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2148     if (!isa<BasicBlock>(I->second.first)) {
2149       I->second.first->replaceAllUsesWith(
2150                            UndefValue::get(I->second.first->getType()));
2151       delete I->second.first;
2152       I->second.first = nullptr;
2153     }
2154 }
2155
2156 bool LLParser::PerFunctionState::FinishFunction() {
2157   if (!ForwardRefVals.empty())
2158     return P.Error(ForwardRefVals.begin()->second.second,
2159                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2160                    "'");
2161   if (!ForwardRefValIDs.empty())
2162     return P.Error(ForwardRefValIDs.begin()->second.second,
2163                    "use of undefined value '%" +
2164                    Twine(ForwardRefValIDs.begin()->first) + "'");
2165   return false;
2166 }
2167
2168
2169 /// GetVal - Get a value with the specified name or ID, creating a
2170 /// forward reference record if needed.  This can return null if the value
2171 /// exists but does not have the right type.
2172 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2173                                           Type *Ty, LocTy Loc) {
2174   // Look this name up in the normal function symbol table.
2175   Value *Val = F.getValueSymbolTable().lookup(Name);
2176
2177   // If this is a forward reference for the value, see if we already created a
2178   // forward ref record.
2179   if (!Val) {
2180     std::map<std::string, std::pair<Value*, LocTy> >::iterator
2181       I = ForwardRefVals.find(Name);
2182     if (I != ForwardRefVals.end())
2183       Val = I->second.first;
2184   }
2185
2186   // If we have the value in the symbol table or fwd-ref table, return it.
2187   if (Val) {
2188     if (Val->getType() == Ty) return Val;
2189     if (Ty->isLabelTy())
2190       P.Error(Loc, "'%" + Name + "' is not a basic block");
2191     else
2192       P.Error(Loc, "'%" + Name + "' defined with type '" +
2193               getTypeString(Val->getType()) + "'");
2194     return nullptr;
2195   }
2196
2197   // Don't make placeholders with invalid type.
2198   if (!Ty->isFirstClassType()) {
2199     P.Error(Loc, "invalid use of a non-first-class type");
2200     return nullptr;
2201   }
2202
2203   // Otherwise, create a new forward reference for this value and remember it.
2204   Value *FwdVal;
2205   if (Ty->isLabelTy())
2206     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2207   else
2208     FwdVal = new Argument(Ty, Name);
2209
2210   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2211   return FwdVal;
2212 }
2213
2214 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2215                                           LocTy Loc) {
2216   // Look this name up in the normal function symbol table.
2217   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2218
2219   // If this is a forward reference for the value, see if we already created a
2220   // forward ref record.
2221   if (!Val) {
2222     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2223       I = ForwardRefValIDs.find(ID);
2224     if (I != ForwardRefValIDs.end())
2225       Val = I->second.first;
2226   }
2227
2228   // If we have the value in the symbol table or fwd-ref table, return it.
2229   if (Val) {
2230     if (Val->getType() == Ty) return Val;
2231     if (Ty->isLabelTy())
2232       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2233     else
2234       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2235               getTypeString(Val->getType()) + "'");
2236     return nullptr;
2237   }
2238
2239   if (!Ty->isFirstClassType()) {
2240     P.Error(Loc, "invalid use of a non-first-class type");
2241     return nullptr;
2242   }
2243
2244   // Otherwise, create a new forward reference for this value and remember it.
2245   Value *FwdVal;
2246   if (Ty->isLabelTy())
2247     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2248   else
2249     FwdVal = new Argument(Ty);
2250
2251   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2252   return FwdVal;
2253 }
2254
2255 /// SetInstName - After an instruction is parsed and inserted into its
2256 /// basic block, this installs its name.
2257 bool LLParser::PerFunctionState::SetInstName(int NameID,
2258                                              const std::string &NameStr,
2259                                              LocTy NameLoc, Instruction *Inst) {
2260   // If this instruction has void type, it cannot have a name or ID specified.
2261   if (Inst->getType()->isVoidTy()) {
2262     if (NameID != -1 || !NameStr.empty())
2263       return P.Error(NameLoc, "instructions returning void cannot have a name");
2264     return false;
2265   }
2266
2267   // If this was a numbered instruction, verify that the instruction is the
2268   // expected value and resolve any forward references.
2269   if (NameStr.empty()) {
2270     // If neither a name nor an ID was specified, just use the next ID.
2271     if (NameID == -1)
2272       NameID = NumberedVals.size();
2273
2274     if (unsigned(NameID) != NumberedVals.size())
2275       return P.Error(NameLoc, "instruction expected to be numbered '%" +
2276                      Twine(NumberedVals.size()) + "'");
2277
2278     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2279       ForwardRefValIDs.find(NameID);
2280     if (FI != ForwardRefValIDs.end()) {
2281       if (FI->second.first->getType() != Inst->getType())
2282         return P.Error(NameLoc, "instruction forward referenced with type '" +
2283                        getTypeString(FI->second.first->getType()) + "'");
2284       FI->second.first->replaceAllUsesWith(Inst);
2285       delete FI->second.first;
2286       ForwardRefValIDs.erase(FI);
2287     }
2288
2289     NumberedVals.push_back(Inst);
2290     return false;
2291   }
2292
2293   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2294   std::map<std::string, std::pair<Value*, LocTy> >::iterator
2295     FI = ForwardRefVals.find(NameStr);
2296   if (FI != ForwardRefVals.end()) {
2297     if (FI->second.first->getType() != Inst->getType())
2298       return P.Error(NameLoc, "instruction forward referenced with type '" +
2299                      getTypeString(FI->second.first->getType()) + "'");
2300     FI->second.first->replaceAllUsesWith(Inst);
2301     delete FI->second.first;
2302     ForwardRefVals.erase(FI);
2303   }
2304
2305   // Set the name on the instruction.
2306   Inst->setName(NameStr);
2307
2308   if (Inst->getName() != NameStr)
2309     return P.Error(NameLoc, "multiple definition of local value named '" +
2310                    NameStr + "'");
2311   return false;
2312 }
2313
2314 /// GetBB - Get a basic block with the specified name or ID, creating a
2315 /// forward reference record if needed.
2316 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2317                                               LocTy Loc) {
2318   return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2319                                       Type::getLabelTy(F.getContext()), Loc));
2320 }
2321
2322 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2323   return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2324                                       Type::getLabelTy(F.getContext()), Loc));
2325 }
2326
2327 /// DefineBB - Define the specified basic block, which is either named or
2328 /// unnamed.  If there is an error, this returns null otherwise it returns
2329 /// the block being defined.
2330 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2331                                                  LocTy Loc) {
2332   BasicBlock *BB;
2333   if (Name.empty())
2334     BB = GetBB(NumberedVals.size(), Loc);
2335   else
2336     BB = GetBB(Name, Loc);
2337   if (!BB) return nullptr; // Already diagnosed error.
2338
2339   // Move the block to the end of the function.  Forward ref'd blocks are
2340   // inserted wherever they happen to be referenced.
2341   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2342
2343   // Remove the block from forward ref sets.
2344   if (Name.empty()) {
2345     ForwardRefValIDs.erase(NumberedVals.size());
2346     NumberedVals.push_back(BB);
2347   } else {
2348     // BB forward references are already in the function symbol table.
2349     ForwardRefVals.erase(Name);
2350   }
2351
2352   return BB;
2353 }
2354
2355 //===----------------------------------------------------------------------===//
2356 // Constants.
2357 //===----------------------------------------------------------------------===//
2358
2359 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2360 /// type implied.  For example, if we parse "4" we don't know what integer type
2361 /// it has.  The value will later be combined with its type and checked for
2362 /// sanity.  PFS is used to convert function-local operands of metadata (since
2363 /// metadata operands are not just parsed here but also converted to values).
2364 /// PFS can be null when we are not parsing metadata values inside a function.
2365 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2366   ID.Loc = Lex.getLoc();
2367   switch (Lex.getKind()) {
2368   default: return TokError("expected value token");
2369   case lltok::GlobalID:  // @42
2370     ID.UIntVal = Lex.getUIntVal();
2371     ID.Kind = ValID::t_GlobalID;
2372     break;
2373   case lltok::GlobalVar:  // @foo
2374     ID.StrVal = Lex.getStrVal();
2375     ID.Kind = ValID::t_GlobalName;
2376     break;
2377   case lltok::LocalVarID:  // %42
2378     ID.UIntVal = Lex.getUIntVal();
2379     ID.Kind = ValID::t_LocalID;
2380     break;
2381   case lltok::LocalVar:  // %foo
2382     ID.StrVal = Lex.getStrVal();
2383     ID.Kind = ValID::t_LocalName;
2384     break;
2385   case lltok::APSInt:
2386     ID.APSIntVal = Lex.getAPSIntVal();
2387     ID.Kind = ValID::t_APSInt;
2388     break;
2389   case lltok::APFloat:
2390     ID.APFloatVal = Lex.getAPFloatVal();
2391     ID.Kind = ValID::t_APFloat;
2392     break;
2393   case lltok::kw_true:
2394     ID.ConstantVal = ConstantInt::getTrue(Context);
2395     ID.Kind = ValID::t_Constant;
2396     break;
2397   case lltok::kw_false:
2398     ID.ConstantVal = ConstantInt::getFalse(Context);
2399     ID.Kind = ValID::t_Constant;
2400     break;
2401   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2402   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2403   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2404
2405   case lltok::lbrace: {
2406     // ValID ::= '{' ConstVector '}'
2407     Lex.Lex();
2408     SmallVector<Constant*, 16> Elts;
2409     if (ParseGlobalValueVector(Elts) ||
2410         ParseToken(lltok::rbrace, "expected end of struct constant"))
2411       return true;
2412
2413     ID.ConstantStructElts = new Constant*[Elts.size()];
2414     ID.UIntVal = Elts.size();
2415     memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2416     ID.Kind = ValID::t_ConstantStruct;
2417     return false;
2418   }
2419   case lltok::less: {
2420     // ValID ::= '<' ConstVector '>'         --> Vector.
2421     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2422     Lex.Lex();
2423     bool isPackedStruct = EatIfPresent(lltok::lbrace);
2424
2425     SmallVector<Constant*, 16> Elts;
2426     LocTy FirstEltLoc = Lex.getLoc();
2427     if (ParseGlobalValueVector(Elts) ||
2428         (isPackedStruct &&
2429          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2430         ParseToken(lltok::greater, "expected end of constant"))
2431       return true;
2432
2433     if (isPackedStruct) {
2434       ID.ConstantStructElts = new Constant*[Elts.size()];
2435       memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2436       ID.UIntVal = Elts.size();
2437       ID.Kind = ValID::t_PackedConstantStruct;
2438       return false;
2439     }
2440
2441     if (Elts.empty())
2442       return Error(ID.Loc, "constant vector must not be empty");
2443
2444     if (!Elts[0]->getType()->isIntegerTy() &&
2445         !Elts[0]->getType()->isFloatingPointTy() &&
2446         !Elts[0]->getType()->isPointerTy())
2447       return Error(FirstEltLoc,
2448             "vector elements must have integer, pointer or floating point type");
2449
2450     // Verify that all the vector elements have the same type.
2451     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2452       if (Elts[i]->getType() != Elts[0]->getType())
2453         return Error(FirstEltLoc,
2454                      "vector element #" + Twine(i) +
2455                     " is not of type '" + getTypeString(Elts[0]->getType()));
2456
2457     ID.ConstantVal = ConstantVector::get(Elts);
2458     ID.Kind = ValID::t_Constant;
2459     return false;
2460   }
2461   case lltok::lsquare: {   // Array Constant
2462     Lex.Lex();
2463     SmallVector<Constant*, 16> Elts;
2464     LocTy FirstEltLoc = Lex.getLoc();
2465     if (ParseGlobalValueVector(Elts) ||
2466         ParseToken(lltok::rsquare, "expected end of array constant"))
2467       return true;
2468
2469     // Handle empty element.
2470     if (Elts.empty()) {
2471       // Use undef instead of an array because it's inconvenient to determine
2472       // the element type at this point, there being no elements to examine.
2473       ID.Kind = ValID::t_EmptyArray;
2474       return false;
2475     }
2476
2477     if (!Elts[0]->getType()->isFirstClassType())
2478       return Error(FirstEltLoc, "invalid array element type: " +
2479                    getTypeString(Elts[0]->getType()));
2480
2481     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2482
2483     // Verify all elements are correct type!
2484     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2485       if (Elts[i]->getType() != Elts[0]->getType())
2486         return Error(FirstEltLoc,
2487                      "array element #" + Twine(i) +
2488                      " is not of type '" + getTypeString(Elts[0]->getType()));
2489     }
2490
2491     ID.ConstantVal = ConstantArray::get(ATy, Elts);
2492     ID.Kind = ValID::t_Constant;
2493     return false;
2494   }
2495   case lltok::kw_c:  // c "foo"
2496     Lex.Lex();
2497     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2498                                                   false);
2499     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2500     ID.Kind = ValID::t_Constant;
2501     return false;
2502
2503   case lltok::kw_asm: {
2504     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2505     //             STRINGCONSTANT
2506     bool HasSideEffect, AlignStack, AsmDialect;
2507     Lex.Lex();
2508     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2509         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2510         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2511         ParseStringConstant(ID.StrVal) ||
2512         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2513         ParseToken(lltok::StringConstant, "expected constraint string"))
2514       return true;
2515     ID.StrVal2 = Lex.getStrVal();
2516     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2517       (unsigned(AsmDialect)<<2);
2518     ID.Kind = ValID::t_InlineAsm;
2519     return false;
2520   }
2521
2522   case lltok::kw_blockaddress: {
2523     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2524     Lex.Lex();
2525
2526     ValID Fn, Label;
2527
2528     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2529         ParseValID(Fn) ||
2530         ParseToken(lltok::comma, "expected comma in block address expression")||
2531         ParseValID(Label) ||
2532         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2533       return true;
2534
2535     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2536       return Error(Fn.Loc, "expected function name in blockaddress");
2537     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2538       return Error(Label.Loc, "expected basic block name in blockaddress");
2539
2540     // Try to find the function (but skip it if it's forward-referenced).
2541     GlobalValue *GV = nullptr;
2542     if (Fn.Kind == ValID::t_GlobalID) {
2543       if (Fn.UIntVal < NumberedVals.size())
2544         GV = NumberedVals[Fn.UIntVal];
2545     } else if (!ForwardRefVals.count(Fn.StrVal)) {
2546       GV = M->getNamedValue(Fn.StrVal);
2547     }
2548     Function *F = nullptr;
2549     if (GV) {
2550       // Confirm that it's actually a function with a definition.
2551       if (!isa<Function>(GV))
2552         return Error(Fn.Loc, "expected function name in blockaddress");
2553       F = cast<Function>(GV);
2554       if (F->isDeclaration())
2555         return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2556     }
2557
2558     if (!F) {
2559       // Make a global variable as a placeholder for this reference.
2560       GlobalValue *&FwdRef =
2561           ForwardRefBlockAddresses.insert(std::make_pair(
2562                                               std::move(Fn),
2563                                               std::map<ValID, GlobalValue *>()))
2564               .first->second.insert(std::make_pair(std::move(Label), nullptr))
2565               .first->second;
2566       if (!FwdRef)
2567         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2568                                     GlobalValue::InternalLinkage, nullptr, "");
2569       ID.ConstantVal = FwdRef;
2570       ID.Kind = ValID::t_Constant;
2571       return false;
2572     }
2573
2574     // We found the function; now find the basic block.  Don't use PFS, since we
2575     // might be inside a constant expression.
2576     BasicBlock *BB;
2577     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2578       if (Label.Kind == ValID::t_LocalID)
2579         BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2580       else
2581         BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2582       if (!BB)
2583         return Error(Label.Loc, "referenced value is not a basic block");
2584     } else {
2585       if (Label.Kind == ValID::t_LocalID)
2586         return Error(Label.Loc, "cannot take address of numeric label after "
2587                                 "the function is defined");
2588       BB = dyn_cast_or_null<BasicBlock>(
2589           F->getValueSymbolTable().lookup(Label.StrVal));
2590       if (!BB)
2591         return Error(Label.Loc, "referenced value is not a basic block");
2592     }
2593
2594     ID.ConstantVal = BlockAddress::get(F, BB);
2595     ID.Kind = ValID::t_Constant;
2596     return false;
2597   }
2598
2599   case lltok::kw_trunc:
2600   case lltok::kw_zext:
2601   case lltok::kw_sext:
2602   case lltok::kw_fptrunc:
2603   case lltok::kw_fpext:
2604   case lltok::kw_bitcast:
2605   case lltok::kw_addrspacecast:
2606   case lltok::kw_uitofp:
2607   case lltok::kw_sitofp:
2608   case lltok::kw_fptoui:
2609   case lltok::kw_fptosi:
2610   case lltok::kw_inttoptr:
2611   case lltok::kw_ptrtoint: {
2612     unsigned Opc = Lex.getUIntVal();
2613     Type *DestTy = nullptr;
2614     Constant *SrcVal;
2615     Lex.Lex();
2616     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2617         ParseGlobalTypeAndValue(SrcVal) ||
2618         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2619         ParseType(DestTy) ||
2620         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2621       return true;
2622     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2623       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2624                    getTypeString(SrcVal->getType()) + "' to '" +
2625                    getTypeString(DestTy) + "'");
2626     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2627                                                  SrcVal, DestTy);
2628     ID.Kind = ValID::t_Constant;
2629     return false;
2630   }
2631   case lltok::kw_extractvalue: {
2632     Lex.Lex();
2633     Constant *Val;
2634     SmallVector<unsigned, 4> Indices;
2635     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2636         ParseGlobalTypeAndValue(Val) ||
2637         ParseIndexList(Indices) ||
2638         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2639       return true;
2640
2641     if (!Val->getType()->isAggregateType())
2642       return Error(ID.Loc, "extractvalue operand must be aggregate type");
2643     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2644       return Error(ID.Loc, "invalid indices for extractvalue");
2645     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2646     ID.Kind = ValID::t_Constant;
2647     return false;
2648   }
2649   case lltok::kw_insertvalue: {
2650     Lex.Lex();
2651     Constant *Val0, *Val1;
2652     SmallVector<unsigned, 4> Indices;
2653     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2654         ParseGlobalTypeAndValue(Val0) ||
2655         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2656         ParseGlobalTypeAndValue(Val1) ||
2657         ParseIndexList(Indices) ||
2658         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2659       return true;
2660     if (!Val0->getType()->isAggregateType())
2661       return Error(ID.Loc, "insertvalue operand must be aggregate type");
2662     Type *IndexedType =
2663         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2664     if (!IndexedType)
2665       return Error(ID.Loc, "invalid indices for insertvalue");
2666     if (IndexedType != Val1->getType())
2667       return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2668                                getTypeString(Val1->getType()) +
2669                                "' instead of '" + getTypeString(IndexedType) +
2670                                "'");
2671     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2672     ID.Kind = ValID::t_Constant;
2673     return false;
2674   }
2675   case lltok::kw_icmp:
2676   case lltok::kw_fcmp: {
2677     unsigned PredVal, Opc = Lex.getUIntVal();
2678     Constant *Val0, *Val1;
2679     Lex.Lex();
2680     if (ParseCmpPredicate(PredVal, Opc) ||
2681         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2682         ParseGlobalTypeAndValue(Val0) ||
2683         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2684         ParseGlobalTypeAndValue(Val1) ||
2685         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2686       return true;
2687
2688     if (Val0->getType() != Val1->getType())
2689       return Error(ID.Loc, "compare operands must have the same type");
2690
2691     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2692
2693     if (Opc == Instruction::FCmp) {
2694       if (!Val0->getType()->isFPOrFPVectorTy())
2695         return Error(ID.Loc, "fcmp requires floating point operands");
2696       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2697     } else {
2698       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2699       if (!Val0->getType()->isIntOrIntVectorTy() &&
2700           !Val0->getType()->getScalarType()->isPointerTy())
2701         return Error(ID.Loc, "icmp requires pointer or integer operands");
2702       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2703     }
2704     ID.Kind = ValID::t_Constant;
2705     return false;
2706   }
2707
2708   // Binary Operators.
2709   case lltok::kw_add:
2710   case lltok::kw_fadd:
2711   case lltok::kw_sub:
2712   case lltok::kw_fsub:
2713   case lltok::kw_mul:
2714   case lltok::kw_fmul:
2715   case lltok::kw_udiv:
2716   case lltok::kw_sdiv:
2717   case lltok::kw_fdiv:
2718   case lltok::kw_urem:
2719   case lltok::kw_srem:
2720   case lltok::kw_frem:
2721   case lltok::kw_shl:
2722   case lltok::kw_lshr:
2723   case lltok::kw_ashr: {
2724     bool NUW = false;
2725     bool NSW = false;
2726     bool Exact = false;
2727     unsigned Opc = Lex.getUIntVal();
2728     Constant *Val0, *Val1;
2729     Lex.Lex();
2730     LocTy ModifierLoc = Lex.getLoc();
2731     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2732         Opc == Instruction::Mul || Opc == Instruction::Shl) {
2733       if (EatIfPresent(lltok::kw_nuw))
2734         NUW = true;
2735       if (EatIfPresent(lltok::kw_nsw)) {
2736         NSW = true;
2737         if (EatIfPresent(lltok::kw_nuw))
2738           NUW = true;
2739       }
2740     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2741                Opc == Instruction::LShr || Opc == Instruction::AShr) {
2742       if (EatIfPresent(lltok::kw_exact))
2743         Exact = true;
2744     }
2745     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2746         ParseGlobalTypeAndValue(Val0) ||
2747         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2748         ParseGlobalTypeAndValue(Val1) ||
2749         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2750       return true;
2751     if (Val0->getType() != Val1->getType())
2752       return Error(ID.Loc, "operands of constexpr must have same type");
2753     if (!Val0->getType()->isIntOrIntVectorTy()) {
2754       if (NUW)
2755         return Error(ModifierLoc, "nuw only applies to integer operations");
2756       if (NSW)
2757         return Error(ModifierLoc, "nsw only applies to integer operations");
2758     }
2759     // Check that the type is valid for the operator.
2760     switch (Opc) {
2761     case Instruction::Add:
2762     case Instruction::Sub:
2763     case Instruction::Mul:
2764     case Instruction::UDiv:
2765     case Instruction::SDiv:
2766     case Instruction::URem:
2767     case Instruction::SRem:
2768     case Instruction::Shl:
2769     case Instruction::AShr:
2770     case Instruction::LShr:
2771       if (!Val0->getType()->isIntOrIntVectorTy())
2772         return Error(ID.Loc, "constexpr requires integer operands");
2773       break;
2774     case Instruction::FAdd:
2775     case Instruction::FSub:
2776     case Instruction::FMul:
2777     case Instruction::FDiv:
2778     case Instruction::FRem:
2779       if (!Val0->getType()->isFPOrFPVectorTy())
2780         return Error(ID.Loc, "constexpr requires fp operands");
2781       break;
2782     default: llvm_unreachable("Unknown binary operator!");
2783     }
2784     unsigned Flags = 0;
2785     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2786     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2787     if (Exact) Flags |= PossiblyExactOperator::IsExact;
2788     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2789     ID.ConstantVal = C;
2790     ID.Kind = ValID::t_Constant;
2791     return false;
2792   }
2793
2794   // Logical Operations
2795   case lltok::kw_and:
2796   case lltok::kw_or:
2797   case lltok::kw_xor: {
2798     unsigned Opc = Lex.getUIntVal();
2799     Constant *Val0, *Val1;
2800     Lex.Lex();
2801     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2802         ParseGlobalTypeAndValue(Val0) ||
2803         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2804         ParseGlobalTypeAndValue(Val1) ||
2805         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2806       return true;
2807     if (Val0->getType() != Val1->getType())
2808       return Error(ID.Loc, "operands of constexpr must have same type");
2809     if (!Val0->getType()->isIntOrIntVectorTy())
2810       return Error(ID.Loc,
2811                    "constexpr requires integer or integer vector operands");
2812     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2813     ID.Kind = ValID::t_Constant;
2814     return false;
2815   }
2816
2817   case lltok::kw_getelementptr:
2818   case lltok::kw_shufflevector:
2819   case lltok::kw_insertelement:
2820   case lltok::kw_extractelement:
2821   case lltok::kw_select: {
2822     unsigned Opc = Lex.getUIntVal();
2823     SmallVector<Constant*, 16> Elts;
2824     bool InBounds = false;
2825     Type *Ty;
2826     Lex.Lex();
2827
2828     if (Opc == Instruction::GetElementPtr)
2829       InBounds = EatIfPresent(lltok::kw_inbounds);
2830
2831     if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2832       return true;
2833
2834     LocTy ExplicitTypeLoc = Lex.getLoc();
2835     if (Opc == Instruction::GetElementPtr) {
2836       if (ParseType(Ty) ||
2837           ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2838         return true;
2839     }
2840
2841     if (ParseGlobalValueVector(Elts) ||
2842         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2843       return true;
2844
2845     if (Opc == Instruction::GetElementPtr) {
2846       if (Elts.size() == 0 ||
2847           !Elts[0]->getType()->getScalarType()->isPointerTy())
2848         return Error(ID.Loc, "base of getelementptr must be a pointer");
2849
2850       Type *BaseType = Elts[0]->getType();
2851       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2852       if (Ty != BasePointerType->getElementType())
2853         return Error(
2854             ExplicitTypeLoc,
2855             "explicit pointee type doesn't match operand's pointee type");
2856
2857       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2858       for (Constant *Val : Indices) {
2859         Type *ValTy = Val->getType();
2860         if (!ValTy->getScalarType()->isIntegerTy())
2861           return Error(ID.Loc, "getelementptr index must be an integer");
2862         if (ValTy->isVectorTy() != BaseType->isVectorTy())
2863           return Error(ID.Loc, "getelementptr index type missmatch");
2864         if (ValTy->isVectorTy()) {
2865           unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2866           unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2867           if (ValNumEl != PtrNumEl)
2868             return Error(
2869                 ID.Loc,
2870                 "getelementptr vector index has a wrong number of elements");
2871         }
2872       }
2873
2874       SmallPtrSet<const Type*, 4> Visited;
2875       if (!Indices.empty() && !Ty->isSized(&Visited))
2876         return Error(ID.Loc, "base element of getelementptr must be sized");
2877
2878       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2879         return Error(ID.Loc, "invalid getelementptr indices");
2880       ID.ConstantVal =
2881           ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2882     } else if (Opc == Instruction::Select) {
2883       if (Elts.size() != 3)
2884         return Error(ID.Loc, "expected three operands to select");
2885       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2886                                                               Elts[2]))
2887         return Error(ID.Loc, Reason);
2888       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2889     } else if (Opc == Instruction::ShuffleVector) {
2890       if (Elts.size() != 3)
2891         return Error(ID.Loc, "expected three operands to shufflevector");
2892       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2893         return Error(ID.Loc, "invalid operands to shufflevector");
2894       ID.ConstantVal =
2895                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2896     } else if (Opc == Instruction::ExtractElement) {
2897       if (Elts.size() != 2)
2898         return Error(ID.Loc, "expected two operands to extractelement");
2899       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2900         return Error(ID.Loc, "invalid extractelement operands");
2901       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2902     } else {
2903       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2904       if (Elts.size() != 3)
2905       return Error(ID.Loc, "expected three operands to insertelement");
2906       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2907         return Error(ID.Loc, "invalid insertelement operands");
2908       ID.ConstantVal =
2909                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2910     }
2911
2912     ID.Kind = ValID::t_Constant;
2913     return false;
2914   }
2915   }
2916
2917   Lex.Lex();
2918   return false;
2919 }
2920
2921 /// ParseGlobalValue - Parse a global value with the specified type.
2922 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2923   C = nullptr;
2924   ValID ID;
2925   Value *V = nullptr;
2926   bool Parsed = ParseValID(ID) ||
2927                 ConvertValIDToValue(Ty, ID, V, nullptr);
2928   if (V && !(C = dyn_cast<Constant>(V)))
2929     return Error(ID.Loc, "global values must be constants");
2930   return Parsed;
2931 }
2932
2933 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2934   Type *Ty = nullptr;
2935   return ParseType(Ty) ||
2936          ParseGlobalValue(Ty, V);
2937 }
2938
2939 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2940   C = nullptr;
2941
2942   LocTy KwLoc = Lex.getLoc();
2943   if (!EatIfPresent(lltok::kw_comdat))
2944     return false;
2945
2946   if (EatIfPresent(lltok::lparen)) {
2947     if (Lex.getKind() != lltok::ComdatVar)
2948       return TokError("expected comdat variable");
2949     C = getComdat(Lex.getStrVal(), Lex.getLoc());
2950     Lex.Lex();
2951     if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2952       return true;
2953   } else {
2954     if (GlobalName.empty())
2955       return TokError("comdat cannot be unnamed");
2956     C = getComdat(GlobalName, KwLoc);
2957   }
2958
2959   return false;
2960 }
2961
2962 /// ParseGlobalValueVector
2963 ///   ::= /*empty*/
2964 ///   ::= TypeAndValue (',' TypeAndValue)*
2965 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2966   // Empty list.
2967   if (Lex.getKind() == lltok::rbrace ||
2968       Lex.getKind() == lltok::rsquare ||
2969       Lex.getKind() == lltok::greater ||
2970       Lex.getKind() == lltok::rparen)
2971     return false;
2972
2973   Constant *C;
2974   if (ParseGlobalTypeAndValue(C)) return true;
2975   Elts.push_back(C);
2976
2977   while (EatIfPresent(lltok::comma)) {
2978     if (ParseGlobalTypeAndValue(C)) return true;
2979     Elts.push_back(C);
2980   }
2981
2982   return false;
2983 }
2984
2985 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2986   SmallVector<Metadata *, 16> Elts;
2987   if (ParseMDNodeVector(Elts))
2988     return true;
2989
2990   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2991   return false;
2992 }
2993
2994 /// MDNode:
2995 ///  ::= !{ ... }
2996 ///  ::= !7
2997 ///  ::= !DILocation(...)
2998 bool LLParser::ParseMDNode(MDNode *&N) {
2999   if (Lex.getKind() == lltok::MetadataVar)
3000     return ParseSpecializedMDNode(N);
3001
3002   return ParseToken(lltok::exclaim, "expected '!' here") ||
3003          ParseMDNodeTail(N);
3004 }
3005
3006 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3007   // !{ ... }
3008   if (Lex.getKind() == lltok::lbrace)
3009     return ParseMDTuple(N);
3010
3011   // !42
3012   return ParseMDNodeID(N);
3013 }
3014
3015 namespace {
3016
3017 /// Structure to represent an optional metadata field.
3018 template <class FieldTy> struct MDFieldImpl {
3019   typedef MDFieldImpl ImplTy;
3020   FieldTy Val;
3021   bool Seen;
3022
3023   void assign(FieldTy Val) {
3024     Seen = true;
3025     this->Val = std::move(Val);
3026   }
3027
3028   explicit MDFieldImpl(FieldTy Default)
3029       : Val(std::move(Default)), Seen(false) {}
3030 };
3031
3032 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3033   uint64_t Max;
3034
3035   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3036       : ImplTy(Default), Max(Max) {}
3037 };
3038 struct LineField : public MDUnsignedField {
3039   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3040 };
3041 struct ColumnField : public MDUnsignedField {
3042   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3043 };
3044 struct DwarfTagField : public MDUnsignedField {
3045   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3046   DwarfTagField(dwarf::Tag DefaultTag)
3047       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3048 };
3049 struct DwarfAttEncodingField : public MDUnsignedField {
3050   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3051 };
3052 struct DwarfVirtualityField : public MDUnsignedField {
3053   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3054 };
3055 struct DwarfLangField : public MDUnsignedField {
3056   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3057 };
3058
3059 struct DIFlagField : public MDUnsignedField {
3060   DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3061 };
3062
3063 struct MDSignedField : public MDFieldImpl<int64_t> {
3064   int64_t Min;
3065   int64_t Max;
3066
3067   MDSignedField(int64_t Default = 0)
3068       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3069   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3070       : ImplTy(Default), Min(Min), Max(Max) {}
3071 };
3072
3073 struct MDBoolField : public MDFieldImpl<bool> {
3074   MDBoolField(bool Default = false) : ImplTy(Default) {}
3075 };
3076 struct MDField : public MDFieldImpl<Metadata *> {
3077   bool AllowNull;
3078
3079   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3080 };
3081 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3082   MDConstant() : ImplTy(nullptr) {}
3083 };
3084 struct MDStringField : public MDFieldImpl<MDString *> {
3085   bool AllowEmpty;
3086   MDStringField(bool AllowEmpty = true)
3087       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3088 };
3089 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3090   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3091 };
3092
3093 } // end namespace
3094
3095 namespace llvm {
3096
3097 template <>
3098 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3099                             MDUnsignedField &Result) {
3100   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3101     return TokError("expected unsigned integer");
3102
3103   auto &U = Lex.getAPSIntVal();
3104   if (U.ugt(Result.Max))
3105     return TokError("value for '" + Name + "' too large, limit is " +
3106                     Twine(Result.Max));
3107   Result.assign(U.getZExtValue());
3108   assert(Result.Val <= Result.Max && "Expected value in range");
3109   Lex.Lex();
3110   return false;
3111 }
3112
3113 template <>
3114 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3115   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3116 }
3117 template <>
3118 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3119   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3120 }
3121
3122 template <>
3123 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3124   if (Lex.getKind() == lltok::APSInt)
3125     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3126
3127   if (Lex.getKind() != lltok::DwarfTag)
3128     return TokError("expected DWARF tag");
3129
3130   unsigned Tag = dwarf::getTag(Lex.getStrVal());
3131   if (Tag == dwarf::DW_TAG_invalid)
3132     return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3133   assert(Tag <= Result.Max && "Expected valid DWARF tag");
3134
3135   Result.assign(Tag);
3136   Lex.Lex();
3137   return false;
3138 }
3139
3140 template <>
3141 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3142                             DwarfVirtualityField &Result) {
3143   if (Lex.getKind() == lltok::APSInt)
3144     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3145
3146   if (Lex.getKind() != lltok::DwarfVirtuality)
3147     return TokError("expected DWARF virtuality code");
3148
3149   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3150   if (!Virtuality)
3151     return TokError("invalid DWARF virtuality code" + Twine(" '") +
3152                     Lex.getStrVal() + "'");
3153   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3154   Result.assign(Virtuality);
3155   Lex.Lex();
3156   return false;
3157 }
3158
3159 template <>
3160 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3161   if (Lex.getKind() == lltok::APSInt)
3162     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3163
3164   if (Lex.getKind() != lltok::DwarfLang)
3165     return TokError("expected DWARF language");
3166
3167   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3168   if (!Lang)
3169     return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3170                     "'");
3171   assert(Lang <= Result.Max && "Expected valid DWARF language");
3172   Result.assign(Lang);
3173   Lex.Lex();
3174   return false;
3175 }
3176
3177 template <>
3178 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3179                             DwarfAttEncodingField &Result) {
3180   if (Lex.getKind() == lltok::APSInt)
3181     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3182
3183   if (Lex.getKind() != lltok::DwarfAttEncoding)
3184     return TokError("expected DWARF type attribute encoding");
3185
3186   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3187   if (!Encoding)
3188     return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3189                     Lex.getStrVal() + "'");
3190   assert(Encoding <= Result.Max && "Expected valid DWARF language");
3191   Result.assign(Encoding);
3192   Lex.Lex();
3193   return false;
3194 }
3195
3196 /// DIFlagField
3197 ///  ::= uint32
3198 ///  ::= DIFlagVector
3199 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3200 template <>
3201 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3202   assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3203
3204   // Parser for a single flag.
3205   auto parseFlag = [&](unsigned &Val) {
3206     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3207       return ParseUInt32(Val);
3208
3209     if (Lex.getKind() != lltok::DIFlag)
3210       return TokError("expected debug info flag");
3211
3212     Val = DINode::getFlag(Lex.getStrVal());
3213     if (!Val)
3214       return TokError(Twine("invalid debug info flag flag '") +
3215                       Lex.getStrVal() + "'");
3216     Lex.Lex();
3217     return false;
3218   };
3219
3220   // Parse the flags and combine them together.
3221   unsigned Combined = 0;
3222   do {
3223     unsigned Val;
3224     if (parseFlag(Val))
3225       return true;
3226     Combined |= Val;
3227   } while (EatIfPresent(lltok::bar));
3228
3229   Result.assign(Combined);
3230   return false;
3231 }
3232
3233 template <>
3234 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3235                             MDSignedField &Result) {
3236   if (Lex.getKind() != lltok::APSInt)
3237     return TokError("expected signed integer");
3238
3239   auto &S = Lex.getAPSIntVal();
3240   if (S < Result.Min)
3241     return TokError("value for '" + Name + "' too small, limit is " +
3242                     Twine(Result.Min));
3243   if (S > Result.Max)
3244     return TokError("value for '" + Name + "' too large, limit is " +
3245                     Twine(Result.Max));
3246   Result.assign(S.getExtValue());
3247   assert(Result.Val >= Result.Min && "Expected value in range");
3248   assert(Result.Val <= Result.Max && "Expected value in range");
3249   Lex.Lex();
3250   return false;
3251 }
3252
3253 template <>
3254 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3255   switch (Lex.getKind()) {
3256   default:
3257     return TokError("expected 'true' or 'false'");
3258   case lltok::kw_true:
3259     Result.assign(true);
3260     break;
3261   case lltok::kw_false:
3262     Result.assign(false);
3263     break;
3264   }
3265   Lex.Lex();
3266   return false;
3267 }
3268
3269 template <>
3270 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3271   if (Lex.getKind() == lltok::kw_null) {
3272     if (!Result.AllowNull)
3273       return TokError("'" + Name + "' cannot be null");
3274     Lex.Lex();
3275     Result.assign(nullptr);
3276     return false;
3277   }
3278
3279   Metadata *MD;
3280   if (ParseMetadata(MD, nullptr))
3281     return true;
3282
3283   Result.assign(MD);
3284   return false;
3285 }
3286
3287 template <>
3288 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3289   Metadata *MD;
3290   if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3291     return true;
3292
3293   Result.assign(cast<ConstantAsMetadata>(MD));
3294   return false;
3295 }
3296
3297 template <>
3298 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3299   LocTy ValueLoc = Lex.getLoc();
3300   std::string S;
3301   if (ParseStringConstant(S))
3302     return true;
3303
3304   if (!Result.AllowEmpty && S.empty())
3305     return Error(ValueLoc, "'" + Name + "' cannot be empty");
3306
3307   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3308   return false;
3309 }
3310
3311 template <>
3312 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3313   SmallVector<Metadata *, 4> MDs;
3314   if (ParseMDNodeVector(MDs))
3315     return true;
3316
3317   Result.assign(std::move(MDs));
3318   return false;
3319 }
3320
3321 } // end namespace llvm
3322
3323 template <class ParserTy>
3324 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3325   do {
3326     if (Lex.getKind() != lltok::LabelStr)
3327       return TokError("expected field label here");
3328
3329     if (parseField())
3330       return true;
3331   } while (EatIfPresent(lltok::comma));
3332
3333   return false;
3334 }
3335
3336 template <class ParserTy>
3337 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3338   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3339   Lex.Lex();
3340
3341   if (ParseToken(lltok::lparen, "expected '(' here"))
3342     return true;
3343   if (Lex.getKind() != lltok::rparen)
3344     if (ParseMDFieldsImplBody(parseField))
3345       return true;
3346
3347   ClosingLoc = Lex.getLoc();
3348   return ParseToken(lltok::rparen, "expected ')' here");
3349 }
3350
3351 template <class FieldTy>
3352 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3353   if (Result.Seen)
3354     return TokError("field '" + Name + "' cannot be specified more than once");
3355
3356   LocTy Loc = Lex.getLoc();
3357   Lex.Lex();
3358   return ParseMDField(Loc, Name, Result);
3359 }
3360
3361 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3362   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3363
3364 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
3365   if (Lex.getStrVal() == #CLASS)                                               \
3366     return Parse##CLASS(N, IsDistinct);
3367 #include "llvm/IR/Metadata.def"
3368
3369   return TokError("expected metadata type");
3370 }
3371
3372 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3373 #define NOP_FIELD(NAME, TYPE, INIT)
3374 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
3375   if (!NAME.Seen)                                                              \
3376     return Error(ClosingLoc, "missing required field '" #NAME "'");
3377 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
3378   if (Lex.getStrVal() == #NAME)                                                \
3379     return ParseMDField(#NAME, NAME);
3380 #define PARSE_MD_FIELDS()                                                      \
3381   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
3382   do {                                                                         \
3383     LocTy ClosingLoc;                                                          \
3384     if (ParseMDFieldsImpl([&]() -> bool {                                      \
3385       VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                          \
3386       return TokError(Twine("invalid field '") + Lex.getStrVal() + "'");       \
3387     }, ClosingLoc))                                                            \
3388       return true;                                                             \
3389     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
3390   } while (false)
3391 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
3392   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3393
3394 /// ParseDILocationFields:
3395 ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3396 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3397 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3398   OPTIONAL(line, LineField, );                                                 \
3399   OPTIONAL(column, ColumnField, );                                             \
3400   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3401   OPTIONAL(inlinedAt, MDField, );
3402   PARSE_MD_FIELDS();
3403 #undef VISIT_MD_FIELDS
3404
3405   Result = GET_OR_DISTINCT(
3406       DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3407   return false;
3408 }
3409
3410 /// ParseGenericDINode:
3411 ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3412 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3413 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3414   REQUIRED(tag, DwarfTagField, );                                              \
3415   OPTIONAL(header, MDStringField, );                                           \
3416   OPTIONAL(operands, MDFieldList, );
3417   PARSE_MD_FIELDS();
3418 #undef VISIT_MD_FIELDS
3419
3420   Result = GET_OR_DISTINCT(GenericDINode,
3421                            (Context, tag.Val, header.Val, operands.Val));
3422   return false;
3423 }
3424
3425 /// ParseDISubrange:
3426 ///   ::= !DISubrange(count: 30, lowerBound: 2)
3427 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3428 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3429   REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX));                         \
3430   OPTIONAL(lowerBound, MDSignedField, );
3431   PARSE_MD_FIELDS();
3432 #undef VISIT_MD_FIELDS
3433
3434   Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3435   return false;
3436 }
3437
3438 /// ParseDIEnumerator:
3439 ///   ::= !DIEnumerator(value: 30, name: "SomeKind")
3440 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3441 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3442   REQUIRED(name, MDStringField, );                                             \
3443   REQUIRED(value, MDSignedField, );
3444   PARSE_MD_FIELDS();
3445 #undef VISIT_MD_FIELDS
3446
3447   Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3448   return false;
3449 }
3450
3451 /// ParseDIBasicType:
3452 ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3453 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3454 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3455   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
3456   OPTIONAL(name, MDStringField, );                                             \
3457   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3458   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3459   OPTIONAL(encoding, DwarfAttEncodingField, );
3460   PARSE_MD_FIELDS();
3461 #undef VISIT_MD_FIELDS
3462
3463   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3464                                          align.Val, encoding.Val));
3465   return false;
3466 }
3467
3468 /// ParseDIDerivedType:
3469 ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3470 ///                      line: 7, scope: !1, baseType: !2, size: 32,
3471 ///                      align: 32, offset: 0, flags: 0, extraData: !3)
3472 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3473 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3474   REQUIRED(tag, DwarfTagField, );                                              \
3475   OPTIONAL(name, MDStringField, );                                             \
3476   OPTIONAL(file, MDField, );                                                   \
3477   OPTIONAL(line, LineField, );                                                 \
3478   OPTIONAL(scope, MDField, );                                                  \
3479   REQUIRED(baseType, MDField, );                                               \
3480   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3481   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3482   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3483   OPTIONAL(flags, DIFlagField, );                                              \
3484   OPTIONAL(extraData, MDField, );
3485   PARSE_MD_FIELDS();
3486 #undef VISIT_MD_FIELDS
3487
3488   Result = GET_OR_DISTINCT(DIDerivedType,
3489                            (Context, tag.Val, name.Val, file.Val, line.Val,
3490                             scope.Val, baseType.Val, size.Val, align.Val,
3491                             offset.Val, flags.Val, extraData.Val));
3492   return false;
3493 }
3494
3495 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3496 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3497   REQUIRED(tag, DwarfTagField, );                                              \
3498   OPTIONAL(name, MDStringField, );                                             \
3499   OPTIONAL(file, MDField, );                                                   \
3500   OPTIONAL(line, LineField, );                                                 \
3501   OPTIONAL(scope, MDField, );                                                  \
3502   OPTIONAL(baseType, MDField, );                                               \
3503   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3504   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3505   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3506   OPTIONAL(flags, DIFlagField, );                                              \
3507   OPTIONAL(elements, MDField, );                                               \
3508   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
3509   OPTIONAL(vtableHolder, MDField, );                                           \
3510   OPTIONAL(templateParams, MDField, );                                         \
3511   OPTIONAL(identifier, MDStringField, );
3512   PARSE_MD_FIELDS();
3513 #undef VISIT_MD_FIELDS
3514
3515   Result = GET_OR_DISTINCT(
3516       DICompositeType,
3517       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3518        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3519        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3520   return false;
3521 }
3522
3523 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3524 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3525   OPTIONAL(flags, DIFlagField, );                                              \
3526   REQUIRED(types, MDField, );
3527   PARSE_MD_FIELDS();
3528 #undef VISIT_MD_FIELDS
3529
3530   Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3531   return false;
3532 }
3533
3534 /// ParseDIFileType:
3535 ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3536 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3537 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3538   REQUIRED(filename, MDStringField, );                                         \
3539   REQUIRED(directory, MDStringField, );
3540   PARSE_MD_FIELDS();
3541 #undef VISIT_MD_FIELDS
3542
3543   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3544   return false;
3545 }
3546
3547 /// ParseDICompileUnit:
3548 ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3549 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
3550 ///                      splitDebugFilename: "abc.debug", emissionKind: 1,
3551 ///                      enums: !1, retainedTypes: !2, subprograms: !3,
3552 ///                      globals: !4, imports: !5)
3553 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3554 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3555   REQUIRED(language, DwarfLangField, );                                        \
3556   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
3557   OPTIONAL(producer, MDStringField, );                                         \
3558   OPTIONAL(isOptimized, MDBoolField, );                                        \
3559   OPTIONAL(flags, MDStringField, );                                            \
3560   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
3561   OPTIONAL(splitDebugFilename, MDStringField, );                               \
3562   OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX));                    \
3563   OPTIONAL(enums, MDField, );                                                  \
3564   OPTIONAL(retainedTypes, MDField, );                                          \
3565   OPTIONAL(subprograms, MDField, );                                            \
3566   OPTIONAL(globals, MDField, );                                                \
3567   OPTIONAL(imports, MDField, );
3568   PARSE_MD_FIELDS();
3569 #undef VISIT_MD_FIELDS
3570
3571   Result = GET_OR_DISTINCT(DICompileUnit,
3572                            (Context, language.Val, file.Val, producer.Val,
3573                             isOptimized.Val, flags.Val, runtimeVersion.Val,
3574                             splitDebugFilename.Val, emissionKind.Val, enums.Val,
3575                             retainedTypes.Val, subprograms.Val, globals.Val,
3576                             imports.Val));
3577   return false;
3578 }
3579
3580 /// ParseDISubprogram:
3581 ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3582 ///                     file: !1, line: 7, type: !2, isLocal: false,
3583 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
3584 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
3585 ///                     virtualIndex: 10, flags: 11,
3586 ///                     isOptimized: false, function: void ()* @_Z3foov,
3587 ///                     templateParams: !4, declaration: !5, variables: !6)
3588 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3589 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3590   OPTIONAL(scope, MDField, );                                                  \
3591   OPTIONAL(name, MDStringField, );                                             \
3592   OPTIONAL(linkageName, MDStringField, );                                      \
3593   OPTIONAL(file, MDField, );                                                   \
3594   OPTIONAL(line, LineField, );                                                 \
3595   OPTIONAL(type, MDField, );                                                   \
3596   OPTIONAL(isLocal, MDBoolField, );                                            \
3597   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
3598   OPTIONAL(scopeLine, LineField, );                                            \
3599   OPTIONAL(containingType, MDField, );                                         \
3600   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
3601   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
3602   OPTIONAL(flags, DIFlagField, );                                              \
3603   OPTIONAL(isOptimized, MDBoolField, );                                        \
3604   OPTIONAL(function, MDConstant, );                                            \
3605   OPTIONAL(templateParams, MDField, );                                         \
3606   OPTIONAL(declaration, MDField, );                                            \
3607   OPTIONAL(variables, MDField, );
3608   PARSE_MD_FIELDS();
3609 #undef VISIT_MD_FIELDS
3610
3611   Result = GET_OR_DISTINCT(
3612       DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3613                      line.Val, type.Val, isLocal.Val, isDefinition.Val,
3614                      scopeLine.Val, containingType.Val, virtuality.Val,
3615                      virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3616                      templateParams.Val, declaration.Val, variables.Val));
3617   return false;
3618 }
3619
3620 /// ParseDILexicalBlock:
3621 ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3622 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3623 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3624   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3625   OPTIONAL(file, MDField, );                                                   \
3626   OPTIONAL(line, LineField, );                                                 \
3627   OPTIONAL(column, ColumnField, );
3628   PARSE_MD_FIELDS();
3629 #undef VISIT_MD_FIELDS
3630
3631   Result = GET_OR_DISTINCT(
3632       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3633   return false;
3634 }
3635
3636 /// ParseDILexicalBlockFile:
3637 ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3638 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3639 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3640   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3641   OPTIONAL(file, MDField, );                                                   \
3642   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3643   PARSE_MD_FIELDS();
3644 #undef VISIT_MD_FIELDS
3645
3646   Result = GET_OR_DISTINCT(DILexicalBlockFile,
3647                            (Context, scope.Val, file.Val, discriminator.Val));
3648   return false;
3649 }
3650
3651 /// ParseDINamespace:
3652 ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3653 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3654 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3655   REQUIRED(scope, MDField, );                                                  \
3656   OPTIONAL(file, MDField, );                                                   \
3657   OPTIONAL(name, MDStringField, );                                             \
3658   OPTIONAL(line, LineField, );
3659   PARSE_MD_FIELDS();
3660 #undef VISIT_MD_FIELDS
3661
3662   Result = GET_OR_DISTINCT(DINamespace,
3663                            (Context, scope.Val, file.Val, name.Val, line.Val));
3664   return false;
3665 }
3666
3667 /// ParseDITemplateTypeParameter:
3668 ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3669 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3670 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3671   OPTIONAL(name, MDStringField, );                                             \
3672   REQUIRED(type, MDField, );
3673   PARSE_MD_FIELDS();
3674 #undef VISIT_MD_FIELDS
3675
3676   Result =
3677       GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3678   return false;
3679 }
3680
3681 /// ParseDITemplateValueParameter:
3682 ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3683 ///                                 name: "V", type: !1, value: i32 7)
3684 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3685 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3686   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
3687   OPTIONAL(name, MDStringField, );                                             \
3688   OPTIONAL(type, MDField, );                                                   \
3689   REQUIRED(value, MDField, );
3690   PARSE_MD_FIELDS();
3691 #undef VISIT_MD_FIELDS
3692
3693   Result = GET_OR_DISTINCT(DITemplateValueParameter,
3694                            (Context, tag.Val, name.Val, type.Val, value.Val));
3695   return false;
3696 }
3697
3698 /// ParseDIGlobalVariable:
3699 ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3700 ///                         file: !1, line: 7, type: !2, isLocal: false,
3701 ///                         isDefinition: true, variable: i32* @foo,
3702 ///                         declaration: !3)
3703 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3704 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3705   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
3706   OPTIONAL(scope, MDField, );                                                  \
3707   OPTIONAL(linkageName, MDStringField, );                                      \
3708   OPTIONAL(file, MDField, );                                                   \
3709   OPTIONAL(line, LineField, );                                                 \
3710   OPTIONAL(type, MDField, );                                                   \
3711   OPTIONAL(isLocal, MDBoolField, );                                            \
3712   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
3713   OPTIONAL(variable, MDConstant, );                                            \
3714   OPTIONAL(declaration, MDField, );
3715   PARSE_MD_FIELDS();
3716 #undef VISIT_MD_FIELDS
3717
3718   Result = GET_OR_DISTINCT(DIGlobalVariable,
3719                            (Context, scope.Val, name.Val, linkageName.Val,
3720                             file.Val, line.Val, type.Val, isLocal.Val,
3721                             isDefinition.Val, variable.Val, declaration.Val));
3722   return false;
3723 }
3724
3725 /// ParseDILocalVariable:
3726 ///   ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3727 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7)
3728 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3729 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3730   REQUIRED(tag, DwarfTagField, );                                              \
3731   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3732   OPTIONAL(name, MDStringField, );                                             \
3733   OPTIONAL(file, MDField, );                                                   \
3734   OPTIONAL(line, LineField, );                                                 \
3735   OPTIONAL(type, MDField, );                                                   \
3736   OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX));                              \
3737   OPTIONAL(flags, DIFlagField, );
3738   PARSE_MD_FIELDS();
3739 #undef VISIT_MD_FIELDS
3740
3741   Result = GET_OR_DISTINCT(DILocalVariable,
3742                            (Context, tag.Val, scope.Val, name.Val, file.Val,
3743                             line.Val, type.Val, arg.Val, flags.Val));
3744   return false;
3745 }
3746
3747 /// ParseDIExpression:
3748 ///   ::= !DIExpression(0, 7, -1)
3749 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3750   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3751   Lex.Lex();
3752
3753   if (ParseToken(lltok::lparen, "expected '(' here"))
3754     return true;
3755
3756   SmallVector<uint64_t, 8> Elements;
3757   if (Lex.getKind() != lltok::rparen)
3758     do {
3759       if (Lex.getKind() == lltok::DwarfOp) {
3760         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3761           Lex.Lex();
3762           Elements.push_back(Op);
3763           continue;
3764         }
3765         return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3766       }
3767
3768       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3769         return TokError("expected unsigned integer");
3770
3771       auto &U = Lex.getAPSIntVal();
3772       if (U.ugt(UINT64_MAX))
3773         return TokError("element too large, limit is " + Twine(UINT64_MAX));
3774       Elements.push_back(U.getZExtValue());
3775       Lex.Lex();
3776     } while (EatIfPresent(lltok::comma));
3777
3778   if (ParseToken(lltok::rparen, "expected ')' here"))
3779     return true;
3780
3781   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3782   return false;
3783 }
3784
3785 /// ParseDIObjCProperty:
3786 ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3787 ///                       getter: "getFoo", attributes: 7, type: !2)
3788 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3789 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3790   OPTIONAL(name, MDStringField, );                                             \
3791   OPTIONAL(file, MDField, );                                                   \
3792   OPTIONAL(line, LineField, );                                                 \
3793   OPTIONAL(setter, MDStringField, );                                           \
3794   OPTIONAL(getter, MDStringField, );                                           \
3795   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
3796   OPTIONAL(type, MDField, );
3797   PARSE_MD_FIELDS();
3798 #undef VISIT_MD_FIELDS
3799
3800   Result = GET_OR_DISTINCT(DIObjCProperty,
3801                            (Context, name.Val, file.Val, line.Val, setter.Val,
3802                             getter.Val, attributes.Val, type.Val));
3803   return false;
3804 }
3805
3806 /// ParseDIImportedEntity:
3807 ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3808 ///                         line: 7, name: "foo")
3809 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
3810 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3811   REQUIRED(tag, DwarfTagField, );                                              \
3812   REQUIRED(scope, MDField, );                                                  \
3813   OPTIONAL(entity, MDField, );                                                 \
3814   OPTIONAL(line, LineField, );                                                 \
3815   OPTIONAL(name, MDStringField, );
3816   PARSE_MD_FIELDS();
3817 #undef VISIT_MD_FIELDS
3818
3819   Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
3820                                               entity.Val, line.Val, name.Val));
3821   return false;
3822 }
3823
3824 #undef PARSE_MD_FIELD
3825 #undef NOP_FIELD
3826 #undef REQUIRE_FIELD
3827 #undef DECLARE_FIELD
3828
3829 /// ParseMetadataAsValue
3830 ///  ::= metadata i32 %local
3831 ///  ::= metadata i32 @global
3832 ///  ::= metadata i32 7
3833 ///  ::= metadata !0
3834 ///  ::= metadata !{...}
3835 ///  ::= metadata !"string"
3836 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3837   // Note: the type 'metadata' has already been parsed.
3838   Metadata *MD;
3839   if (ParseMetadata(MD, &PFS))
3840     return true;
3841
3842   V = MetadataAsValue::get(Context, MD);
3843   return false;
3844 }
3845
3846 /// ParseValueAsMetadata
3847 ///  ::= i32 %local
3848 ///  ::= i32 @global
3849 ///  ::= i32 7
3850 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3851                                     PerFunctionState *PFS) {
3852   Type *Ty;
3853   LocTy Loc;
3854   if (ParseType(Ty, TypeMsg, Loc))
3855     return true;
3856   if (Ty->isMetadataTy())
3857     return Error(Loc, "invalid metadata-value-metadata roundtrip");
3858
3859   Value *V;
3860   if (ParseValue(Ty, V, PFS))
3861     return true;
3862
3863   MD = ValueAsMetadata::get(V);
3864   return false;
3865 }
3866
3867 /// ParseMetadata
3868 ///  ::= i32 %local
3869 ///  ::= i32 @global
3870 ///  ::= i32 7
3871 ///  ::= !42
3872 ///  ::= !{...}
3873 ///  ::= !"string"
3874 ///  ::= !DILocation(...)
3875 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3876   if (Lex.getKind() == lltok::MetadataVar) {
3877     MDNode *N;
3878     if (ParseSpecializedMDNode(N))
3879       return true;
3880     MD = N;
3881     return false;
3882   }
3883
3884   // ValueAsMetadata:
3885   // <type> <value>
3886   if (Lex.getKind() != lltok::exclaim)
3887     return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3888
3889   // '!'.
3890   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3891   Lex.Lex();
3892
3893   // MDString:
3894   //   ::= '!' STRINGCONSTANT
3895   if (Lex.getKind() == lltok::StringConstant) {
3896     MDString *S;
3897     if (ParseMDString(S))
3898       return true;
3899     MD = S;
3900     return false;
3901   }
3902
3903   // MDNode:
3904   // !{ ... }
3905   // !7
3906   MDNode *N;
3907   if (ParseMDNodeTail(N))
3908     return true;
3909   MD = N;
3910   return false;
3911 }
3912
3913
3914 //===----------------------------------------------------------------------===//
3915 // Function Parsing.
3916 //===----------------------------------------------------------------------===//
3917
3918 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3919                                    PerFunctionState *PFS) {
3920   if (Ty->isFunctionTy())
3921     return Error(ID.Loc, "functions are not values, refer to them as pointers");
3922
3923   switch (ID.Kind) {
3924   case ValID::t_LocalID:
3925     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3926     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3927     return V == nullptr;
3928   case ValID::t_LocalName:
3929     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3930     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3931     return V == nullptr;
3932   case ValID::t_InlineAsm: {
3933     PointerType *PTy = dyn_cast<PointerType>(Ty);
3934     FunctionType *FTy =
3935       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3936     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3937       return Error(ID.Loc, "invalid type for inline asm constraint string");
3938     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3939                        (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3940     return false;
3941   }
3942   case ValID::t_GlobalName:
3943     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3944     return V == nullptr;
3945   case ValID::t_GlobalID:
3946     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3947     return V == nullptr;
3948   case ValID::t_APSInt:
3949     if (!Ty->isIntegerTy())
3950       return Error(ID.Loc, "integer constant must have integer type");
3951     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3952     V = ConstantInt::get(Context, ID.APSIntVal);
3953     return false;
3954   case ValID::t_APFloat:
3955     if (!Ty->isFloatingPointTy() ||
3956         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3957       return Error(ID.Loc, "floating point constant invalid for type");
3958
3959     // The lexer has no type info, so builds all half, float, and double FP
3960     // constants as double.  Fix this here.  Long double does not need this.
3961     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3962       bool Ignored;
3963       if (Ty->isHalfTy())
3964         ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3965                               &Ignored);
3966       else if (Ty->isFloatTy())
3967         ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3968                               &Ignored);
3969     }
3970     V = ConstantFP::get(Context, ID.APFloatVal);
3971
3972     if (V->getType() != Ty)
3973       return Error(ID.Loc, "floating point constant does not have type '" +
3974                    getTypeString(Ty) + "'");
3975
3976     return false;
3977   case ValID::t_Null:
3978     if (!Ty->isPointerTy())
3979       return Error(ID.Loc, "null must be a pointer type");
3980     V = ConstantPointerNull::get(cast<PointerType>(Ty));
3981     return false;
3982   case ValID::t_Undef:
3983     // FIXME: LabelTy should not be a first-class type.
3984     if (!Ty->isFirstClassType() || Ty->isLabelTy())
3985       return Error(ID.Loc, "invalid type for undef constant");
3986     V = UndefValue::get(Ty);
3987     return false;
3988   case ValID::t_EmptyArray:
3989     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3990       return Error(ID.Loc, "invalid empty array initializer");
3991     V = UndefValue::get(Ty);
3992     return false;
3993   case ValID::t_Zero:
3994     // FIXME: LabelTy should not be a first-class type.
3995     if (!Ty->isFirstClassType() || Ty->isLabelTy())
3996       return Error(ID.Loc, "invalid type for null constant");
3997     V = Constant::getNullValue(Ty);
3998     return false;
3999   case ValID::t_Constant:
4000     if (ID.ConstantVal->getType() != Ty)
4001       return Error(ID.Loc, "constant expression type mismatch");
4002
4003     V = ID.ConstantVal;
4004     return false;
4005   case ValID::t_ConstantStruct:
4006   case ValID::t_PackedConstantStruct:
4007     if (StructType *ST = dyn_cast<StructType>(Ty)) {
4008       if (ST->getNumElements() != ID.UIntVal)
4009         return Error(ID.Loc,
4010                      "initializer with struct type has wrong # elements");
4011       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4012         return Error(ID.Loc, "packed'ness of initializer and type don't match");
4013
4014       // Verify that the elements are compatible with the structtype.
4015       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4016         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4017           return Error(ID.Loc, "element " + Twine(i) +
4018                     " of struct initializer doesn't match struct element type");
4019
4020       V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4021                                                ID.UIntVal));
4022     } else
4023       return Error(ID.Loc, "constant expression type mismatch");
4024     return false;
4025   }
4026   llvm_unreachable("Invalid ValID");
4027 }
4028
4029 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4030   V = nullptr;
4031   ValID ID;
4032   return ParseValID(ID, PFS) ||
4033          ConvertValIDToValue(Ty, ID, V, PFS);
4034 }
4035
4036 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4037   Type *Ty = nullptr;
4038   return ParseType(Ty) ||
4039          ParseValue(Ty, V, PFS);
4040 }
4041
4042 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4043                                       PerFunctionState &PFS) {
4044   Value *V;
4045   Loc = Lex.getLoc();
4046   if (ParseTypeAndValue(V, PFS)) return true;
4047   if (!isa<BasicBlock>(V))
4048     return Error(Loc, "expected a basic block");
4049   BB = cast<BasicBlock>(V);
4050   return false;
4051 }
4052
4053
4054 /// FunctionHeader
4055 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4056 ///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4057 ///       OptionalAlign OptGC OptionalPrefix OptionalPrologue
4058 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4059   // Parse the linkage.
4060   LocTy LinkageLoc = Lex.getLoc();
4061   unsigned Linkage;
4062
4063   unsigned Visibility;
4064   unsigned DLLStorageClass;
4065   AttrBuilder RetAttrs;
4066   unsigned CC;
4067   Type *RetType = nullptr;
4068   LocTy RetTypeLoc = Lex.getLoc();
4069   if (ParseOptionalLinkage(Linkage) ||
4070       ParseOptionalVisibility(Visibility) ||
4071       ParseOptionalDLLStorageClass(DLLStorageClass) ||
4072       ParseOptionalCallingConv(CC) ||
4073       ParseOptionalReturnAttrs(RetAttrs) ||
4074       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4075     return true;
4076
4077   // Verify that the linkage is ok.
4078   switch ((GlobalValue::LinkageTypes)Linkage) {
4079   case GlobalValue::ExternalLinkage:
4080     break; // always ok.
4081   case GlobalValue::ExternalWeakLinkage:
4082     if (isDefine)
4083       return Error(LinkageLoc, "invalid linkage for function definition");
4084     break;
4085   case GlobalValue::PrivateLinkage:
4086   case GlobalValue::InternalLinkage:
4087   case GlobalValue::AvailableExternallyLinkage:
4088   case GlobalValue::LinkOnceAnyLinkage:
4089   case GlobalValue::LinkOnceODRLinkage:
4090   case GlobalValue::WeakAnyLinkage:
4091   case GlobalValue::WeakODRLinkage:
4092     if (!isDefine)
4093       return Error(LinkageLoc, "invalid linkage for function declaration");
4094     break;
4095   case GlobalValue::AppendingLinkage:
4096   case GlobalValue::CommonLinkage:
4097     return Error(LinkageLoc, "invalid function linkage type");
4098   }
4099
4100   if (!isValidVisibilityForLinkage(Visibility, Linkage))
4101     return Error(LinkageLoc,
4102                  "symbol with local linkage must have default visibility");
4103
4104   if (!FunctionType::isValidReturnType(RetType))
4105     return Error(RetTypeLoc, "invalid function return type");
4106
4107   LocTy NameLoc = Lex.getLoc();
4108
4109   std::string FunctionName;
4110   if (Lex.getKind() == lltok::GlobalVar) {
4111     FunctionName = Lex.getStrVal();
4112   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
4113     unsigned NameID = Lex.getUIntVal();
4114
4115     if (NameID != NumberedVals.size())
4116       return TokError("function expected to be numbered '%" +
4117                       Twine(NumberedVals.size()) + "'");
4118   } else {
4119     return TokError("expected function name");
4120   }
4121
4122   Lex.Lex();
4123
4124   if (Lex.getKind() != lltok::lparen)
4125     return TokError("expected '(' in function argument list");
4126
4127   SmallVector<ArgInfo, 8> ArgList;
4128   bool isVarArg;
4129   AttrBuilder FuncAttrs;
4130   std::vector<unsigned> FwdRefAttrGrps;
4131   LocTy BuiltinLoc;
4132   std::string Section;
4133   unsigned Alignment;
4134   std::string GC;
4135   bool UnnamedAddr;
4136   LocTy UnnamedAddrLoc;
4137   Constant *Prefix = nullptr;
4138   Constant *Prologue = nullptr;
4139   Comdat *C;
4140
4141   if (ParseArgumentList(ArgList, isVarArg) ||
4142       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4143                          &UnnamedAddrLoc) ||
4144       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4145                                  BuiltinLoc) ||
4146       (EatIfPresent(lltok::kw_section) &&
4147        ParseStringConstant(Section)) ||
4148       parseOptionalComdat(FunctionName, C) ||
4149       ParseOptionalAlignment(Alignment) ||
4150       (EatIfPresent(lltok::kw_gc) &&
4151        ParseStringConstant(GC)) ||
4152       (EatIfPresent(lltok::kw_prefix) &&
4153        ParseGlobalTypeAndValue(Prefix)) ||
4154       (EatIfPresent(lltok::kw_prologue) &&
4155        ParseGlobalTypeAndValue(Prologue)))
4156     return true;
4157
4158   if (FuncAttrs.contains(Attribute::Builtin))
4159     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4160
4161   // If the alignment was parsed as an attribute, move to the alignment field.
4162   if (FuncAttrs.hasAlignmentAttr()) {
4163     Alignment = FuncAttrs.getAlignment();
4164     FuncAttrs.removeAttribute(Attribute::Alignment);
4165   }
4166
4167   // Okay, if we got here, the function is syntactically valid.  Convert types
4168   // and do semantic checks.
4169   std::vector<Type*> ParamTypeList;
4170   SmallVector<AttributeSet, 8> Attrs;
4171
4172   if (RetAttrs.hasAttributes())
4173     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4174                                       AttributeSet::ReturnIndex,
4175                                       RetAttrs));
4176
4177   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4178     ParamTypeList.push_back(ArgList[i].Ty);
4179     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4180       AttrBuilder B(ArgList[i].Attrs, i + 1);
4181       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4182     }
4183   }
4184
4185   if (FuncAttrs.hasAttributes())
4186     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4187                                       AttributeSet::FunctionIndex,
4188                                       FuncAttrs));
4189
4190   AttributeSet PAL = AttributeSet::get(Context, Attrs);
4191
4192   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4193     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4194
4195   FunctionType *FT =
4196     FunctionType::get(RetType, ParamTypeList, isVarArg);
4197   PointerType *PFT = PointerType::getUnqual(FT);
4198
4199   Fn = nullptr;
4200   if (!FunctionName.empty()) {
4201     // If this was a definition of a forward reference, remove the definition
4202     // from the forward reference table and fill in the forward ref.
4203     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4204       ForwardRefVals.find(FunctionName);
4205     if (FRVI != ForwardRefVals.end()) {
4206       Fn = M->getFunction(FunctionName);
4207       if (!Fn)
4208         return Error(FRVI->second.second, "invalid forward reference to "
4209                      "function as global value!");
4210       if (Fn->getType() != PFT)
4211         return Error(FRVI->second.second, "invalid forward reference to "
4212                      "function '" + FunctionName + "' with wrong type!");
4213
4214       ForwardRefVals.erase(FRVI);
4215     } else if ((Fn = M->getFunction(FunctionName))) {
4216       // Reject redefinitions.
4217       return Error(NameLoc, "invalid redefinition of function '" +
4218                    FunctionName + "'");
4219     } else if (M->getNamedValue(FunctionName)) {
4220       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4221     }
4222
4223   } else {
4224     // If this is a definition of a forward referenced function, make sure the
4225     // types agree.
4226     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4227       = ForwardRefValIDs.find(NumberedVals.size());
4228     if (I != ForwardRefValIDs.end()) {
4229       Fn = cast<Function>(I->second.first);
4230       if (Fn->getType() != PFT)
4231         return Error(NameLoc, "type of definition and forward reference of '@" +
4232                      Twine(NumberedVals.size()) + "' disagree");
4233       ForwardRefValIDs.erase(I);
4234     }
4235   }
4236
4237   if (!Fn)
4238     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4239   else // Move the forward-reference to the correct spot in the module.
4240     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4241
4242   if (FunctionName.empty())
4243     NumberedVals.push_back(Fn);
4244
4245   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4246   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4247   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4248   Fn->setCallingConv(CC);
4249   Fn->setAttributes(PAL);
4250   Fn->setUnnamedAddr(UnnamedAddr);
4251   Fn->setAlignment(Alignment);
4252   Fn->setSection(Section);
4253   Fn->setComdat(C);
4254   if (!GC.empty()) Fn->setGC(GC.c_str());
4255   Fn->setPrefixData(Prefix);
4256   Fn->setPrologueData(Prologue);
4257   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4258
4259   // Add all of the arguments we parsed to the function.
4260   Function::arg_iterator ArgIt = Fn->arg_begin();
4261   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4262     // If the argument has a name, insert it into the argument symbol table.
4263     if (ArgList[i].Name.empty()) continue;
4264
4265     // Set the name, if it conflicted, it will be auto-renamed.
4266     ArgIt->setName(ArgList[i].Name);
4267
4268     if (ArgIt->getName() != ArgList[i].Name)
4269       return Error(ArgList[i].Loc, "redefinition of argument '%" +
4270                    ArgList[i].Name + "'");
4271   }
4272
4273   if (isDefine)
4274     return false;
4275
4276   // Check the declaration has no block address forward references.
4277   ValID ID;
4278   if (FunctionName.empty()) {
4279     ID.Kind = ValID::t_GlobalID;
4280     ID.UIntVal = NumberedVals.size() - 1;
4281   } else {
4282     ID.Kind = ValID::t_GlobalName;
4283     ID.StrVal = FunctionName;
4284   }
4285   auto Blocks = ForwardRefBlockAddresses.find(ID);
4286   if (Blocks != ForwardRefBlockAddresses.end())
4287     return Error(Blocks->first.Loc,
4288                  "cannot take blockaddress inside a declaration");
4289   return false;
4290 }
4291
4292 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4293   ValID ID;
4294   if (FunctionNumber == -1) {
4295     ID.Kind = ValID::t_GlobalName;
4296     ID.StrVal = F.getName();
4297   } else {
4298     ID.Kind = ValID::t_GlobalID;
4299     ID.UIntVal = FunctionNumber;
4300   }
4301
4302   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4303   if (Blocks == P.ForwardRefBlockAddresses.end())
4304     return false;
4305
4306   for (const auto &I : Blocks->second) {
4307     const ValID &BBID = I.first;
4308     GlobalValue *GV = I.second;
4309
4310     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4311            "Expected local id or name");
4312     BasicBlock *BB;
4313     if (BBID.Kind == ValID::t_LocalName)
4314       BB = GetBB(BBID.StrVal, BBID.Loc);
4315     else
4316       BB = GetBB(BBID.UIntVal, BBID.Loc);
4317     if (!BB)
4318       return P.Error(BBID.Loc, "referenced value is not a basic block");
4319
4320     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4321     GV->eraseFromParent();
4322   }
4323
4324   P.ForwardRefBlockAddresses.erase(Blocks);
4325   return false;
4326 }
4327
4328 /// ParseFunctionBody
4329 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
4330 bool LLParser::ParseFunctionBody(Function &Fn) {
4331   if (Lex.getKind() != lltok::lbrace)
4332     return TokError("expected '{' in function body");
4333   Lex.Lex();  // eat the {.
4334
4335   int FunctionNumber = -1;
4336   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4337
4338   PerFunctionState PFS(*this, Fn, FunctionNumber);
4339
4340   // Resolve block addresses and allow basic blocks to be forward-declared
4341   // within this function.
4342   if (PFS.resolveForwardRefBlockAddresses())
4343     return true;
4344   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4345
4346   // We need at least one basic block.
4347   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4348     return TokError("function body requires at least one basic block");
4349
4350   while (Lex.getKind() != lltok::rbrace &&
4351          Lex.getKind() != lltok::kw_uselistorder)
4352     if (ParseBasicBlock(PFS)) return true;
4353
4354   while (Lex.getKind() != lltok::rbrace)
4355     if (ParseUseListOrder(&PFS))
4356       return true;
4357
4358   // Eat the }.
4359   Lex.Lex();
4360
4361   // Verify function is ok.
4362   return PFS.FinishFunction();
4363 }
4364
4365 /// ParseBasicBlock
4366 ///   ::= LabelStr? Instruction*
4367 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4368   // If this basic block starts out with a name, remember it.
4369   std::string Name;
4370   LocTy NameLoc = Lex.getLoc();
4371   if (Lex.getKind() == lltok::LabelStr) {
4372     Name = Lex.getStrVal();
4373     Lex.Lex();
4374   }
4375
4376   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4377   if (!BB)
4378     return Error(NameLoc,
4379                  "unable to create block named '" + Name + "'");
4380
4381   std::string NameStr;
4382
4383   // Parse the instructions in this block until we get a terminator.
4384   Instruction *Inst;
4385   do {
4386     // This instruction may have three possibilities for a name: a) none
4387     // specified, b) name specified "%foo =", c) number specified: "%4 =".
4388     LocTy NameLoc = Lex.getLoc();
4389     int NameID = -1;
4390     NameStr = "";
4391
4392     if (Lex.getKind() == lltok::LocalVarID) {
4393       NameID = Lex.getUIntVal();
4394       Lex.Lex();
4395       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4396         return true;
4397     } else if (Lex.getKind() == lltok::LocalVar) {
4398       NameStr = Lex.getStrVal();
4399       Lex.Lex();
4400       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4401         return true;
4402     }
4403
4404     switch (ParseInstruction(Inst, BB, PFS)) {
4405     default: llvm_unreachable("Unknown ParseInstruction result!");
4406     case InstError: return true;
4407     case InstNormal:
4408       BB->getInstList().push_back(Inst);
4409
4410       // With a normal result, we check to see if the instruction is followed by
4411       // a comma and metadata.
4412       if (EatIfPresent(lltok::comma))
4413         if (ParseInstructionMetadata(*Inst))
4414           return true;
4415       break;
4416     case InstExtraComma:
4417       BB->getInstList().push_back(Inst);
4418
4419       // If the instruction parser ate an extra comma at the end of it, it
4420       // *must* be followed by metadata.
4421       if (ParseInstructionMetadata(*Inst))
4422         return true;
4423       break;
4424     }
4425
4426     // Set the name on the instruction.
4427     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4428   } while (!isa<TerminatorInst>(Inst));
4429
4430   return false;
4431 }
4432
4433 //===----------------------------------------------------------------------===//
4434 // Instruction Parsing.
4435 //===----------------------------------------------------------------------===//
4436
4437 /// ParseInstruction - Parse one of the many different instructions.
4438 ///
4439 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4440                                PerFunctionState &PFS) {
4441   lltok::Kind Token = Lex.getKind();
4442   if (Token == lltok::Eof)
4443     return TokError("found end of file when expecting more instructions");
4444   LocTy Loc = Lex.getLoc();
4445   unsigned KeywordVal = Lex.getUIntVal();
4446   Lex.Lex();  // Eat the keyword.
4447
4448   switch (Token) {
4449   default:                    return Error(Loc, "expected instruction opcode");
4450   // Terminator Instructions.
4451   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4452   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
4453   case lltok::kw_br:          return ParseBr(Inst, PFS);
4454   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
4455   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
4456   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
4457   case lltok::kw_resume:      return ParseResume(Inst, PFS);
4458   // Binary Operators.
4459   case lltok::kw_add:
4460   case lltok::kw_sub:
4461   case lltok::kw_mul:
4462   case lltok::kw_shl: {
4463     bool NUW = EatIfPresent(lltok::kw_nuw);
4464     bool NSW = EatIfPresent(lltok::kw_nsw);
4465     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4466
4467     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4468
4469     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4470     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4471     return false;
4472   }
4473   case lltok::kw_fadd:
4474   case lltok::kw_fsub:
4475   case lltok::kw_fmul:
4476   case lltok::kw_fdiv:
4477   case lltok::kw_frem: {
4478     FastMathFlags FMF = EatFastMathFlagsIfPresent();
4479     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4480     if (Res != 0)
4481       return Res;
4482     if (FMF.any())
4483       Inst->setFastMathFlags(FMF);
4484     return 0;
4485   }
4486
4487   case lltok::kw_sdiv:
4488   case lltok::kw_udiv:
4489   case lltok::kw_lshr:
4490   case lltok::kw_ashr: {
4491     bool Exact = EatIfPresent(lltok::kw_exact);
4492
4493     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4494     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4495     return false;
4496   }
4497
4498   case lltok::kw_urem:
4499   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4500   case lltok::kw_and:
4501   case lltok::kw_or:
4502   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
4503   case lltok::kw_icmp:
4504   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
4505   // Casts.
4506   case lltok::kw_trunc:
4507   case lltok::kw_zext:
4508   case lltok::kw_sext:
4509   case lltok::kw_fptrunc:
4510   case lltok::kw_fpext:
4511   case lltok::kw_bitcast:
4512   case lltok::kw_addrspacecast:
4513   case lltok::kw_uitofp:
4514   case lltok::kw_sitofp:
4515   case lltok::kw_fptoui:
4516   case lltok::kw_fptosi:
4517   case lltok::kw_inttoptr:
4518   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
4519   // Other.
4520   case lltok::kw_select:         return ParseSelect(Inst, PFS);
4521   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
4522   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4523   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
4524   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
4525   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
4526   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
4527   // Call.
4528   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
4529   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4530   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4531   // Memory.
4532   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
4533   case lltok::kw_load:           return ParseLoad(Inst, PFS);
4534   case lltok::kw_store:          return ParseStore(Inst, PFS);
4535   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
4536   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
4537   case lltok::kw_fence:          return ParseFence(Inst, PFS);
4538   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4539   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
4540   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
4541   }
4542 }
4543
4544 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4545 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4546   if (Opc == Instruction::FCmp) {
4547     switch (Lex.getKind()) {
4548     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4549     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4550     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4551     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4552     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4553     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4554     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4555     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4556     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4557     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4558     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4559     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4560     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4561     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4562     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4563     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4564     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4565     }
4566   } else {
4567     switch (Lex.getKind()) {
4568     default: return TokError("expected icmp predicate (e.g. 'eq')");
4569     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
4570     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
4571     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4572     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4573     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4574     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4575     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4576     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4577     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4578     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4579     }
4580   }
4581   Lex.Lex();
4582   return false;
4583 }
4584
4585 //===----------------------------------------------------------------------===//
4586 // Terminator Instructions.
4587 //===----------------------------------------------------------------------===//
4588
4589 /// ParseRet - Parse a return instruction.
4590 ///   ::= 'ret' void (',' !dbg, !1)*
4591 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
4592 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4593                         PerFunctionState &PFS) {
4594   SMLoc TypeLoc = Lex.getLoc();
4595   Type *Ty = nullptr;
4596   if (ParseType(Ty, true /*void allowed*/)) return true;
4597
4598   Type *ResType = PFS.getFunction().getReturnType();
4599
4600   if (Ty->isVoidTy()) {
4601     if (!ResType->isVoidTy())
4602       return Error(TypeLoc, "value doesn't match function result type '" +
4603                    getTypeString(ResType) + "'");
4604
4605     Inst = ReturnInst::Create(Context);
4606     return false;
4607   }
4608
4609   Value *RV;
4610   if (ParseValue(Ty, RV, PFS)) return true;
4611
4612   if (ResType != RV->getType())
4613     return Error(TypeLoc, "value doesn't match function result type '" +
4614                  getTypeString(ResType) + "'");
4615
4616   Inst = ReturnInst::Create(Context, RV);
4617   return false;
4618 }
4619
4620
4621 /// ParseBr
4622 ///   ::= 'br' TypeAndValue
4623 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4624 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4625   LocTy Loc, Loc2;
4626   Value *Op0;
4627   BasicBlock *Op1, *Op2;
4628   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4629
4630   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4631     Inst = BranchInst::Create(BB);
4632     return false;
4633   }
4634
4635   if (Op0->getType() != Type::getInt1Ty(Context))
4636     return Error(Loc, "branch condition must have 'i1' type");
4637
4638   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4639       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4640       ParseToken(lltok::comma, "expected ',' after true destination") ||
4641       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4642     return true;
4643
4644   Inst = BranchInst::Create(Op1, Op2, Op0);
4645   return false;
4646 }
4647
4648 /// ParseSwitch
4649 ///  Instruction
4650 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4651 ///  JumpTable
4652 ///    ::= (TypeAndValue ',' TypeAndValue)*
4653 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4654   LocTy CondLoc, BBLoc;
4655   Value *Cond;
4656   BasicBlock *DefaultBB;
4657   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4658       ParseToken(lltok::comma, "expected ',' after switch condition") ||
4659       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4660       ParseToken(lltok::lsquare, "expected '[' with switch table"))
4661     return true;
4662
4663   if (!Cond->getType()->isIntegerTy())
4664     return Error(CondLoc, "switch condition must have integer type");
4665
4666   // Parse the jump table pairs.
4667   SmallPtrSet<Value*, 32> SeenCases;
4668   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4669   while (Lex.getKind() != lltok::rsquare) {
4670     Value *Constant;
4671     BasicBlock *DestBB;
4672
4673     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4674         ParseToken(lltok::comma, "expected ',' after case value") ||
4675         ParseTypeAndBasicBlock(DestBB, PFS))
4676       return true;
4677
4678     if (!SeenCases.insert(Constant).second)
4679       return Error(CondLoc, "duplicate case value in switch");
4680     if (!isa<ConstantInt>(Constant))
4681       return Error(CondLoc, "case value is not a constant integer");
4682
4683     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4684   }
4685
4686   Lex.Lex();  // Eat the ']'.
4687
4688   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4689   for (unsigned i = 0, e = Table.size(); i != e; ++i)
4690     SI->addCase(Table[i].first, Table[i].second);
4691   Inst = SI;
4692   return false;
4693 }
4694
4695 /// ParseIndirectBr
4696 ///  Instruction
4697 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4698 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4699   LocTy AddrLoc;
4700   Value *Address;
4701   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4702       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4703       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4704     return true;
4705
4706   if (!Address->getType()->isPointerTy())
4707     return Error(AddrLoc, "indirectbr address must have pointer type");
4708
4709   // Parse the destination list.
4710   SmallVector<BasicBlock*, 16> DestList;
4711
4712   if (Lex.getKind() != lltok::rsquare) {
4713     BasicBlock *DestBB;
4714     if (ParseTypeAndBasicBlock(DestBB, PFS))
4715       return true;
4716     DestList.push_back(DestBB);
4717
4718     while (EatIfPresent(lltok::comma)) {
4719       if (ParseTypeAndBasicBlock(DestBB, PFS))
4720         return true;
4721       DestList.push_back(DestBB);
4722     }
4723   }
4724
4725   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4726     return true;
4727
4728   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4729   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4730     IBI->addDestination(DestList[i]);
4731   Inst = IBI;
4732   return false;
4733 }
4734
4735
4736 /// ParseInvoke
4737 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4738 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4739 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4740   LocTy CallLoc = Lex.getLoc();
4741   AttrBuilder RetAttrs, FnAttrs;
4742   std::vector<unsigned> FwdRefAttrGrps;
4743   LocTy NoBuiltinLoc;
4744   unsigned CC;
4745   Type *RetType = nullptr;
4746   LocTy RetTypeLoc;
4747   ValID CalleeID;
4748   SmallVector<ParamInfo, 16> ArgList;
4749
4750   BasicBlock *NormalBB, *UnwindBB;
4751   if (ParseOptionalCallingConv(CC) ||
4752       ParseOptionalReturnAttrs(RetAttrs) ||
4753       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4754       ParseValID(CalleeID) ||
4755       ParseParameterList(ArgList, PFS) ||
4756       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4757                                  NoBuiltinLoc) ||
4758       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4759       ParseTypeAndBasicBlock(NormalBB, PFS) ||
4760       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4761       ParseTypeAndBasicBlock(UnwindBB, PFS))
4762     return true;
4763
4764   // If RetType is a non-function pointer type, then this is the short syntax
4765   // for the call, which means that RetType is just the return type.  Infer the
4766   // rest of the function argument types from the arguments that are present.
4767   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4768   if (!Ty) {
4769     // Pull out the types of all of the arguments...
4770     std::vector<Type*> ParamTypes;
4771     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4772       ParamTypes.push_back(ArgList[i].V->getType());
4773
4774     if (!FunctionType::isValidReturnType(RetType))
4775       return Error(RetTypeLoc, "Invalid result type for LLVM function");
4776
4777     Ty = FunctionType::get(RetType, ParamTypes, false);
4778   }
4779
4780   // Look up the callee.
4781   Value *Callee;
4782   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4783     return true;
4784
4785   // Set up the Attribute for the function.
4786   SmallVector<AttributeSet, 8> Attrs;
4787   if (RetAttrs.hasAttributes())
4788     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4789                                       AttributeSet::ReturnIndex,
4790                                       RetAttrs));
4791
4792   SmallVector<Value*, 8> Args;
4793
4794   // Loop through FunctionType's arguments and ensure they are specified
4795   // correctly.  Also, gather any parameter attributes.
4796   FunctionType::param_iterator I = Ty->param_begin();
4797   FunctionType::param_iterator E = Ty->param_end();
4798   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4799     Type *ExpectedTy = nullptr;
4800     if (I != E) {
4801       ExpectedTy = *I++;
4802     } else if (!Ty->isVarArg()) {
4803       return Error(ArgList[i].Loc, "too many arguments specified");
4804     }
4805
4806     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4807       return Error(ArgList[i].Loc, "argument is not of expected type '" +
4808                    getTypeString(ExpectedTy) + "'");
4809     Args.push_back(ArgList[i].V);
4810     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4811       AttrBuilder B(ArgList[i].Attrs, i + 1);
4812       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4813     }
4814   }
4815
4816   if (I != E)
4817     return Error(CallLoc, "not enough parameters specified for call");
4818
4819   if (FnAttrs.hasAttributes()) {
4820     if (FnAttrs.hasAlignmentAttr())
4821       return Error(CallLoc, "invoke instructions may not have an alignment");
4822
4823     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4824                                       AttributeSet::FunctionIndex,
4825                                       FnAttrs));
4826   }
4827
4828   // Finish off the Attribute and check them
4829   AttributeSet PAL = AttributeSet::get(Context, Attrs);
4830
4831   InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
4832   II->setCallingConv(CC);
4833   II->setAttributes(PAL);
4834   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4835   Inst = II;
4836   return false;
4837 }
4838
4839 /// ParseResume
4840 ///   ::= 'resume' TypeAndValue
4841 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4842   Value *Exn; LocTy ExnLoc;
4843   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4844     return true;
4845
4846   ResumeInst *RI = ResumeInst::Create(Exn);
4847   Inst = RI;
4848   return false;
4849 }
4850
4851 //===----------------------------------------------------------------------===//
4852 // Binary Operators.
4853 //===----------------------------------------------------------------------===//
4854
4855 /// ParseArithmetic
4856 ///  ::= ArithmeticOps TypeAndValue ',' Value
4857 ///
4858 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
4859 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4860 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4861                                unsigned Opc, unsigned OperandType) {
4862   LocTy Loc; Value *LHS, *RHS;
4863   if (ParseTypeAndValue(LHS, Loc, PFS) ||
4864       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4865       ParseValue(LHS->getType(), RHS, PFS))
4866     return true;
4867
4868   bool Valid;
4869   switch (OperandType) {
4870   default: llvm_unreachable("Unknown operand type!");
4871   case 0: // int or FP.
4872     Valid = LHS->getType()->isIntOrIntVectorTy() ||
4873             LHS->getType()->isFPOrFPVectorTy();
4874     break;
4875   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4876   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4877   }
4878
4879   if (!Valid)
4880     return Error(Loc, "invalid operand type for instruction");
4881
4882   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4883   return false;
4884 }
4885
4886 /// ParseLogical
4887 ///  ::= ArithmeticOps TypeAndValue ',' Value {
4888 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4889                             unsigned Opc) {
4890   LocTy Loc; Value *LHS, *RHS;
4891   if (ParseTypeAndValue(LHS, Loc, PFS) ||
4892       ParseToken(lltok::comma, "expected ',' in logical operation") ||
4893       ParseValue(LHS->getType(), RHS, PFS))
4894     return true;
4895
4896   if (!LHS->getType()->isIntOrIntVectorTy())
4897     return Error(Loc,"instruction requires integer or integer vector operands");
4898
4899   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4900   return false;
4901 }
4902
4903
4904 /// ParseCompare
4905 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
4906 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
4907 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4908                             unsigned Opc) {
4909   // Parse the integer/fp comparison predicate.
4910   LocTy Loc;
4911   unsigned Pred;
4912   Value *LHS, *RHS;
4913   if (ParseCmpPredicate(Pred, Opc) ||
4914       ParseTypeAndValue(LHS, Loc, PFS) ||
4915       ParseToken(lltok::comma, "expected ',' after compare value") ||
4916       ParseValue(LHS->getType(), RHS, PFS))
4917     return true;
4918
4919   if (Opc == Instruction::FCmp) {
4920     if (!LHS->getType()->isFPOrFPVectorTy())
4921       return Error(Loc, "fcmp requires floating point operands");
4922     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4923   } else {
4924     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4925     if (!LHS->getType()->isIntOrIntVectorTy() &&
4926         !LHS->getType()->getScalarType()->isPointerTy())
4927       return Error(Loc, "icmp requires integer operands");
4928     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4929   }
4930   return false;
4931 }
4932
4933 //===----------------------------------------------------------------------===//
4934 // Other Instructions.
4935 //===----------------------------------------------------------------------===//
4936
4937
4938 /// ParseCast
4939 ///   ::= CastOpc TypeAndValue 'to' Type
4940 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4941                          unsigned Opc) {
4942   LocTy Loc;
4943   Value *Op;
4944   Type *DestTy = nullptr;
4945   if (ParseTypeAndValue(Op, Loc, PFS) ||
4946       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4947       ParseType(DestTy))
4948     return true;
4949
4950   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4951     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4952     return Error(Loc, "invalid cast opcode for cast from '" +
4953                  getTypeString(Op->getType()) + "' to '" +
4954                  getTypeString(DestTy) + "'");
4955   }
4956   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4957   return false;
4958 }
4959
4960 /// ParseSelect
4961 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4962 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4963   LocTy Loc;
4964   Value *Op0, *Op1, *Op2;
4965   if (ParseTypeAndValue(Op0, Loc, PFS) ||
4966       ParseToken(lltok::comma, "expected ',' after select condition") ||
4967       ParseTypeAndValue(Op1, PFS) ||
4968       ParseToken(lltok::comma, "expected ',' after select value") ||
4969       ParseTypeAndValue(Op2, PFS))
4970     return true;
4971
4972   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4973     return Error(Loc, Reason);
4974
4975   Inst = SelectInst::Create(Op0, Op1, Op2);
4976   return false;
4977 }
4978
4979 /// ParseVA_Arg
4980 ///   ::= 'va_arg' TypeAndValue ',' Type
4981 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4982   Value *Op;
4983   Type *EltTy = nullptr;
4984   LocTy TypeLoc;
4985   if (ParseTypeAndValue(Op, PFS) ||
4986       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4987       ParseType(EltTy, TypeLoc))
4988     return true;
4989
4990   if (!EltTy->isFirstClassType())
4991     return Error(TypeLoc, "va_arg requires operand with first class type");
4992
4993   Inst = new VAArgInst(Op, EltTy);
4994   return false;
4995 }
4996
4997 /// ParseExtractElement
4998 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
4999 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
5000   LocTy Loc;
5001   Value *Op0, *Op1;
5002   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5003       ParseToken(lltok::comma, "expected ',' after extract value") ||
5004       ParseTypeAndValue(Op1, PFS))
5005     return true;
5006
5007   if (!ExtractElementInst::isValidOperands(Op0, Op1))
5008     return Error(Loc, "invalid extractelement operands");
5009
5010   Inst = ExtractElementInst::Create(Op0, Op1);
5011   return false;
5012 }
5013
5014 /// ParseInsertElement
5015 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5016 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5017   LocTy Loc;
5018   Value *Op0, *Op1, *Op2;
5019   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5020       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5021       ParseTypeAndValue(Op1, PFS) ||
5022       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5023       ParseTypeAndValue(Op2, PFS))
5024     return true;
5025
5026   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5027     return Error(Loc, "invalid insertelement operands");
5028
5029   Inst = InsertElementInst::Create(Op0, Op1, Op2);
5030   return false;
5031 }
5032
5033 /// ParseShuffleVector
5034 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5035 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5036   LocTy Loc;
5037   Value *Op0, *Op1, *Op2;
5038   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5039       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5040       ParseTypeAndValue(Op1, PFS) ||
5041       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5042       ParseTypeAndValue(Op2, PFS))
5043     return true;
5044
5045   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5046     return Error(Loc, "invalid shufflevector operands");
5047
5048   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5049   return false;
5050 }
5051
5052 /// ParsePHI
5053 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5054 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5055   Type *Ty = nullptr;  LocTy TypeLoc;
5056   Value *Op0, *Op1;
5057
5058   if (ParseType(Ty, TypeLoc) ||
5059       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5060       ParseValue(Ty, Op0, PFS) ||
5061       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5062       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5063       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5064     return true;
5065
5066   bool AteExtraComma = false;
5067   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5068   while (1) {
5069     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5070
5071     if (!EatIfPresent(lltok::comma))
5072       break;
5073
5074     if (Lex.getKind() == lltok::MetadataVar) {
5075       AteExtraComma = true;
5076       break;
5077     }
5078
5079     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5080         ParseValue(Ty, Op0, PFS) ||
5081         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5082         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5083         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5084       return true;
5085   }
5086
5087   if (!Ty->isFirstClassType())
5088     return Error(TypeLoc, "phi node must have first class type");
5089
5090   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5091   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5092     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5093   Inst = PN;
5094   return AteExtraComma ? InstExtraComma : InstNormal;
5095 }
5096
5097 /// ParseLandingPad
5098 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5099 /// Clause
5100 ///   ::= 'catch' TypeAndValue
5101 ///   ::= 'filter'
5102 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5103 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5104   Type *Ty = nullptr; LocTy TyLoc;
5105   Value *PersFn; LocTy PersFnLoc;
5106
5107   if (ParseType(Ty, TyLoc) ||
5108       ParseToken(lltok::kw_personality, "expected 'personality'") ||
5109       ParseTypeAndValue(PersFn, PersFnLoc, PFS))
5110     return true;
5111
5112   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, PersFn, 0));
5113   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5114
5115   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5116     LandingPadInst::ClauseType CT;
5117     if (EatIfPresent(lltok::kw_catch))
5118       CT = LandingPadInst::Catch;
5119     else if (EatIfPresent(lltok::kw_filter))
5120       CT = LandingPadInst::Filter;
5121     else
5122       return TokError("expected 'catch' or 'filter' clause type");
5123
5124     Value *V;
5125     LocTy VLoc;
5126     if (ParseTypeAndValue(V, VLoc, PFS))
5127       return true;
5128
5129     // A 'catch' type expects a non-array constant. A filter clause expects an
5130     // array constant.
5131     if (CT == LandingPadInst::Catch) {
5132       if (isa<ArrayType>(V->getType()))
5133         Error(VLoc, "'catch' clause has an invalid type");
5134     } else {
5135       if (!isa<ArrayType>(V->getType()))
5136         Error(VLoc, "'filter' clause has an invalid type");
5137     }
5138
5139     Constant *CV = dyn_cast<Constant>(V);
5140     if (!CV)
5141       return Error(VLoc, "clause argument must be a constant");
5142     LP->addClause(CV);
5143   }
5144
5145   Inst = LP.release();
5146   return false;
5147 }
5148
5149 /// ParseCall
5150 ///   ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5151 ///       ParameterList OptionalAttrs
5152 ///   ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5153 ///       ParameterList OptionalAttrs
5154 ///   ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5155 ///       ParameterList OptionalAttrs
5156 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5157                          CallInst::TailCallKind TCK) {
5158   AttrBuilder RetAttrs, FnAttrs;
5159   std::vector<unsigned> FwdRefAttrGrps;
5160   LocTy BuiltinLoc;
5161   unsigned CC;
5162   Type *RetType = nullptr;
5163   LocTy RetTypeLoc;
5164   ValID CalleeID;
5165   SmallVector<ParamInfo, 16> ArgList;
5166   LocTy CallLoc = Lex.getLoc();
5167
5168   if ((TCK != CallInst::TCK_None &&
5169        ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5170       ParseOptionalCallingConv(CC) ||
5171       ParseOptionalReturnAttrs(RetAttrs) ||
5172       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5173       ParseValID(CalleeID) ||
5174       ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5175                          PFS.getFunction().isVarArg()) ||
5176       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5177                                  BuiltinLoc))
5178     return true;
5179
5180   // If RetType is a non-function pointer type, then this is the short syntax
5181   // for the call, which means that RetType is just the return type.  Infer the
5182   // rest of the function argument types from the arguments that are present.
5183   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5184   if (!Ty) {
5185     // Pull out the types of all of the arguments...
5186     std::vector<Type*> ParamTypes;
5187     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5188       ParamTypes.push_back(ArgList[i].V->getType());
5189
5190     if (!FunctionType::isValidReturnType(RetType))
5191       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5192
5193     Ty = FunctionType::get(RetType, ParamTypes, false);
5194   }
5195
5196   // Look up the callee.
5197   Value *Callee;
5198   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5199     return true;
5200
5201   // Set up the Attribute for the function.
5202   SmallVector<AttributeSet, 8> Attrs;
5203   if (RetAttrs.hasAttributes())
5204     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5205                                       AttributeSet::ReturnIndex,
5206                                       RetAttrs));
5207
5208   SmallVector<Value*, 8> Args;
5209
5210   // Loop through FunctionType's arguments and ensure they are specified
5211   // correctly.  Also, gather any parameter attributes.
5212   FunctionType::param_iterator I = Ty->param_begin();
5213   FunctionType::param_iterator E = Ty->param_end();
5214   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5215     Type *ExpectedTy = nullptr;
5216     if (I != E) {
5217       ExpectedTy = *I++;
5218     } else if (!Ty->isVarArg()) {
5219       return Error(ArgList[i].Loc, "too many arguments specified");
5220     }
5221
5222     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5223       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5224                    getTypeString(ExpectedTy) + "'");
5225     Args.push_back(ArgList[i].V);
5226     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5227       AttrBuilder B(ArgList[i].Attrs, i + 1);
5228       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5229     }
5230   }
5231
5232   if (I != E)
5233     return Error(CallLoc, "not enough parameters specified for call");
5234
5235   if (FnAttrs.hasAttributes()) {
5236     if (FnAttrs.hasAlignmentAttr())
5237       return Error(CallLoc, "call instructions may not have an alignment");
5238
5239     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5240                                       AttributeSet::FunctionIndex,
5241                                       FnAttrs));
5242   }
5243
5244   // Finish off the Attribute and check them
5245   AttributeSet PAL = AttributeSet::get(Context, Attrs);
5246
5247   CallInst *CI = CallInst::Create(Ty, Callee, Args);
5248   CI->setTailCallKind(TCK);
5249   CI->setCallingConv(CC);
5250   CI->setAttributes(PAL);
5251   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5252   Inst = CI;
5253   return false;
5254 }
5255
5256 //===----------------------------------------------------------------------===//
5257 // Memory Instructions.
5258 //===----------------------------------------------------------------------===//
5259
5260 /// ParseAlloc
5261 ///   ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5262 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5263   Value *Size = nullptr;
5264   LocTy SizeLoc, TyLoc;
5265   unsigned Alignment = 0;
5266   Type *Ty = nullptr;
5267
5268   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5269
5270   if (ParseType(Ty, TyLoc)) return true;
5271
5272   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5273     return Error(TyLoc, "invalid type for alloca");
5274
5275   bool AteExtraComma = false;
5276   if (EatIfPresent(lltok::comma)) {
5277     if (Lex.getKind() == lltok::kw_align) {
5278       if (ParseOptionalAlignment(Alignment)) return true;
5279     } else if (Lex.getKind() == lltok::MetadataVar) {
5280       AteExtraComma = true;
5281     } else {
5282       if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5283           ParseOptionalCommaAlign(Alignment, AteExtraComma))
5284         return true;
5285     }
5286   }
5287
5288   if (Size && !Size->getType()->isIntegerTy())
5289     return Error(SizeLoc, "element count must have integer type");
5290
5291   AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5292   AI->setUsedWithInAlloca(IsInAlloca);
5293   Inst = AI;
5294   return AteExtraComma ? InstExtraComma : InstNormal;
5295 }
5296
5297 /// ParseLoad
5298 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5299 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
5300 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
5301 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5302   Value *Val; LocTy Loc;
5303   unsigned Alignment = 0;
5304   bool AteExtraComma = false;
5305   bool isAtomic = false;
5306   AtomicOrdering Ordering = NotAtomic;
5307   SynchronizationScope Scope = CrossThread;
5308
5309   if (Lex.getKind() == lltok::kw_atomic) {
5310     isAtomic = true;
5311     Lex.Lex();
5312   }
5313
5314   bool isVolatile = false;
5315   if (Lex.getKind() == lltok::kw_volatile) {
5316     isVolatile = true;
5317     Lex.Lex();
5318   }
5319
5320   Type *Ty;
5321   LocTy ExplicitTypeLoc = Lex.getLoc();
5322   if (ParseType(Ty) ||
5323       ParseToken(lltok::comma, "expected comma after load's type") ||
5324       ParseTypeAndValue(Val, Loc, PFS) ||
5325       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5326       ParseOptionalCommaAlign(Alignment, AteExtraComma))
5327     return true;
5328
5329   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5330     return Error(Loc, "load operand must be a pointer to a first class type");
5331   if (isAtomic && !Alignment)
5332     return Error(Loc, "atomic load must have explicit non-zero alignment");
5333   if (Ordering == Release || Ordering == AcquireRelease)
5334     return Error(Loc, "atomic load cannot use Release ordering");
5335
5336   if (Ty != cast<PointerType>(Val->getType())->getElementType())
5337     return Error(ExplicitTypeLoc,
5338                  "explicit pointee type doesn't match operand's pointee type");
5339
5340   Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5341   return AteExtraComma ? InstExtraComma : InstNormal;
5342 }
5343
5344 /// ParseStore
5345
5346 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5347 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5348 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
5349 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5350   Value *Val, *Ptr; LocTy Loc, PtrLoc;
5351   unsigned Alignment = 0;
5352   bool AteExtraComma = false;
5353   bool isAtomic = false;
5354   AtomicOrdering Ordering = NotAtomic;
5355   SynchronizationScope Scope = CrossThread;
5356
5357   if (Lex.getKind() == lltok::kw_atomic) {
5358     isAtomic = true;
5359     Lex.Lex();
5360   }
5361
5362   bool isVolatile = false;
5363   if (Lex.getKind() == lltok::kw_volatile) {
5364     isVolatile = true;
5365     Lex.Lex();
5366   }
5367
5368   if (ParseTypeAndValue(Val, Loc, PFS) ||
5369       ParseToken(lltok::comma, "expected ',' after store operand") ||
5370       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5371       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5372       ParseOptionalCommaAlign(Alignment, AteExtraComma))
5373     return true;
5374
5375   if (!Ptr->getType()->isPointerTy())
5376     return Error(PtrLoc, "store operand must be a pointer");
5377   if (!Val->getType()->isFirstClassType())
5378     return Error(Loc, "store operand must be a first class value");
5379   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5380     return Error(Loc, "stored value and pointer type do not match");
5381   if (isAtomic && !Alignment)
5382     return Error(Loc, "atomic store must have explicit non-zero alignment");
5383   if (Ordering == Acquire || Ordering == AcquireRelease)
5384     return Error(Loc, "atomic store cannot use Acquire ordering");
5385
5386   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5387   return AteExtraComma ? InstExtraComma : InstNormal;
5388 }
5389
5390 /// ParseCmpXchg
5391 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5392 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5393 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5394   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5395   bool AteExtraComma = false;
5396   AtomicOrdering SuccessOrdering = NotAtomic;
5397   AtomicOrdering FailureOrdering = NotAtomic;
5398   SynchronizationScope Scope = CrossThread;
5399   bool isVolatile = false;
5400   bool isWeak = false;
5401
5402   if (EatIfPresent(lltok::kw_weak))
5403     isWeak = true;
5404
5405   if (EatIfPresent(lltok::kw_volatile))
5406     isVolatile = true;
5407
5408   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5409       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5410       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5411       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5412       ParseTypeAndValue(New, NewLoc, PFS) ||
5413       ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5414       ParseOrdering(FailureOrdering))
5415     return true;
5416
5417   if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5418     return TokError("cmpxchg cannot be unordered");
5419   if (SuccessOrdering < FailureOrdering)
5420     return TokError("cmpxchg must be at least as ordered on success as failure");
5421   if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5422     return TokError("cmpxchg failure ordering cannot include release semantics");
5423   if (!Ptr->getType()->isPointerTy())
5424     return Error(PtrLoc, "cmpxchg operand must be a pointer");
5425   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5426     return Error(CmpLoc, "compare value and pointer type do not match");
5427   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5428     return Error(NewLoc, "new value and pointer type do not match");
5429   if (!New->getType()->isIntegerTy())
5430     return Error(NewLoc, "cmpxchg operand must be an integer");
5431   unsigned Size = New->getType()->getPrimitiveSizeInBits();
5432   if (Size < 8 || (Size & (Size - 1)))
5433     return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5434                          " integer");
5435
5436   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5437       Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5438   CXI->setVolatile(isVolatile);
5439   CXI->setWeak(isWeak);
5440   Inst = CXI;
5441   return AteExtraComma ? InstExtraComma : InstNormal;
5442 }
5443
5444 /// ParseAtomicRMW
5445 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5446 ///       'singlethread'? AtomicOrdering
5447 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5448   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5449   bool AteExtraComma = false;
5450   AtomicOrdering Ordering = NotAtomic;
5451   SynchronizationScope Scope = CrossThread;
5452   bool isVolatile = false;
5453   AtomicRMWInst::BinOp Operation;
5454
5455   if (EatIfPresent(lltok::kw_volatile))
5456     isVolatile = true;
5457
5458   switch (Lex.getKind()) {
5459   default: return TokError("expected binary operation in atomicrmw");
5460   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5461   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5462   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5463   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5464   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5465   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5466   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5467   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5468   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5469   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5470   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5471   }
5472   Lex.Lex();  // Eat the operation.
5473
5474   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5475       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5476       ParseTypeAndValue(Val, ValLoc, PFS) ||
5477       ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5478     return true;
5479
5480   if (Ordering == Unordered)
5481     return TokError("atomicrmw cannot be unordered");
5482   if (!Ptr->getType()->isPointerTy())
5483     return Error(PtrLoc, "atomicrmw operand must be a pointer");
5484   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5485     return Error(ValLoc, "atomicrmw value and pointer type do not match");
5486   if (!Val->getType()->isIntegerTy())
5487     return Error(ValLoc, "atomicrmw operand must be an integer");
5488   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5489   if (Size < 8 || (Size & (Size - 1)))
5490     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5491                          " integer");
5492
5493   AtomicRMWInst *RMWI =
5494     new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5495   RMWI->setVolatile(isVolatile);
5496   Inst = RMWI;
5497   return AteExtraComma ? InstExtraComma : InstNormal;
5498 }
5499
5500 /// ParseFence
5501 ///   ::= 'fence' 'singlethread'? AtomicOrdering
5502 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5503   AtomicOrdering Ordering = NotAtomic;
5504   SynchronizationScope Scope = CrossThread;
5505   if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5506     return true;
5507
5508   if (Ordering == Unordered)
5509     return TokError("fence cannot be unordered");
5510   if (Ordering == Monotonic)
5511     return TokError("fence cannot be monotonic");
5512
5513   Inst = new FenceInst(Context, Ordering, Scope);
5514   return InstNormal;
5515 }
5516
5517 /// ParseGetElementPtr
5518 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5519 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5520   Value *Ptr = nullptr;
5521   Value *Val = nullptr;
5522   LocTy Loc, EltLoc;
5523
5524   bool InBounds = EatIfPresent(lltok::kw_inbounds);
5525
5526   Type *Ty = nullptr;
5527   LocTy ExplicitTypeLoc = Lex.getLoc();
5528   if (ParseType(Ty) ||
5529       ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5530       ParseTypeAndValue(Ptr, Loc, PFS))
5531     return true;
5532
5533   Type *BaseType = Ptr->getType();
5534   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5535   if (!BasePointerType)
5536     return Error(Loc, "base of getelementptr must be a pointer");
5537
5538   if (Ty != BasePointerType->getElementType())
5539     return Error(ExplicitTypeLoc,
5540                  "explicit pointee type doesn't match operand's pointee type");
5541
5542   SmallVector<Value*, 16> Indices;
5543   bool AteExtraComma = false;
5544   while (EatIfPresent(lltok::comma)) {
5545     if (Lex.getKind() == lltok::MetadataVar) {
5546       AteExtraComma = true;
5547       break;
5548     }
5549     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5550     if (!Val->getType()->getScalarType()->isIntegerTy())
5551       return Error(EltLoc, "getelementptr index must be an integer");
5552     if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5553       return Error(EltLoc, "getelementptr index type missmatch");
5554     if (Val->getType()->isVectorTy()) {
5555       unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5556       unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5557       if (ValNumEl != PtrNumEl)
5558         return Error(EltLoc,
5559           "getelementptr vector index has a wrong number of elements");
5560     }
5561     Indices.push_back(Val);
5562   }
5563
5564   SmallPtrSet<const Type*, 4> Visited;
5565   if (!Indices.empty() && !Ty->isSized(&Visited))
5566     return Error(Loc, "base element of getelementptr must be sized");
5567
5568   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5569     return Error(Loc, "invalid getelementptr indices");
5570   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5571   if (InBounds)
5572     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5573   return AteExtraComma ? InstExtraComma : InstNormal;
5574 }
5575
5576 /// ParseExtractValue
5577 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
5578 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5579   Value *Val; LocTy Loc;
5580   SmallVector<unsigned, 4> Indices;
5581   bool AteExtraComma;
5582   if (ParseTypeAndValue(Val, Loc, PFS) ||
5583       ParseIndexList(Indices, AteExtraComma))
5584     return true;
5585
5586   if (!Val->getType()->isAggregateType())
5587     return Error(Loc, "extractvalue operand must be aggregate type");
5588
5589   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5590     return Error(Loc, "invalid indices for extractvalue");
5591   Inst = ExtractValueInst::Create(Val, Indices);
5592   return AteExtraComma ? InstExtraComma : InstNormal;
5593 }
5594
5595 /// ParseInsertValue
5596 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5597 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5598   Value *Val0, *Val1; LocTy Loc0, Loc1;
5599   SmallVector<unsigned, 4> Indices;
5600   bool AteExtraComma;
5601   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5602       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5603       ParseTypeAndValue(Val1, Loc1, PFS) ||
5604       ParseIndexList(Indices, AteExtraComma))
5605     return true;
5606
5607   if (!Val0->getType()->isAggregateType())
5608     return Error(Loc0, "insertvalue operand must be aggregate type");
5609
5610   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5611   if (!IndexedType)
5612     return Error(Loc0, "invalid indices for insertvalue");
5613   if (IndexedType != Val1->getType())
5614     return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5615                            getTypeString(Val1->getType()) + "' instead of '" +
5616                            getTypeString(IndexedType) + "'");
5617   Inst = InsertValueInst::Create(Val0, Val1, Indices);
5618   return AteExtraComma ? InstExtraComma : InstNormal;
5619 }
5620
5621 //===----------------------------------------------------------------------===//
5622 // Embedded metadata.
5623 //===----------------------------------------------------------------------===//
5624
5625 /// ParseMDNodeVector
5626 ///   ::= { Element (',' Element)* }
5627 /// Element
5628 ///   ::= 'null' | TypeAndValue
5629 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5630   if (ParseToken(lltok::lbrace, "expected '{' here"))
5631     return true;
5632
5633   // Check for an empty list.
5634   if (EatIfPresent(lltok::rbrace))
5635     return false;
5636
5637   do {
5638     // Null is a special case since it is typeless.
5639     if (EatIfPresent(lltok::kw_null)) {
5640       Elts.push_back(nullptr);
5641       continue;
5642     }
5643
5644     Metadata *MD;
5645     if (ParseMetadata(MD, nullptr))
5646       return true;
5647     Elts.push_back(MD);
5648   } while (EatIfPresent(lltok::comma));
5649
5650   return ParseToken(lltok::rbrace, "expected end of metadata node");
5651 }
5652
5653 //===----------------------------------------------------------------------===//
5654 // Use-list order directives.
5655 //===----------------------------------------------------------------------===//
5656 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5657                                 SMLoc Loc) {
5658   if (V->use_empty())
5659     return Error(Loc, "value has no uses");
5660
5661   unsigned NumUses = 0;
5662   SmallDenseMap<const Use *, unsigned, 16> Order;
5663   for (const Use &U : V->uses()) {
5664     if (++NumUses > Indexes.size())
5665       break;
5666     Order[&U] = Indexes[NumUses - 1];
5667   }
5668   if (NumUses < 2)
5669     return Error(Loc, "value only has one use");
5670   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5671     return Error(Loc, "wrong number of indexes, expected " +
5672                           Twine(std::distance(V->use_begin(), V->use_end())));
5673
5674   V->sortUseList([&](const Use &L, const Use &R) {
5675     return Order.lookup(&L) < Order.lookup(&R);
5676   });
5677   return false;
5678 }
5679
5680 /// ParseUseListOrderIndexes
5681 ///   ::= '{' uint32 (',' uint32)+ '}'
5682 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5683   SMLoc Loc = Lex.getLoc();
5684   if (ParseToken(lltok::lbrace, "expected '{' here"))
5685     return true;
5686   if (Lex.getKind() == lltok::rbrace)
5687     return Lex.Error("expected non-empty list of uselistorder indexes");
5688
5689   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
5690   // indexes should be distinct numbers in the range [0, size-1], and should
5691   // not be in order.
5692   unsigned Offset = 0;
5693   unsigned Max = 0;
5694   bool IsOrdered = true;
5695   assert(Indexes.empty() && "Expected empty order vector");
5696   do {
5697     unsigned Index;
5698     if (ParseUInt32(Index))
5699       return true;
5700
5701     // Update consistency checks.
5702     Offset += Index - Indexes.size();
5703     Max = std::max(Max, Index);
5704     IsOrdered &= Index == Indexes.size();
5705
5706     Indexes.push_back(Index);
5707   } while (EatIfPresent(lltok::comma));
5708
5709   if (ParseToken(lltok::rbrace, "expected '}' here"))
5710     return true;
5711
5712   if (Indexes.size() < 2)
5713     return Error(Loc, "expected >= 2 uselistorder indexes");
5714   if (Offset != 0 || Max >= Indexes.size())
5715     return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5716   if (IsOrdered)
5717     return Error(Loc, "expected uselistorder indexes to change the order");
5718
5719   return false;
5720 }
5721
5722 /// ParseUseListOrder
5723 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5724 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5725   SMLoc Loc = Lex.getLoc();
5726   if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5727     return true;
5728
5729   Value *V;
5730   SmallVector<unsigned, 16> Indexes;
5731   if (ParseTypeAndValue(V, PFS) ||
5732       ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5733       ParseUseListOrderIndexes(Indexes))
5734     return true;
5735
5736   return sortUseListOrder(V, Indexes, Loc);
5737 }
5738
5739 /// ParseUseListOrderBB
5740 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5741 bool LLParser::ParseUseListOrderBB() {
5742   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5743   SMLoc Loc = Lex.getLoc();
5744   Lex.Lex();
5745
5746   ValID Fn, Label;
5747   SmallVector<unsigned, 16> Indexes;
5748   if (ParseValID(Fn) ||
5749       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5750       ParseValID(Label) ||
5751       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5752       ParseUseListOrderIndexes(Indexes))
5753     return true;
5754
5755   // Check the function.
5756   GlobalValue *GV;
5757   if (Fn.Kind == ValID::t_GlobalName)
5758     GV = M->getNamedValue(Fn.StrVal);
5759   else if (Fn.Kind == ValID::t_GlobalID)
5760     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5761   else
5762     return Error(Fn.Loc, "expected function name in uselistorder_bb");
5763   if (!GV)
5764     return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5765   auto *F = dyn_cast<Function>(GV);
5766   if (!F)
5767     return Error(Fn.Loc, "expected function name in uselistorder_bb");
5768   if (F->isDeclaration())
5769     return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5770
5771   // Check the basic block.
5772   if (Label.Kind == ValID::t_LocalID)
5773     return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5774   if (Label.Kind != ValID::t_LocalName)
5775     return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5776   Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5777   if (!V)
5778     return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5779   if (!isa<BasicBlock>(V))
5780     return Error(Label.Loc, "expected basic block in uselistorder_bb");
5781
5782   return sortUseListOrder(V, Indexes, Loc);
5783 }