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