Add 'musttail' marker to call instructions
[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/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29
30 static std::string getTypeString(Type *T) {
31   std::string Result;
32   raw_string_ostream Tmp(Result);
33   Tmp << *T;
34   return Tmp.str();
35 }
36
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
39   // Prime the lexer.
40   Lex.Lex();
41
42   return ParseTopLevelEntities() ||
43          ValidateEndOfModule();
44 }
45
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 /// module.
48 bool LLParser::ValidateEndOfModule() {
49   // Handle any instruction metadata forward references.
50   if (!ForwardRefInstMetadata.empty()) {
51     for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52          I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53          I != E; ++I) {
54       Instruction *Inst = I->first;
55       const std::vector<MDRef> &MDList = I->second;
56
57       for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58         unsigned SlotNo = MDList[i].MDSlot;
59
60         if (SlotNo >= NumberedMetadata.size() ||
61             NumberedMetadata[SlotNo] == nullptr)
62           return Error(MDList[i].Loc, "use of undefined metadata '!" +
63                        Twine(SlotNo) + "'");
64         Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65       }
66     }
67     ForwardRefInstMetadata.clear();
68   }
69
70   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
72
73   // Handle any function attribute group forward references.
74   for (std::map<Value*, std::vector<unsigned> >::iterator
75          I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
76          I != E; ++I) {
77     Value *V = I->first;
78     std::vector<unsigned> &Vec = I->second;
79     AttrBuilder B;
80
81     for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
82          VI != VE; ++VI)
83       B.merge(NumberedAttrBuilders[*VI]);
84
85     if (Function *Fn = dyn_cast<Function>(V)) {
86       AttributeSet AS = Fn->getAttributes();
87       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89                                AS.getFnAttributes());
90
91       FnAttrs.merge(B);
92
93       // If the alignment was parsed as an attribute, move to the alignment
94       // field.
95       if (FnAttrs.hasAlignmentAttr()) {
96         Fn->setAlignment(FnAttrs.getAlignment());
97         FnAttrs.removeAttribute(Attribute::Alignment);
98       }
99
100       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101                             AttributeSet::get(Context,
102                                               AttributeSet::FunctionIndex,
103                                               FnAttrs));
104       Fn->setAttributes(AS);
105     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106       AttributeSet AS = CI->getAttributes();
107       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109                                AS.getFnAttributes());
110       FnAttrs.merge(B);
111       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112                             AttributeSet::get(Context,
113                                               AttributeSet::FunctionIndex,
114                                               FnAttrs));
115       CI->setAttributes(AS);
116     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117       AttributeSet AS = II->getAttributes();
118       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120                                AS.getFnAttributes());
121       FnAttrs.merge(B);
122       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123                             AttributeSet::get(Context,
124                                               AttributeSet::FunctionIndex,
125                                               FnAttrs));
126       II->setAttributes(AS);
127     } else {
128       llvm_unreachable("invalid object with forward attribute group reference");
129     }
130   }
131
132   // If there are entries in ForwardRefBlockAddresses at this point, they are
133   // references after the function was defined.  Resolve those now.
134   while (!ForwardRefBlockAddresses.empty()) {
135     // Okay, we are referencing an already-parsed function, resolve them now.
136     Function *TheFn = nullptr;
137     const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138     if (Fn.Kind == ValID::t_GlobalName)
139       TheFn = M->getFunction(Fn.StrVal);
140     else if (Fn.UIntVal < NumberedVals.size())
141       TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
142
143     if (!TheFn)
144       return Error(Fn.Loc, "unknown function referenced by blockaddress");
145
146     // Resolve all these references.
147     if (ResolveForwardRefBlockAddresses(TheFn,
148                                       ForwardRefBlockAddresses.begin()->second,
149                                         nullptr))
150       return true;
151
152     ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
153   }
154
155   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156     if (NumberedTypes[i].second.isValid())
157       return Error(NumberedTypes[i].second,
158                    "use of undefined type '%" + Twine(i) + "'");
159
160   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162     if (I->second.second.isValid())
163       return Error(I->second.second,
164                    "use of undefined type named '" + I->getKey() + "'");
165
166   if (!ForwardRefVals.empty())
167     return Error(ForwardRefVals.begin()->second.second,
168                  "use of undefined value '@" + ForwardRefVals.begin()->first +
169                  "'");
170
171   if (!ForwardRefValIDs.empty())
172     return Error(ForwardRefValIDs.begin()->second.second,
173                  "use of undefined value '@" +
174                  Twine(ForwardRefValIDs.begin()->first) + "'");
175
176   if (!ForwardRefMDNodes.empty())
177     return Error(ForwardRefMDNodes.begin()->second.second,
178                  "use of undefined metadata '!" +
179                  Twine(ForwardRefMDNodes.begin()->first) + "'");
180
181
182   // Look for intrinsic functions and CallInst that need to be upgraded
183   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
184     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
185
186   UpgradeDebugInfo(*M);
187
188   return false;
189 }
190
191 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
192                              std::vector<std::pair<ValID, GlobalValue*> > &Refs,
193                                                PerFunctionState *PFS) {
194   // Loop over all the references, resolving them.
195   for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
196     BasicBlock *Res;
197     if (PFS) {
198       if (Refs[i].first.Kind == ValID::t_LocalName)
199         Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
200       else
201         Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
202     } else if (Refs[i].first.Kind == ValID::t_LocalID) {
203       return Error(Refs[i].first.Loc,
204        "cannot take address of numeric label after the function is defined");
205     } else {
206       Res = dyn_cast_or_null<BasicBlock>(
207                      TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
208     }
209
210     if (!Res)
211       return Error(Refs[i].first.Loc,
212                    "referenced value is not a basic block");
213
214     // Get the BlockAddress for this and update references to use it.
215     BlockAddress *BA = BlockAddress::get(TheFn, Res);
216     Refs[i].second->replaceAllUsesWith(BA);
217     Refs[i].second->eraseFromParent();
218   }
219   return false;
220 }
221
222
223 //===----------------------------------------------------------------------===//
224 // Top-Level Entities
225 //===----------------------------------------------------------------------===//
226
227 bool LLParser::ParseTopLevelEntities() {
228   while (1) {
229     switch (Lex.getKind()) {
230     default:         return TokError("expected top-level entity");
231     case lltok::Eof: return false;
232     case lltok::kw_declare: if (ParseDeclare()) return true; break;
233     case lltok::kw_define:  if (ParseDefine()) return true; break;
234     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
235     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
236     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
237     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
238     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
239     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
240     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
241     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
242     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
243
244     // The Global variable production with no name can have many different
245     // optional leading prefixes, the production is:
246     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
247     //               OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
248     //               ('constant'|'global') ...
249     case lltok::kw_private:             // OptionalLinkage
250     case lltok::kw_internal:            // OptionalLinkage
251     case lltok::kw_linker_private:      // Obsolete OptionalLinkage
252     case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
253     case lltok::kw_weak:                // OptionalLinkage
254     case lltok::kw_weak_odr:            // OptionalLinkage
255     case lltok::kw_linkonce:            // OptionalLinkage
256     case lltok::kw_linkonce_odr:        // OptionalLinkage
257     case lltok::kw_appending:           // OptionalLinkage
258     case lltok::kw_common:              // OptionalLinkage
259     case lltok::kw_extern_weak:         // OptionalLinkage
260     case lltok::kw_external: {          // OptionalLinkage
261       unsigned Linkage, Visibility, DLLStorageClass;
262       if (ParseOptionalLinkage(Linkage) ||
263           ParseOptionalVisibility(Visibility) ||
264           ParseOptionalDLLStorageClass(DLLStorageClass) ||
265           ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass))
266         return true;
267       break;
268     }
269     case lltok::kw_default:       // OptionalVisibility
270     case lltok::kw_hidden:        // OptionalVisibility
271     case lltok::kw_protected: {   // OptionalVisibility
272       unsigned Visibility, DLLStorageClass;
273       if (ParseOptionalVisibility(Visibility) ||
274           ParseOptionalDLLStorageClass(DLLStorageClass) ||
275           ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass))
276         return true;
277       break;
278     }
279
280     case lltok::kw_thread_local:  // OptionalThreadLocal
281     case lltok::kw_addrspace:     // OptionalAddrSpace
282     case lltok::kw_constant:      // GlobalType
283     case lltok::kw_global:        // GlobalType
284       if (ParseGlobal("", SMLoc(), 0, false, 0, 0)) return true;
285       break;
286
287     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
288     }
289   }
290 }
291
292
293 /// toplevelentity
294 ///   ::= 'module' 'asm' STRINGCONSTANT
295 bool LLParser::ParseModuleAsm() {
296   assert(Lex.getKind() == lltok::kw_module);
297   Lex.Lex();
298
299   std::string AsmStr;
300   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
301       ParseStringConstant(AsmStr)) return true;
302
303   M->appendModuleInlineAsm(AsmStr);
304   return false;
305 }
306
307 /// toplevelentity
308 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
309 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
310 bool LLParser::ParseTargetDefinition() {
311   assert(Lex.getKind() == lltok::kw_target);
312   std::string Str;
313   switch (Lex.Lex()) {
314   default: return TokError("unknown target property");
315   case lltok::kw_triple:
316     Lex.Lex();
317     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
318         ParseStringConstant(Str))
319       return true;
320     M->setTargetTriple(Str);
321     return false;
322   case lltok::kw_datalayout:
323     Lex.Lex();
324     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
325         ParseStringConstant(Str))
326       return true;
327     M->setDataLayout(Str);
328     return false;
329   }
330 }
331
332 /// toplevelentity
333 ///   ::= 'deplibs' '=' '[' ']'
334 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
335 /// FIXME: Remove in 4.0. Currently parse, but ignore.
336 bool LLParser::ParseDepLibs() {
337   assert(Lex.getKind() == lltok::kw_deplibs);
338   Lex.Lex();
339   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
340       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
341     return true;
342
343   if (EatIfPresent(lltok::rsquare))
344     return false;
345
346   do {
347     std::string Str;
348     if (ParseStringConstant(Str)) return true;
349   } while (EatIfPresent(lltok::comma));
350
351   return ParseToken(lltok::rsquare, "expected ']' at end of list");
352 }
353
354 /// ParseUnnamedType:
355 ///   ::= LocalVarID '=' 'type' type
356 bool LLParser::ParseUnnamedType() {
357   LocTy TypeLoc = Lex.getLoc();
358   unsigned TypeID = Lex.getUIntVal();
359   Lex.Lex(); // eat LocalVarID;
360
361   if (ParseToken(lltok::equal, "expected '=' after name") ||
362       ParseToken(lltok::kw_type, "expected 'type' after '='"))
363     return true;
364
365   if (TypeID >= NumberedTypes.size())
366     NumberedTypes.resize(TypeID+1);
367
368   Type *Result = nullptr;
369   if (ParseStructDefinition(TypeLoc, "",
370                             NumberedTypes[TypeID], Result)) return true;
371
372   if (!isa<StructType>(Result)) {
373     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
374     if (Entry.first)
375       return Error(TypeLoc, "non-struct types may not be recursive");
376     Entry.first = Result;
377     Entry.second = SMLoc();
378   }
379
380   return false;
381 }
382
383
384 /// toplevelentity
385 ///   ::= LocalVar '=' 'type' type
386 bool LLParser::ParseNamedType() {
387   std::string Name = Lex.getStrVal();
388   LocTy NameLoc = Lex.getLoc();
389   Lex.Lex();  // eat LocalVar.
390
391   if (ParseToken(lltok::equal, "expected '=' after name") ||
392       ParseToken(lltok::kw_type, "expected 'type' after name"))
393     return true;
394
395   Type *Result = nullptr;
396   if (ParseStructDefinition(NameLoc, Name,
397                             NamedTypes[Name], Result)) return true;
398
399   if (!isa<StructType>(Result)) {
400     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
401     if (Entry.first)
402       return Error(NameLoc, "non-struct types may not be recursive");
403     Entry.first = Result;
404     Entry.second = SMLoc();
405   }
406
407   return false;
408 }
409
410
411 /// toplevelentity
412 ///   ::= 'declare' FunctionHeader
413 bool LLParser::ParseDeclare() {
414   assert(Lex.getKind() == lltok::kw_declare);
415   Lex.Lex();
416
417   Function *F;
418   return ParseFunctionHeader(F, false);
419 }
420
421 /// toplevelentity
422 ///   ::= 'define' FunctionHeader '{' ...
423 bool LLParser::ParseDefine() {
424   assert(Lex.getKind() == lltok::kw_define);
425   Lex.Lex();
426
427   Function *F;
428   return ParseFunctionHeader(F, true) ||
429          ParseFunctionBody(*F);
430 }
431
432 /// ParseGlobalType
433 ///   ::= 'constant'
434 ///   ::= 'global'
435 bool LLParser::ParseGlobalType(bool &IsConstant) {
436   if (Lex.getKind() == lltok::kw_constant)
437     IsConstant = true;
438   else if (Lex.getKind() == lltok::kw_global)
439     IsConstant = false;
440   else {
441     IsConstant = false;
442     return TokError("expected 'global' or 'constant'");
443   }
444   Lex.Lex();
445   return false;
446 }
447
448 /// ParseUnnamedGlobal:
449 ///   OptionalVisibility ALIAS ...
450 ///   OptionalLinkage OptionalVisibility OptionalDLLStorageClass
451 ///                                                     ...   -> global variable
452 ///   GlobalID '=' OptionalVisibility ALIAS ...
453 ///   GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
454 ///                                                     ...   -> global variable
455 bool LLParser::ParseUnnamedGlobal() {
456   unsigned VarID = NumberedVals.size();
457   std::string Name;
458   LocTy NameLoc = Lex.getLoc();
459
460   // Handle the GlobalID form.
461   if (Lex.getKind() == lltok::GlobalID) {
462     if (Lex.getUIntVal() != VarID)
463       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
464                    Twine(VarID) + "'");
465     Lex.Lex(); // eat GlobalID;
466
467     if (ParseToken(lltok::equal, "expected '=' after name"))
468       return true;
469   }
470
471   bool HasLinkage;
472   unsigned Linkage, Visibility, DLLStorageClass;
473   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
474       ParseOptionalVisibility(Visibility) ||
475       ParseOptionalDLLStorageClass(DLLStorageClass))
476     return true;
477
478   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
479     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
480                        DLLStorageClass);
481   return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
482 }
483
484 /// ParseNamedGlobal:
485 ///   GlobalVar '=' OptionalVisibility ALIAS ...
486 ///   GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
487 ///                                                     ...   -> global variable
488 bool LLParser::ParseNamedGlobal() {
489   assert(Lex.getKind() == lltok::GlobalVar);
490   LocTy NameLoc = Lex.getLoc();
491   std::string Name = Lex.getStrVal();
492   Lex.Lex();
493
494   bool HasLinkage;
495   unsigned Linkage, Visibility, DLLStorageClass;
496   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
497       ParseOptionalLinkage(Linkage, HasLinkage) ||
498       ParseOptionalVisibility(Visibility) ||
499       ParseOptionalDLLStorageClass(DLLStorageClass))
500     return true;
501
502   if (HasLinkage || Lex.getKind() != lltok::kw_alias)
503     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
504                        DLLStorageClass);
505   return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
506 }
507
508 // MDString:
509 //   ::= '!' STRINGCONSTANT
510 bool LLParser::ParseMDString(MDString *&Result) {
511   std::string Str;
512   if (ParseStringConstant(Str)) return true;
513   Result = MDString::get(Context, Str);
514   return false;
515 }
516
517 // MDNode:
518 //   ::= '!' MDNodeNumber
519 //
520 /// This version of ParseMDNodeID returns the slot number and null in the case
521 /// of a forward reference.
522 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
523   // !{ ..., !42, ... }
524   if (ParseUInt32(SlotNo)) return true;
525
526   // Check existing MDNode.
527   if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
528     Result = NumberedMetadata[SlotNo];
529   else
530     Result = nullptr;
531   return false;
532 }
533
534 bool LLParser::ParseMDNodeID(MDNode *&Result) {
535   // !{ ..., !42, ... }
536   unsigned MID = 0;
537   if (ParseMDNodeID(Result, MID)) return true;
538
539   // If not a forward reference, just return it now.
540   if (Result) return false;
541
542   // Otherwise, create MDNode forward reference.
543   MDNode *FwdNode = MDNode::getTemporary(Context, None);
544   ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
545
546   if (NumberedMetadata.size() <= MID)
547     NumberedMetadata.resize(MID+1);
548   NumberedMetadata[MID] = FwdNode;
549   Result = FwdNode;
550   return false;
551 }
552
553 /// ParseNamedMetadata:
554 ///   !foo = !{ !1, !2 }
555 bool LLParser::ParseNamedMetadata() {
556   assert(Lex.getKind() == lltok::MetadataVar);
557   std::string Name = Lex.getStrVal();
558   Lex.Lex();
559
560   if (ParseToken(lltok::equal, "expected '=' here") ||
561       ParseToken(lltok::exclaim, "Expected '!' here") ||
562       ParseToken(lltok::lbrace, "Expected '{' here"))
563     return true;
564
565   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
566   if (Lex.getKind() != lltok::rbrace)
567     do {
568       if (ParseToken(lltok::exclaim, "Expected '!' here"))
569         return true;
570
571       MDNode *N = nullptr;
572       if (ParseMDNodeID(N)) return true;
573       NMD->addOperand(N);
574     } while (EatIfPresent(lltok::comma));
575
576   if (ParseToken(lltok::rbrace, "expected end of metadata node"))
577     return true;
578
579   return false;
580 }
581
582 /// ParseStandaloneMetadata:
583 ///   !42 = !{...}
584 bool LLParser::ParseStandaloneMetadata() {
585   assert(Lex.getKind() == lltok::exclaim);
586   Lex.Lex();
587   unsigned MetadataID = 0;
588
589   LocTy TyLoc;
590   Type *Ty = nullptr;
591   SmallVector<Value *, 16> Elts;
592   if (ParseUInt32(MetadataID) ||
593       ParseToken(lltok::equal, "expected '=' here") ||
594       ParseType(Ty, TyLoc) ||
595       ParseToken(lltok::exclaim, "Expected '!' here") ||
596       ParseToken(lltok::lbrace, "Expected '{' here") ||
597       ParseMDNodeVector(Elts, nullptr) ||
598       ParseToken(lltok::rbrace, "expected end of metadata node"))
599     return true;
600
601   MDNode *Init = MDNode::get(Context, Elts);
602
603   // See if this was forward referenced, if so, handle it.
604   std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
605     FI = ForwardRefMDNodes.find(MetadataID);
606   if (FI != ForwardRefMDNodes.end()) {
607     MDNode *Temp = FI->second.first;
608     Temp->replaceAllUsesWith(Init);
609     MDNode::deleteTemporary(Temp);
610     ForwardRefMDNodes.erase(FI);
611
612     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
613   } else {
614     if (MetadataID >= NumberedMetadata.size())
615       NumberedMetadata.resize(MetadataID+1);
616
617     if (NumberedMetadata[MetadataID] != nullptr)
618       return TokError("Metadata id is already used");
619     NumberedMetadata[MetadataID] = Init;
620   }
621
622   return false;
623 }
624
625 /// ParseAlias:
626 ///   ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
627 ///                     OptionalLinkage Aliasee
628 /// Aliasee
629 ///   ::= TypeAndValue
630 ///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
631 ///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
632 ///
633 /// Everything through DLL storage class has already been parsed.
634 ///
635 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
636                           unsigned Visibility, unsigned DLLStorageClass) {
637   assert(Lex.getKind() == lltok::kw_alias);
638   Lex.Lex();
639   LocTy LinkageLoc = Lex.getLoc();
640   unsigned L;
641   if (ParseOptionalLinkage(L))
642     return true;
643
644   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
645
646   if(!GlobalAlias::isValidLinkage(Linkage))
647     return Error(LinkageLoc, "invalid linkage type for alias");
648
649   Constant *Aliasee;
650   LocTy AliaseeLoc = Lex.getLoc();
651   if (Lex.getKind() != lltok::kw_bitcast &&
652       Lex.getKind() != lltok::kw_getelementptr) {
653     if (ParseGlobalTypeAndValue(Aliasee)) return true;
654   } else {
655     // The bitcast dest type is not present, it is implied by the dest type.
656     ValID ID;
657     if (ParseValID(ID)) return true;
658     if (ID.Kind != ValID::t_Constant)
659       return Error(AliaseeLoc, "invalid aliasee");
660     Aliasee = ID.ConstantVal;
661   }
662
663   if (!Aliasee->getType()->isPointerTy())
664     return Error(AliaseeLoc, "alias must have pointer type");
665
666   // Okay, create the alias but do not insert it into the module yet.
667   GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
668                                     (GlobalValue::LinkageTypes)Linkage, Name,
669                                     Aliasee);
670   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
671   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
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);
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);
698   assert(GA->getName() == Name && "Should not be a name conflict!");
699
700   return false;
701 }
702
703 /// ParseGlobal
704 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
705 ///       OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
706 ///       OptionalExternallyInitialized GlobalType Type Const
707 ///   ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
708 ///       OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
709 ///       OptionalExternallyInitialized GlobalType Type Const
710 ///
711 /// Everything up to and including OptionalDLLStorageClass has been parsed
712 /// already.
713 ///
714 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
715                            unsigned Linkage, bool HasLinkage,
716                            unsigned Visibility, unsigned DLLStorageClass) {
717   unsigned AddrSpace;
718   bool IsConstant, UnnamedAddr, IsExternallyInitialized;
719   GlobalVariable::ThreadLocalMode TLM;
720   LocTy UnnamedAddrLoc;
721   LocTy IsExternallyInitializedLoc;
722   LocTy TyLoc;
723
724   Type *Ty = nullptr;
725   if (ParseOptionalThreadLocal(TLM) ||
726       ParseOptionalAddrSpace(AddrSpace) ||
727       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
728                          &UnnamedAddrLoc) ||
729       ParseOptionalToken(lltok::kw_externally_initialized,
730                          IsExternallyInitialized,
731                          &IsExternallyInitializedLoc) ||
732       ParseGlobalType(IsConstant) ||
733       ParseType(Ty, TyLoc))
734     return true;
735
736   // If the linkage is specified and is external, then no initializer is
737   // present.
738   Constant *Init = nullptr;
739   if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
740                       Linkage != GlobalValue::ExternalLinkage)) {
741     if (ParseGlobalValue(Ty, Init))
742       return true;
743   }
744
745   if (Ty->isFunctionTy() || Ty->isLabelTy())
746     return Error(TyLoc, "invalid type for global variable");
747
748   GlobalVariable *GV = nullptr;
749
750   // See if the global was forward referenced, if so, use the global.
751   if (!Name.empty()) {
752     if (GlobalValue *GVal = M->getNamedValue(Name)) {
753       if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
754         return Error(NameLoc, "redefinition of global '@" + Name + "'");
755       GV = cast<GlobalVariable>(GVal);
756     }
757   } else {
758     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
759       I = ForwardRefValIDs.find(NumberedVals.size());
760     if (I != ForwardRefValIDs.end()) {
761       GV = cast<GlobalVariable>(I->second.first);
762       ForwardRefValIDs.erase(I);
763     }
764   }
765
766   if (!GV) {
767     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
768                             Name, nullptr, GlobalVariable::NotThreadLocal,
769                             AddrSpace);
770   } else {
771     if (GV->getType()->getElementType() != Ty)
772       return Error(TyLoc,
773             "forward reference and definition of global have different types");
774
775     // Move the forward-reference to the correct spot in the module.
776     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
777   }
778
779   if (Name.empty())
780     NumberedVals.push_back(GV);
781
782   // Set the parsed properties on the global.
783   if (Init)
784     GV->setInitializer(Init);
785   GV->setConstant(IsConstant);
786   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
787   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
788   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
789   GV->setExternallyInitialized(IsExternallyInitialized);
790   GV->setThreadLocalMode(TLM);
791   GV->setUnnamedAddr(UnnamedAddr);
792
793   // Parse attributes on the global.
794   while (Lex.getKind() == lltok::comma) {
795     Lex.Lex();
796
797     if (Lex.getKind() == lltok::kw_section) {
798       Lex.Lex();
799       GV->setSection(Lex.getStrVal());
800       if (ParseToken(lltok::StringConstant, "expected global section string"))
801         return true;
802     } else if (Lex.getKind() == lltok::kw_align) {
803       unsigned Alignment;
804       if (ParseOptionalAlignment(Alignment)) return true;
805       GV->setAlignment(Alignment);
806     } else {
807       TokError("unknown global variable property!");
808     }
809   }
810
811   return false;
812 }
813
814 /// ParseUnnamedAttrGrp
815 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
816 bool LLParser::ParseUnnamedAttrGrp() {
817   assert(Lex.getKind() == lltok::kw_attributes);
818   LocTy AttrGrpLoc = Lex.getLoc();
819   Lex.Lex();
820
821   assert(Lex.getKind() == lltok::AttrGrpID);
822   unsigned VarID = Lex.getUIntVal();
823   std::vector<unsigned> unused;
824   LocTy BuiltinLoc;
825   Lex.Lex();
826
827   if (ParseToken(lltok::equal, "expected '=' here") ||
828       ParseToken(lltok::lbrace, "expected '{' here") ||
829       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
830                                  BuiltinLoc) ||
831       ParseToken(lltok::rbrace, "expected end of attribute group"))
832     return true;
833
834   if (!NumberedAttrBuilders[VarID].hasAttributes())
835     return Error(AttrGrpLoc, "attribute group has no attributes");
836
837   return false;
838 }
839
840 /// ParseFnAttributeValuePairs
841 ///   ::= <attr> | <attr> '=' <value>
842 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
843                                           std::vector<unsigned> &FwdRefAttrGrps,
844                                           bool inAttrGrp, LocTy &BuiltinLoc) {
845   bool HaveError = false;
846
847   B.clear();
848
849   while (true) {
850     lltok::Kind Token = Lex.getKind();
851     if (Token == lltok::kw_builtin)
852       BuiltinLoc = Lex.getLoc();
853     switch (Token) {
854     default:
855       if (!inAttrGrp) return HaveError;
856       return Error(Lex.getLoc(), "unterminated attribute group");
857     case lltok::rbrace:
858       // Finished.
859       return false;
860
861     case lltok::AttrGrpID: {
862       // Allow a function to reference an attribute group:
863       //
864       //   define void @foo() #1 { ... }
865       if (inAttrGrp)
866         HaveError |=
867           Error(Lex.getLoc(),
868               "cannot have an attribute group reference in an attribute group");
869
870       unsigned AttrGrpNum = Lex.getUIntVal();
871       if (inAttrGrp) break;
872
873       // Save the reference to the attribute group. We'll fill it in later.
874       FwdRefAttrGrps.push_back(AttrGrpNum);
875       break;
876     }
877     // Target-dependent attributes:
878     case lltok::StringConstant: {
879       std::string Attr = Lex.getStrVal();
880       Lex.Lex();
881       std::string Val;
882       if (EatIfPresent(lltok::equal) &&
883           ParseStringConstant(Val))
884         return true;
885
886       B.addAttribute(Attr, Val);
887       continue;
888     }
889
890     // Target-independent attributes:
891     case lltok::kw_align: {
892       // As a hack, we allow function alignment to be initially parsed as an
893       // attribute on a function declaration/definition or added to an attribute
894       // group and later moved to the alignment field.
895       unsigned Alignment;
896       if (inAttrGrp) {
897         Lex.Lex();
898         if (ParseToken(lltok::equal, "expected '=' here") ||
899             ParseUInt32(Alignment))
900           return true;
901       } else {
902         if (ParseOptionalAlignment(Alignment))
903           return true;
904       }
905       B.addAlignmentAttr(Alignment);
906       continue;
907     }
908     case lltok::kw_alignstack: {
909       unsigned Alignment;
910       if (inAttrGrp) {
911         Lex.Lex();
912         if (ParseToken(lltok::equal, "expected '=' here") ||
913             ParseUInt32(Alignment))
914           return true;
915       } else {
916         if (ParseOptionalStackAlignment(Alignment))
917           return true;
918       }
919       B.addStackAlignmentAttr(Alignment);
920       continue;
921     }
922     case lltok::kw_alwaysinline:      B.addAttribute(Attribute::AlwaysInline); break;
923     case lltok::kw_builtin:           B.addAttribute(Attribute::Builtin); break;
924     case lltok::kw_cold:              B.addAttribute(Attribute::Cold); break;
925     case lltok::kw_inlinehint:        B.addAttribute(Attribute::InlineHint); break;
926     case lltok::kw_minsize:           B.addAttribute(Attribute::MinSize); break;
927     case lltok::kw_naked:             B.addAttribute(Attribute::Naked); break;
928     case lltok::kw_nobuiltin:         B.addAttribute(Attribute::NoBuiltin); break;
929     case lltok::kw_noduplicate:       B.addAttribute(Attribute::NoDuplicate); break;
930     case lltok::kw_noimplicitfloat:   B.addAttribute(Attribute::NoImplicitFloat); break;
931     case lltok::kw_noinline:          B.addAttribute(Attribute::NoInline); break;
932     case lltok::kw_nonlazybind:       B.addAttribute(Attribute::NonLazyBind); break;
933     case lltok::kw_noredzone:         B.addAttribute(Attribute::NoRedZone); break;
934     case lltok::kw_noreturn:          B.addAttribute(Attribute::NoReturn); break;
935     case lltok::kw_nounwind:          B.addAttribute(Attribute::NoUnwind); break;
936     case lltok::kw_optnone:           B.addAttribute(Attribute::OptimizeNone); break;
937     case lltok::kw_optsize:           B.addAttribute(Attribute::OptimizeForSize); break;
938     case lltok::kw_readnone:          B.addAttribute(Attribute::ReadNone); break;
939     case lltok::kw_readonly:          B.addAttribute(Attribute::ReadOnly); break;
940     case lltok::kw_returns_twice:     B.addAttribute(Attribute::ReturnsTwice); break;
941     case lltok::kw_ssp:               B.addAttribute(Attribute::StackProtect); break;
942     case lltok::kw_sspreq:            B.addAttribute(Attribute::StackProtectReq); break;
943     case lltok::kw_sspstrong:         B.addAttribute(Attribute::StackProtectStrong); break;
944     case lltok::kw_sanitize_address:  B.addAttribute(Attribute::SanitizeAddress); break;
945     case lltok::kw_sanitize_thread:   B.addAttribute(Attribute::SanitizeThread); break;
946     case lltok::kw_sanitize_memory:   B.addAttribute(Attribute::SanitizeMemory); break;
947     case lltok::kw_uwtable:           B.addAttribute(Attribute::UWTable); break;
948
949     // Error handling.
950     case lltok::kw_inreg:
951     case lltok::kw_signext:
952     case lltok::kw_zeroext:
953       HaveError |=
954         Error(Lex.getLoc(),
955               "invalid use of attribute on a function");
956       break;
957     case lltok::kw_byval:
958     case lltok::kw_inalloca:
959     case lltok::kw_nest:
960     case lltok::kw_noalias:
961     case lltok::kw_nocapture:
962     case lltok::kw_returned:
963     case lltok::kw_sret:
964       HaveError |=
965         Error(Lex.getLoc(),
966               "invalid use of parameter-only attribute on a function");
967       break;
968     }
969
970     Lex.Lex();
971   }
972 }
973
974 //===----------------------------------------------------------------------===//
975 // GlobalValue Reference/Resolution Routines.
976 //===----------------------------------------------------------------------===//
977
978 /// GetGlobalVal - Get a value with the specified name or ID, creating a
979 /// forward reference record if needed.  This can return null if the value
980 /// exists but does not have the right type.
981 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
982                                     LocTy Loc) {
983   PointerType *PTy = dyn_cast<PointerType>(Ty);
984   if (!PTy) {
985     Error(Loc, "global variable reference must have pointer type");
986     return nullptr;
987   }
988
989   // Look this name up in the normal function symbol table.
990   GlobalValue *Val =
991     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
992
993   // If this is a forward reference for the value, see if we already created a
994   // forward ref record.
995   if (!Val) {
996     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
997       I = ForwardRefVals.find(Name);
998     if (I != ForwardRefVals.end())
999       Val = I->second.first;
1000   }
1001
1002   // If we have the value in the symbol table or fwd-ref table, return it.
1003   if (Val) {
1004     if (Val->getType() == Ty) return Val;
1005     Error(Loc, "'@" + Name + "' defined with type '" +
1006           getTypeString(Val->getType()) + "'");
1007     return nullptr;
1008   }
1009
1010   // Otherwise, create a new forward reference for this value and remember it.
1011   GlobalValue *FwdVal;
1012   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1013     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1014   else
1015     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1016                                 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1017                                 nullptr, GlobalVariable::NotThreadLocal,
1018                                 PTy->getAddressSpace());
1019
1020   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1021   return FwdVal;
1022 }
1023
1024 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1025   PointerType *PTy = dyn_cast<PointerType>(Ty);
1026   if (!PTy) {
1027     Error(Loc, "global variable reference must have pointer type");
1028     return nullptr;
1029   }
1030
1031   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1032
1033   // If this is a forward reference for the value, see if we already created a
1034   // forward ref record.
1035   if (!Val) {
1036     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1037       I = ForwardRefValIDs.find(ID);
1038     if (I != ForwardRefValIDs.end())
1039       Val = I->second.first;
1040   }
1041
1042   // If we have the value in the symbol table or fwd-ref table, return it.
1043   if (Val) {
1044     if (Val->getType() == Ty) return Val;
1045     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1046           getTypeString(Val->getType()) + "'");
1047     return nullptr;
1048   }
1049
1050   // Otherwise, create a new forward reference for this value and remember it.
1051   GlobalValue *FwdVal;
1052   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1053     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1054   else
1055     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1056                                 GlobalValue::ExternalWeakLinkage, nullptr, "");
1057
1058   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1059   return FwdVal;
1060 }
1061
1062
1063 //===----------------------------------------------------------------------===//
1064 // Helper Routines.
1065 //===----------------------------------------------------------------------===//
1066
1067 /// ParseToken - If the current token has the specified kind, eat it and return
1068 /// success.  Otherwise, emit the specified error and return failure.
1069 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1070   if (Lex.getKind() != T)
1071     return TokError(ErrMsg);
1072   Lex.Lex();
1073   return false;
1074 }
1075
1076 /// ParseStringConstant
1077 ///   ::= StringConstant
1078 bool LLParser::ParseStringConstant(std::string &Result) {
1079   if (Lex.getKind() != lltok::StringConstant)
1080     return TokError("expected string constant");
1081   Result = Lex.getStrVal();
1082   Lex.Lex();
1083   return false;
1084 }
1085
1086 /// ParseUInt32
1087 ///   ::= uint32
1088 bool LLParser::ParseUInt32(unsigned &Val) {
1089   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1090     return TokError("expected integer");
1091   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1092   if (Val64 != unsigned(Val64))
1093     return TokError("expected 32-bit integer (too large)");
1094   Val = Val64;
1095   Lex.Lex();
1096   return false;
1097 }
1098
1099 /// ParseTLSModel
1100 ///   := 'localdynamic'
1101 ///   := 'initialexec'
1102 ///   := 'localexec'
1103 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1104   switch (Lex.getKind()) {
1105     default:
1106       return TokError("expected localdynamic, initialexec or localexec");
1107     case lltok::kw_localdynamic:
1108       TLM = GlobalVariable::LocalDynamicTLSModel;
1109       break;
1110     case lltok::kw_initialexec:
1111       TLM = GlobalVariable::InitialExecTLSModel;
1112       break;
1113     case lltok::kw_localexec:
1114       TLM = GlobalVariable::LocalExecTLSModel;
1115       break;
1116   }
1117
1118   Lex.Lex();
1119   return false;
1120 }
1121
1122 /// ParseOptionalThreadLocal
1123 ///   := /*empty*/
1124 ///   := 'thread_local'
1125 ///   := 'thread_local' '(' tlsmodel ')'
1126 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1127   TLM = GlobalVariable::NotThreadLocal;
1128   if (!EatIfPresent(lltok::kw_thread_local))
1129     return false;
1130
1131   TLM = GlobalVariable::GeneralDynamicTLSModel;
1132   if (Lex.getKind() == lltok::lparen) {
1133     Lex.Lex();
1134     return ParseTLSModel(TLM) ||
1135       ParseToken(lltok::rparen, "expected ')' after thread local model");
1136   }
1137   return false;
1138 }
1139
1140 /// ParseOptionalAddrSpace
1141 ///   := /*empty*/
1142 ///   := 'addrspace' '(' uint32 ')'
1143 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1144   AddrSpace = 0;
1145   if (!EatIfPresent(lltok::kw_addrspace))
1146     return false;
1147   return ParseToken(lltok::lparen, "expected '(' in address space") ||
1148          ParseUInt32(AddrSpace) ||
1149          ParseToken(lltok::rparen, "expected ')' in address space");
1150 }
1151
1152 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1153 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1154   bool HaveError = false;
1155
1156   B.clear();
1157
1158   while (1) {
1159     lltok::Kind Token = Lex.getKind();
1160     switch (Token) {
1161     default:  // End of attributes.
1162       return HaveError;
1163     case lltok::kw_align: {
1164       unsigned Alignment;
1165       if (ParseOptionalAlignment(Alignment))
1166         return true;
1167       B.addAlignmentAttr(Alignment);
1168       continue;
1169     }
1170     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1171     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
1172     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1173     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1174     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1175     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1176     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1177     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1178     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1179     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1180     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1181     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1182
1183     case lltok::kw_alignstack:
1184     case lltok::kw_alwaysinline:
1185     case lltok::kw_builtin:
1186     case lltok::kw_inlinehint:
1187     case lltok::kw_minsize:
1188     case lltok::kw_naked:
1189     case lltok::kw_nobuiltin:
1190     case lltok::kw_noduplicate:
1191     case lltok::kw_noimplicitfloat:
1192     case lltok::kw_noinline:
1193     case lltok::kw_nonlazybind:
1194     case lltok::kw_noredzone:
1195     case lltok::kw_noreturn:
1196     case lltok::kw_nounwind:
1197     case lltok::kw_optnone:
1198     case lltok::kw_optsize:
1199     case lltok::kw_returns_twice:
1200     case lltok::kw_sanitize_address:
1201     case lltok::kw_sanitize_memory:
1202     case lltok::kw_sanitize_thread:
1203     case lltok::kw_ssp:
1204     case lltok::kw_sspreq:
1205     case lltok::kw_sspstrong:
1206     case lltok::kw_uwtable:
1207       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1208       break;
1209     }
1210
1211     Lex.Lex();
1212   }
1213 }
1214
1215 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1216 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1217   bool HaveError = false;
1218
1219   B.clear();
1220
1221   while (1) {
1222     lltok::Kind Token = Lex.getKind();
1223     switch (Token) {
1224     default:  // End of attributes.
1225       return HaveError;
1226     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1227     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1228     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1229     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1230
1231     // Error handling.
1232     case lltok::kw_align:
1233     case lltok::kw_byval:
1234     case lltok::kw_inalloca:
1235     case lltok::kw_nest:
1236     case lltok::kw_nocapture:
1237     case lltok::kw_returned:
1238     case lltok::kw_sret:
1239       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1240       break;
1241
1242     case lltok::kw_alignstack:
1243     case lltok::kw_alwaysinline:
1244     case lltok::kw_builtin:
1245     case lltok::kw_cold:
1246     case lltok::kw_inlinehint:
1247     case lltok::kw_minsize:
1248     case lltok::kw_naked:
1249     case lltok::kw_nobuiltin:
1250     case lltok::kw_noduplicate:
1251     case lltok::kw_noimplicitfloat:
1252     case lltok::kw_noinline:
1253     case lltok::kw_nonlazybind:
1254     case lltok::kw_noredzone:
1255     case lltok::kw_noreturn:
1256     case lltok::kw_nounwind:
1257     case lltok::kw_optnone:
1258     case lltok::kw_optsize:
1259     case lltok::kw_returns_twice:
1260     case lltok::kw_sanitize_address:
1261     case lltok::kw_sanitize_memory:
1262     case lltok::kw_sanitize_thread:
1263     case lltok::kw_ssp:
1264     case lltok::kw_sspreq:
1265     case lltok::kw_sspstrong:
1266     case lltok::kw_uwtable:
1267       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1268       break;
1269
1270     case lltok::kw_readnone:
1271     case lltok::kw_readonly:
1272       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1273     }
1274
1275     Lex.Lex();
1276   }
1277 }
1278
1279 /// ParseOptionalLinkage
1280 ///   ::= /*empty*/
1281 ///   ::= 'private'
1282 ///   ::= 'internal'
1283 ///   ::= 'weak'
1284 ///   ::= 'weak_odr'
1285 ///   ::= 'linkonce'
1286 ///   ::= 'linkonce_odr'
1287 ///   ::= 'available_externally'
1288 ///   ::= 'appending'
1289 ///   ::= 'common'
1290 ///   ::= 'extern_weak'
1291 ///   ::= 'external'
1292 ///
1293 ///   Deprecated Values:
1294 ///     ::= 'linker_private'
1295 ///     ::= 'linker_private_weak'
1296 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1297   HasLinkage = false;
1298   switch (Lex.getKind()) {
1299   default:                       Res=GlobalValue::ExternalLinkage; return false;
1300   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
1301   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
1302   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
1303   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
1304   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
1305   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
1306   case lltok::kw_available_externally:
1307     Res = GlobalValue::AvailableExternallyLinkage;
1308     break;
1309   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
1310   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
1311   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
1312   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1313
1314   case lltok::kw_linker_private:
1315   case lltok::kw_linker_private_weak:
1316     Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1317                 " PrivateLinkage");
1318     Lex.Lex();
1319     // treat linker_private and linker_private_weak as PrivateLinkage
1320     Res = GlobalValue::PrivateLinkage;
1321     return false;
1322   }
1323   Lex.Lex();
1324   HasLinkage = true;
1325   return false;
1326 }
1327
1328 /// ParseOptionalVisibility
1329 ///   ::= /*empty*/
1330 ///   ::= 'default'
1331 ///   ::= 'hidden'
1332 ///   ::= 'protected'
1333 ///
1334 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1335   switch (Lex.getKind()) {
1336   default:                  Res = GlobalValue::DefaultVisibility; return false;
1337   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1338   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1339   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1340   }
1341   Lex.Lex();
1342   return false;
1343 }
1344
1345 /// ParseOptionalDLLStorageClass
1346 ///   ::= /*empty*/
1347 ///   ::= 'dllimport'
1348 ///   ::= 'dllexport'
1349 ///
1350 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1351   switch (Lex.getKind()) {
1352   default:                  Res = GlobalValue::DefaultStorageClass; return false;
1353   case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1354   case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1355   }
1356   Lex.Lex();
1357   return false;
1358 }
1359
1360 /// ParseOptionalCallingConv
1361 ///   ::= /*empty*/
1362 ///   ::= 'ccc'
1363 ///   ::= 'fastcc'
1364 ///   ::= 'kw_intel_ocl_bicc'
1365 ///   ::= 'coldcc'
1366 ///   ::= 'x86_stdcallcc'
1367 ///   ::= 'x86_fastcallcc'
1368 ///   ::= 'x86_thiscallcc'
1369 ///   ::= 'x86_cdeclmethodcc'
1370 ///   ::= 'arm_apcscc'
1371 ///   ::= 'arm_aapcscc'
1372 ///   ::= 'arm_aapcs_vfpcc'
1373 ///   ::= 'msp430_intrcc'
1374 ///   ::= 'ptx_kernel'
1375 ///   ::= 'ptx_device'
1376 ///   ::= 'spir_func'
1377 ///   ::= 'spir_kernel'
1378 ///   ::= 'x86_64_sysvcc'
1379 ///   ::= 'x86_64_win64cc'
1380 ///   ::= 'webkit_jscc'
1381 ///   ::= 'anyregcc'
1382 ///   ::= 'preserve_mostcc'
1383 ///   ::= 'preserve_allcc'
1384 ///   ::= 'cc' UINT
1385 ///
1386 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1387   switch (Lex.getKind()) {
1388   default:                       CC = CallingConv::C; return false;
1389   case lltok::kw_ccc:            CC = CallingConv::C; break;
1390   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1391   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1392   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1393   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1394   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1395   case lltok::kw_x86_cdeclmethodcc:CC = CallingConv::X86_CDeclMethod; break;
1396   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1397   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1398   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1399   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1400   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1401   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1402   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1403   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1404   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1405   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1406   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1407   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
1408   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
1409   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1410   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1411   case lltok::kw_cc: {
1412       unsigned ArbitraryCC;
1413       Lex.Lex();
1414       if (ParseUInt32(ArbitraryCC))
1415         return true;
1416       CC = static_cast<CallingConv::ID>(ArbitraryCC);
1417       return false;
1418     }
1419   }
1420
1421   Lex.Lex();
1422   return false;
1423 }
1424
1425 /// ParseInstructionMetadata
1426 ///   ::= !dbg !42 (',' !dbg !57)*
1427 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1428                                         PerFunctionState *PFS) {
1429   do {
1430     if (Lex.getKind() != lltok::MetadataVar)
1431       return TokError("expected metadata after comma");
1432
1433     std::string Name = Lex.getStrVal();
1434     unsigned MDK = M->getMDKindID(Name);
1435     Lex.Lex();
1436
1437     MDNode *Node;
1438     SMLoc Loc = Lex.getLoc();
1439
1440     if (ParseToken(lltok::exclaim, "expected '!' here"))
1441       return true;
1442
1443     // This code is similar to that of ParseMetadataValue, however it needs to
1444     // have special-case code for a forward reference; see the comments on
1445     // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1446     // at the top level here.
1447     if (Lex.getKind() == lltok::lbrace) {
1448       ValID ID;
1449       if (ParseMetadataListValue(ID, PFS))
1450         return true;
1451       assert(ID.Kind == ValID::t_MDNode);
1452       Inst->setMetadata(MDK, ID.MDNodeVal);
1453     } else {
1454       unsigned NodeID = 0;
1455       if (ParseMDNodeID(Node, NodeID))
1456         return true;
1457       if (Node) {
1458         // If we got the node, add it to the instruction.
1459         Inst->setMetadata(MDK, Node);
1460       } else {
1461         MDRef R = { Loc, MDK, NodeID };
1462         // Otherwise, remember that this should be resolved later.
1463         ForwardRefInstMetadata[Inst].push_back(R);
1464       }
1465     }
1466
1467     if (MDK == LLVMContext::MD_tbaa)
1468       InstsWithTBAATag.push_back(Inst);
1469
1470     // If this is the end of the list, we're done.
1471   } while (EatIfPresent(lltok::comma));
1472   return false;
1473 }
1474
1475 /// ParseOptionalAlignment
1476 ///   ::= /* empty */
1477 ///   ::= 'align' 4
1478 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1479   Alignment = 0;
1480   if (!EatIfPresent(lltok::kw_align))
1481     return false;
1482   LocTy AlignLoc = Lex.getLoc();
1483   if (ParseUInt32(Alignment)) return true;
1484   if (!isPowerOf2_32(Alignment))
1485     return Error(AlignLoc, "alignment is not a power of two");
1486   if (Alignment > Value::MaximumAlignment)
1487     return Error(AlignLoc, "huge alignments are not supported yet");
1488   return false;
1489 }
1490
1491 /// ParseOptionalCommaAlign
1492 ///   ::=
1493 ///   ::= ',' align 4
1494 ///
1495 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1496 /// end.
1497 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1498                                        bool &AteExtraComma) {
1499   AteExtraComma = false;
1500   while (EatIfPresent(lltok::comma)) {
1501     // Metadata at the end is an early exit.
1502     if (Lex.getKind() == lltok::MetadataVar) {
1503       AteExtraComma = true;
1504       return false;
1505     }
1506
1507     if (Lex.getKind() != lltok::kw_align)
1508       return Error(Lex.getLoc(), "expected metadata or 'align'");
1509
1510     if (ParseOptionalAlignment(Alignment)) return true;
1511   }
1512
1513   return false;
1514 }
1515
1516 /// ParseScopeAndOrdering
1517 ///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1518 ///   else: ::=
1519 ///
1520 /// This sets Scope and Ordering to the parsed values.
1521 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1522                                      AtomicOrdering &Ordering) {
1523   if (!isAtomic)
1524     return false;
1525
1526   Scope = CrossThread;
1527   if (EatIfPresent(lltok::kw_singlethread))
1528     Scope = SingleThread;
1529
1530   return ParseOrdering(Ordering);
1531 }
1532
1533 /// ParseOrdering
1534 ///   ::= AtomicOrdering
1535 ///
1536 /// This sets Ordering to the parsed value.
1537 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1538   switch (Lex.getKind()) {
1539   default: return TokError("Expected ordering on atomic instruction");
1540   case lltok::kw_unordered: Ordering = Unordered; break;
1541   case lltok::kw_monotonic: Ordering = Monotonic; break;
1542   case lltok::kw_acquire: Ordering = Acquire; break;
1543   case lltok::kw_release: Ordering = Release; break;
1544   case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1545   case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1546   }
1547   Lex.Lex();
1548   return false;
1549 }
1550
1551 /// ParseOptionalStackAlignment
1552 ///   ::= /* empty */
1553 ///   ::= 'alignstack' '(' 4 ')'
1554 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1555   Alignment = 0;
1556   if (!EatIfPresent(lltok::kw_alignstack))
1557     return false;
1558   LocTy ParenLoc = Lex.getLoc();
1559   if (!EatIfPresent(lltok::lparen))
1560     return Error(ParenLoc, "expected '('");
1561   LocTy AlignLoc = Lex.getLoc();
1562   if (ParseUInt32(Alignment)) return true;
1563   ParenLoc = Lex.getLoc();
1564   if (!EatIfPresent(lltok::rparen))
1565     return Error(ParenLoc, "expected ')'");
1566   if (!isPowerOf2_32(Alignment))
1567     return Error(AlignLoc, "stack alignment is not a power of two");
1568   return false;
1569 }
1570
1571 /// ParseIndexList - This parses the index list for an insert/extractvalue
1572 /// instruction.  This sets AteExtraComma in the case where we eat an extra
1573 /// comma at the end of the line and find that it is followed by metadata.
1574 /// Clients that don't allow metadata can call the version of this function that
1575 /// only takes one argument.
1576 ///
1577 /// ParseIndexList
1578 ///    ::=  (',' uint32)+
1579 ///
1580 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1581                               bool &AteExtraComma) {
1582   AteExtraComma = false;
1583
1584   if (Lex.getKind() != lltok::comma)
1585     return TokError("expected ',' as start of index list");
1586
1587   while (EatIfPresent(lltok::comma)) {
1588     if (Lex.getKind() == lltok::MetadataVar) {
1589       AteExtraComma = true;
1590       return false;
1591     }
1592     unsigned Idx = 0;
1593     if (ParseUInt32(Idx)) return true;
1594     Indices.push_back(Idx);
1595   }
1596
1597   return false;
1598 }
1599
1600 //===----------------------------------------------------------------------===//
1601 // Type Parsing.
1602 //===----------------------------------------------------------------------===//
1603
1604 /// ParseType - Parse a type.
1605 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1606   SMLoc TypeLoc = Lex.getLoc();
1607   switch (Lex.getKind()) {
1608   default:
1609     return TokError("expected type");
1610   case lltok::Type:
1611     // Type ::= 'float' | 'void' (etc)
1612     Result = Lex.getTyVal();
1613     Lex.Lex();
1614     break;
1615   case lltok::lbrace:
1616     // Type ::= StructType
1617     if (ParseAnonStructType(Result, false))
1618       return true;
1619     break;
1620   case lltok::lsquare:
1621     // Type ::= '[' ... ']'
1622     Lex.Lex(); // eat the lsquare.
1623     if (ParseArrayVectorType(Result, false))
1624       return true;
1625     break;
1626   case lltok::less: // Either vector or packed struct.
1627     // Type ::= '<' ... '>'
1628     Lex.Lex();
1629     if (Lex.getKind() == lltok::lbrace) {
1630       if (ParseAnonStructType(Result, true) ||
1631           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1632         return true;
1633     } else if (ParseArrayVectorType(Result, true))
1634       return true;
1635     break;
1636   case lltok::LocalVar: {
1637     // Type ::= %foo
1638     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1639
1640     // If the type hasn't been defined yet, create a forward definition and
1641     // remember where that forward def'n was seen (in case it never is defined).
1642     if (!Entry.first) {
1643       Entry.first = StructType::create(Context, Lex.getStrVal());
1644       Entry.second = Lex.getLoc();
1645     }
1646     Result = Entry.first;
1647     Lex.Lex();
1648     break;
1649   }
1650
1651   case lltok::LocalVarID: {
1652     // Type ::= %4
1653     if (Lex.getUIntVal() >= NumberedTypes.size())
1654       NumberedTypes.resize(Lex.getUIntVal()+1);
1655     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1656
1657     // If the type hasn't been defined yet, create a forward definition and
1658     // remember where that forward def'n was seen (in case it never is defined).
1659     if (!Entry.first) {
1660       Entry.first = StructType::create(Context);
1661       Entry.second = Lex.getLoc();
1662     }
1663     Result = Entry.first;
1664     Lex.Lex();
1665     break;
1666   }
1667   }
1668
1669   // Parse the type suffixes.
1670   while (1) {
1671     switch (Lex.getKind()) {
1672     // End of type.
1673     default:
1674       if (!AllowVoid && Result->isVoidTy())
1675         return Error(TypeLoc, "void type only allowed for function results");
1676       return false;
1677
1678     // Type ::= Type '*'
1679     case lltok::star:
1680       if (Result->isLabelTy())
1681         return TokError("basic block pointers are invalid");
1682       if (Result->isVoidTy())
1683         return TokError("pointers to void are invalid - use i8* instead");
1684       if (!PointerType::isValidElementType(Result))
1685         return TokError("pointer to this type is invalid");
1686       Result = PointerType::getUnqual(Result);
1687       Lex.Lex();
1688       break;
1689
1690     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1691     case lltok::kw_addrspace: {
1692       if (Result->isLabelTy())
1693         return TokError("basic block pointers are invalid");
1694       if (Result->isVoidTy())
1695         return TokError("pointers to void are invalid; use i8* instead");
1696       if (!PointerType::isValidElementType(Result))
1697         return TokError("pointer to this type is invalid");
1698       unsigned AddrSpace;
1699       if (ParseOptionalAddrSpace(AddrSpace) ||
1700           ParseToken(lltok::star, "expected '*' in address space"))
1701         return true;
1702
1703       Result = PointerType::get(Result, AddrSpace);
1704       break;
1705     }
1706
1707     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1708     case lltok::lparen:
1709       if (ParseFunctionType(Result))
1710         return true;
1711       break;
1712     }
1713   }
1714 }
1715
1716 /// ParseParameterList
1717 ///    ::= '(' ')'
1718 ///    ::= '(' Arg (',' Arg)* ')'
1719 ///  Arg
1720 ///    ::= Type OptionalAttributes Value OptionalAttributes
1721 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1722                                   PerFunctionState &PFS) {
1723   if (ParseToken(lltok::lparen, "expected '(' in call"))
1724     return true;
1725
1726   unsigned AttrIndex = 1;
1727   while (Lex.getKind() != lltok::rparen) {
1728     // If this isn't the first argument, we need a comma.
1729     if (!ArgList.empty() &&
1730         ParseToken(lltok::comma, "expected ',' in argument list"))
1731       return true;
1732
1733     // Parse the argument.
1734     LocTy ArgLoc;
1735     Type *ArgTy = nullptr;
1736     AttrBuilder ArgAttrs;
1737     Value *V;
1738     if (ParseType(ArgTy, ArgLoc))
1739       return true;
1740
1741     // Otherwise, handle normal operands.
1742     if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1743       return true;
1744     ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1745                                                              AttrIndex++,
1746                                                              ArgAttrs)));
1747   }
1748
1749   Lex.Lex();  // Lex the ')'.
1750   return false;
1751 }
1752
1753
1754
1755 /// ParseArgumentList - Parse the argument list for a function type or function
1756 /// prototype.
1757 ///   ::= '(' ArgTypeListI ')'
1758 /// ArgTypeListI
1759 ///   ::= /*empty*/
1760 ///   ::= '...'
1761 ///   ::= ArgTypeList ',' '...'
1762 ///   ::= ArgType (',' ArgType)*
1763 ///
1764 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1765                                  bool &isVarArg){
1766   isVarArg = false;
1767   assert(Lex.getKind() == lltok::lparen);
1768   Lex.Lex(); // eat the (.
1769
1770   if (Lex.getKind() == lltok::rparen) {
1771     // empty
1772   } else if (Lex.getKind() == lltok::dotdotdot) {
1773     isVarArg = true;
1774     Lex.Lex();
1775   } else {
1776     LocTy TypeLoc = Lex.getLoc();
1777     Type *ArgTy = nullptr;
1778     AttrBuilder Attrs;
1779     std::string Name;
1780
1781     if (ParseType(ArgTy) ||
1782         ParseOptionalParamAttrs(Attrs)) return true;
1783
1784     if (ArgTy->isVoidTy())
1785       return Error(TypeLoc, "argument can not have void type");
1786
1787     if (Lex.getKind() == lltok::LocalVar) {
1788       Name = Lex.getStrVal();
1789       Lex.Lex();
1790     }
1791
1792     if (!FunctionType::isValidArgumentType(ArgTy))
1793       return Error(TypeLoc, "invalid type for function argument");
1794
1795     unsigned AttrIndex = 1;
1796     ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1797                               AttributeSet::get(ArgTy->getContext(),
1798                                                 AttrIndex++, Attrs), Name));
1799
1800     while (EatIfPresent(lltok::comma)) {
1801       // Handle ... at end of arg list.
1802       if (EatIfPresent(lltok::dotdotdot)) {
1803         isVarArg = true;
1804         break;
1805       }
1806
1807       // Otherwise must be an argument type.
1808       TypeLoc = Lex.getLoc();
1809       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1810
1811       if (ArgTy->isVoidTy())
1812         return Error(TypeLoc, "argument can not have void type");
1813
1814       if (Lex.getKind() == lltok::LocalVar) {
1815         Name = Lex.getStrVal();
1816         Lex.Lex();
1817       } else {
1818         Name = "";
1819       }
1820
1821       if (!ArgTy->isFirstClassType())
1822         return Error(TypeLoc, "invalid type for function argument");
1823
1824       ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1825                                 AttributeSet::get(ArgTy->getContext(),
1826                                                   AttrIndex++, Attrs),
1827                                 Name));
1828     }
1829   }
1830
1831   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1832 }
1833
1834 /// ParseFunctionType
1835 ///  ::= Type ArgumentList OptionalAttrs
1836 bool LLParser::ParseFunctionType(Type *&Result) {
1837   assert(Lex.getKind() == lltok::lparen);
1838
1839   if (!FunctionType::isValidReturnType(Result))
1840     return TokError("invalid function return type");
1841
1842   SmallVector<ArgInfo, 8> ArgList;
1843   bool isVarArg;
1844   if (ParseArgumentList(ArgList, isVarArg))
1845     return true;
1846
1847   // Reject names on the arguments lists.
1848   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1849     if (!ArgList[i].Name.empty())
1850       return Error(ArgList[i].Loc, "argument name invalid in function type");
1851     if (ArgList[i].Attrs.hasAttributes(i + 1))
1852       return Error(ArgList[i].Loc,
1853                    "argument attributes invalid in function type");
1854   }
1855
1856   SmallVector<Type*, 16> ArgListTy;
1857   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1858     ArgListTy.push_back(ArgList[i].Ty);
1859
1860   Result = FunctionType::get(Result, ArgListTy, isVarArg);
1861   return false;
1862 }
1863
1864 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1865 /// other structs.
1866 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1867   SmallVector<Type*, 8> Elts;
1868   if (ParseStructBody(Elts)) return true;
1869
1870   Result = StructType::get(Context, Elts, Packed);
1871   return false;
1872 }
1873
1874 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1875 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1876                                      std::pair<Type*, LocTy> &Entry,
1877                                      Type *&ResultTy) {
1878   // If the type was already defined, diagnose the redefinition.
1879   if (Entry.first && !Entry.second.isValid())
1880     return Error(TypeLoc, "redefinition of type");
1881
1882   // If we have opaque, just return without filling in the definition for the
1883   // struct.  This counts as a definition as far as the .ll file goes.
1884   if (EatIfPresent(lltok::kw_opaque)) {
1885     // This type is being defined, so clear the location to indicate this.
1886     Entry.second = SMLoc();
1887
1888     // If this type number has never been uttered, create it.
1889     if (!Entry.first)
1890       Entry.first = StructType::create(Context, Name);
1891     ResultTy = Entry.first;
1892     return false;
1893   }
1894
1895   // If the type starts with '<', then it is either a packed struct or a vector.
1896   bool isPacked = EatIfPresent(lltok::less);
1897
1898   // If we don't have a struct, then we have a random type alias, which we
1899   // accept for compatibility with old files.  These types are not allowed to be
1900   // forward referenced and not allowed to be recursive.
1901   if (Lex.getKind() != lltok::lbrace) {
1902     if (Entry.first)
1903       return Error(TypeLoc, "forward references to non-struct type");
1904
1905     ResultTy = nullptr;
1906     if (isPacked)
1907       return ParseArrayVectorType(ResultTy, true);
1908     return ParseType(ResultTy);
1909   }
1910
1911   // This type is being defined, so clear the location to indicate this.
1912   Entry.second = SMLoc();
1913
1914   // If this type number has never been uttered, create it.
1915   if (!Entry.first)
1916     Entry.first = StructType::create(Context, Name);
1917
1918   StructType *STy = cast<StructType>(Entry.first);
1919
1920   SmallVector<Type*, 8> Body;
1921   if (ParseStructBody(Body) ||
1922       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1923     return true;
1924
1925   STy->setBody(Body, isPacked);
1926   ResultTy = STy;
1927   return false;
1928 }
1929
1930
1931 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1932 ///   StructType
1933 ///     ::= '{' '}'
1934 ///     ::= '{' Type (',' Type)* '}'
1935 ///     ::= '<' '{' '}' '>'
1936 ///     ::= '<' '{' Type (',' Type)* '}' '>'
1937 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1938   assert(Lex.getKind() == lltok::lbrace);
1939   Lex.Lex(); // Consume the '{'
1940
1941   // Handle the empty struct.
1942   if (EatIfPresent(lltok::rbrace))
1943     return false;
1944
1945   LocTy EltTyLoc = Lex.getLoc();
1946   Type *Ty = nullptr;
1947   if (ParseType(Ty)) return true;
1948   Body.push_back(Ty);
1949
1950   if (!StructType::isValidElementType(Ty))
1951     return Error(EltTyLoc, "invalid element type for struct");
1952
1953   while (EatIfPresent(lltok::comma)) {
1954     EltTyLoc = Lex.getLoc();
1955     if (ParseType(Ty)) return true;
1956
1957     if (!StructType::isValidElementType(Ty))
1958       return Error(EltTyLoc, "invalid element type for struct");
1959
1960     Body.push_back(Ty);
1961   }
1962
1963   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1964 }
1965
1966 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1967 /// token has already been consumed.
1968 ///   Type
1969 ///     ::= '[' APSINTVAL 'x' Types ']'
1970 ///     ::= '<' APSINTVAL 'x' Types '>'
1971 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1972   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1973       Lex.getAPSIntVal().getBitWidth() > 64)
1974     return TokError("expected number in address space");
1975
1976   LocTy SizeLoc = Lex.getLoc();
1977   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1978   Lex.Lex();
1979
1980   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1981       return true;
1982
1983   LocTy TypeLoc = Lex.getLoc();
1984   Type *EltTy = nullptr;
1985   if (ParseType(EltTy)) return true;
1986
1987   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1988                  "expected end of sequential type"))
1989     return true;
1990
1991   if (isVector) {
1992     if (Size == 0)
1993       return Error(SizeLoc, "zero element vector is illegal");
1994     if ((unsigned)Size != Size)
1995       return Error(SizeLoc, "size too large for vector");
1996     if (!VectorType::isValidElementType(EltTy))
1997       return Error(TypeLoc, "invalid vector element type");
1998     Result = VectorType::get(EltTy, unsigned(Size));
1999   } else {
2000     if (!ArrayType::isValidElementType(EltTy))
2001       return Error(TypeLoc, "invalid array element type");
2002     Result = ArrayType::get(EltTy, Size);
2003   }
2004   return false;
2005 }
2006
2007 //===----------------------------------------------------------------------===//
2008 // Function Semantic Analysis.
2009 //===----------------------------------------------------------------------===//
2010
2011 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2012                                              int functionNumber)
2013   : P(p), F(f), FunctionNumber(functionNumber) {
2014
2015   // Insert unnamed arguments into the NumberedVals list.
2016   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2017        AI != E; ++AI)
2018     if (!AI->hasName())
2019       NumberedVals.push_back(AI);
2020 }
2021
2022 LLParser::PerFunctionState::~PerFunctionState() {
2023   // If there were any forward referenced non-basicblock values, delete them.
2024   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2025        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2026     if (!isa<BasicBlock>(I->second.first)) {
2027       I->second.first->replaceAllUsesWith(
2028                            UndefValue::get(I->second.first->getType()));
2029       delete I->second.first;
2030       I->second.first = nullptr;
2031     }
2032
2033   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2034        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2035     if (!isa<BasicBlock>(I->second.first)) {
2036       I->second.first->replaceAllUsesWith(
2037                            UndefValue::get(I->second.first->getType()));
2038       delete I->second.first;
2039       I->second.first = nullptr;
2040     }
2041 }
2042
2043 bool LLParser::PerFunctionState::FinishFunction() {
2044   // Check to see if someone took the address of labels in this block.
2045   if (!P.ForwardRefBlockAddresses.empty()) {
2046     ValID FunctionID;
2047     if (!F.getName().empty()) {
2048       FunctionID.Kind = ValID::t_GlobalName;
2049       FunctionID.StrVal = F.getName();
2050     } else {
2051       FunctionID.Kind = ValID::t_GlobalID;
2052       FunctionID.UIntVal = FunctionNumber;
2053     }
2054
2055     std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2056       FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2057     if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2058       // Resolve all these references.
2059       if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2060         return true;
2061
2062       P.ForwardRefBlockAddresses.erase(FRBAI);
2063     }
2064   }
2065
2066   if (!ForwardRefVals.empty())
2067     return P.Error(ForwardRefVals.begin()->second.second,
2068                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2069                    "'");
2070   if (!ForwardRefValIDs.empty())
2071     return P.Error(ForwardRefValIDs.begin()->second.second,
2072                    "use of undefined value '%" +
2073                    Twine(ForwardRefValIDs.begin()->first) + "'");
2074   return false;
2075 }
2076
2077
2078 /// GetVal - Get a value with the specified name or ID, creating a
2079 /// forward reference record if needed.  This can return null if the value
2080 /// exists but does not have the right type.
2081 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2082                                           Type *Ty, LocTy Loc) {
2083   // Look this name up in the normal function symbol table.
2084   Value *Val = F.getValueSymbolTable().lookup(Name);
2085
2086   // If this is a forward reference for the value, see if we already created a
2087   // forward ref record.
2088   if (!Val) {
2089     std::map<std::string, std::pair<Value*, LocTy> >::iterator
2090       I = ForwardRefVals.find(Name);
2091     if (I != ForwardRefVals.end())
2092       Val = I->second.first;
2093   }
2094
2095   // If we have the value in the symbol table or fwd-ref table, return it.
2096   if (Val) {
2097     if (Val->getType() == Ty) return Val;
2098     if (Ty->isLabelTy())
2099       P.Error(Loc, "'%" + Name + "' is not a basic block");
2100     else
2101       P.Error(Loc, "'%" + Name + "' defined with type '" +
2102               getTypeString(Val->getType()) + "'");
2103     return nullptr;
2104   }
2105
2106   // Don't make placeholders with invalid type.
2107   if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2108     P.Error(Loc, "invalid use of a non-first-class type");
2109     return nullptr;
2110   }
2111
2112   // Otherwise, create a new forward reference for this value and remember it.
2113   Value *FwdVal;
2114   if (Ty->isLabelTy())
2115     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2116   else
2117     FwdVal = new Argument(Ty, Name);
2118
2119   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2120   return FwdVal;
2121 }
2122
2123 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2124                                           LocTy Loc) {
2125   // Look this name up in the normal function symbol table.
2126   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2127
2128   // If this is a forward reference for the value, see if we already created a
2129   // forward ref record.
2130   if (!Val) {
2131     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2132       I = ForwardRefValIDs.find(ID);
2133     if (I != ForwardRefValIDs.end())
2134       Val = I->second.first;
2135   }
2136
2137   // If we have the value in the symbol table or fwd-ref table, return it.
2138   if (Val) {
2139     if (Val->getType() == Ty) return Val;
2140     if (Ty->isLabelTy())
2141       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2142     else
2143       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2144               getTypeString(Val->getType()) + "'");
2145     return nullptr;
2146   }
2147
2148   if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2149     P.Error(Loc, "invalid use of a non-first-class type");
2150     return nullptr;
2151   }
2152
2153   // Otherwise, create a new forward reference for this value and remember it.
2154   Value *FwdVal;
2155   if (Ty->isLabelTy())
2156     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2157   else
2158     FwdVal = new Argument(Ty);
2159
2160   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2161   return FwdVal;
2162 }
2163
2164 /// SetInstName - After an instruction is parsed and inserted into its
2165 /// basic block, this installs its name.
2166 bool LLParser::PerFunctionState::SetInstName(int NameID,
2167                                              const std::string &NameStr,
2168                                              LocTy NameLoc, Instruction *Inst) {
2169   // If this instruction has void type, it cannot have a name or ID specified.
2170   if (Inst->getType()->isVoidTy()) {
2171     if (NameID != -1 || !NameStr.empty())
2172       return P.Error(NameLoc, "instructions returning void cannot have a name");
2173     return false;
2174   }
2175
2176   // If this was a numbered instruction, verify that the instruction is the
2177   // expected value and resolve any forward references.
2178   if (NameStr.empty()) {
2179     // If neither a name nor an ID was specified, just use the next ID.
2180     if (NameID == -1)
2181       NameID = NumberedVals.size();
2182
2183     if (unsigned(NameID) != NumberedVals.size())
2184       return P.Error(NameLoc, "instruction expected to be numbered '%" +
2185                      Twine(NumberedVals.size()) + "'");
2186
2187     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2188       ForwardRefValIDs.find(NameID);
2189     if (FI != ForwardRefValIDs.end()) {
2190       if (FI->second.first->getType() != Inst->getType())
2191         return P.Error(NameLoc, "instruction forward referenced with type '" +
2192                        getTypeString(FI->second.first->getType()) + "'");
2193       FI->second.first->replaceAllUsesWith(Inst);
2194       delete FI->second.first;
2195       ForwardRefValIDs.erase(FI);
2196     }
2197
2198     NumberedVals.push_back(Inst);
2199     return false;
2200   }
2201
2202   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2203   std::map<std::string, std::pair<Value*, LocTy> >::iterator
2204     FI = ForwardRefVals.find(NameStr);
2205   if (FI != ForwardRefVals.end()) {
2206     if (FI->second.first->getType() != Inst->getType())
2207       return P.Error(NameLoc, "instruction forward referenced with type '" +
2208                      getTypeString(FI->second.first->getType()) + "'");
2209     FI->second.first->replaceAllUsesWith(Inst);
2210     delete FI->second.first;
2211     ForwardRefVals.erase(FI);
2212   }
2213
2214   // Set the name on the instruction.
2215   Inst->setName(NameStr);
2216
2217   if (Inst->getName() != NameStr)
2218     return P.Error(NameLoc, "multiple definition of local value named '" +
2219                    NameStr + "'");
2220   return false;
2221 }
2222
2223 /// GetBB - Get a basic block with the specified name or ID, creating a
2224 /// forward reference record if needed.
2225 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2226                                               LocTy Loc) {
2227   return cast_or_null<BasicBlock>(GetVal(Name,
2228                                         Type::getLabelTy(F.getContext()), Loc));
2229 }
2230
2231 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2232   return cast_or_null<BasicBlock>(GetVal(ID,
2233                                         Type::getLabelTy(F.getContext()), Loc));
2234 }
2235
2236 /// DefineBB - Define the specified basic block, which is either named or
2237 /// unnamed.  If there is an error, this returns null otherwise it returns
2238 /// the block being defined.
2239 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2240                                                  LocTy Loc) {
2241   BasicBlock *BB;
2242   if (Name.empty())
2243     BB = GetBB(NumberedVals.size(), Loc);
2244   else
2245     BB = GetBB(Name, Loc);
2246   if (!BB) return nullptr; // Already diagnosed error.
2247
2248   // Move the block to the end of the function.  Forward ref'd blocks are
2249   // inserted wherever they happen to be referenced.
2250   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2251
2252   // Remove the block from forward ref sets.
2253   if (Name.empty()) {
2254     ForwardRefValIDs.erase(NumberedVals.size());
2255     NumberedVals.push_back(BB);
2256   } else {
2257     // BB forward references are already in the function symbol table.
2258     ForwardRefVals.erase(Name);
2259   }
2260
2261   return BB;
2262 }
2263
2264 //===----------------------------------------------------------------------===//
2265 // Constants.
2266 //===----------------------------------------------------------------------===//
2267
2268 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2269 /// type implied.  For example, if we parse "4" we don't know what integer type
2270 /// it has.  The value will later be combined with its type and checked for
2271 /// sanity.  PFS is used to convert function-local operands of metadata (since
2272 /// metadata operands are not just parsed here but also converted to values).
2273 /// PFS can be null when we are not parsing metadata values inside a function.
2274 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2275   ID.Loc = Lex.getLoc();
2276   switch (Lex.getKind()) {
2277   default: return TokError("expected value token");
2278   case lltok::GlobalID:  // @42
2279     ID.UIntVal = Lex.getUIntVal();
2280     ID.Kind = ValID::t_GlobalID;
2281     break;
2282   case lltok::GlobalVar:  // @foo
2283     ID.StrVal = Lex.getStrVal();
2284     ID.Kind = ValID::t_GlobalName;
2285     break;
2286   case lltok::LocalVarID:  // %42
2287     ID.UIntVal = Lex.getUIntVal();
2288     ID.Kind = ValID::t_LocalID;
2289     break;
2290   case lltok::LocalVar:  // %foo
2291     ID.StrVal = Lex.getStrVal();
2292     ID.Kind = ValID::t_LocalName;
2293     break;
2294   case lltok::exclaim:   // !42, !{...}, or !"foo"
2295     return ParseMetadataValue(ID, PFS);
2296   case lltok::APSInt:
2297     ID.APSIntVal = Lex.getAPSIntVal();
2298     ID.Kind = ValID::t_APSInt;
2299     break;
2300   case lltok::APFloat:
2301     ID.APFloatVal = Lex.getAPFloatVal();
2302     ID.Kind = ValID::t_APFloat;
2303     break;
2304   case lltok::kw_true:
2305     ID.ConstantVal = ConstantInt::getTrue(Context);
2306     ID.Kind = ValID::t_Constant;
2307     break;
2308   case lltok::kw_false:
2309     ID.ConstantVal = ConstantInt::getFalse(Context);
2310     ID.Kind = ValID::t_Constant;
2311     break;
2312   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2313   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2314   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2315
2316   case lltok::lbrace: {
2317     // ValID ::= '{' ConstVector '}'
2318     Lex.Lex();
2319     SmallVector<Constant*, 16> Elts;
2320     if (ParseGlobalValueVector(Elts) ||
2321         ParseToken(lltok::rbrace, "expected end of struct constant"))
2322       return true;
2323
2324     ID.ConstantStructElts = new Constant*[Elts.size()];
2325     ID.UIntVal = Elts.size();
2326     memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2327     ID.Kind = ValID::t_ConstantStruct;
2328     return false;
2329   }
2330   case lltok::less: {
2331     // ValID ::= '<' ConstVector '>'         --> Vector.
2332     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2333     Lex.Lex();
2334     bool isPackedStruct = EatIfPresent(lltok::lbrace);
2335
2336     SmallVector<Constant*, 16> Elts;
2337     LocTy FirstEltLoc = Lex.getLoc();
2338     if (ParseGlobalValueVector(Elts) ||
2339         (isPackedStruct &&
2340          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2341         ParseToken(lltok::greater, "expected end of constant"))
2342       return true;
2343
2344     if (isPackedStruct) {
2345       ID.ConstantStructElts = new Constant*[Elts.size()];
2346       memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2347       ID.UIntVal = Elts.size();
2348       ID.Kind = ValID::t_PackedConstantStruct;
2349       return false;
2350     }
2351
2352     if (Elts.empty())
2353       return Error(ID.Loc, "constant vector must not be empty");
2354
2355     if (!Elts[0]->getType()->isIntegerTy() &&
2356         !Elts[0]->getType()->isFloatingPointTy() &&
2357         !Elts[0]->getType()->isPointerTy())
2358       return Error(FirstEltLoc,
2359             "vector elements must have integer, pointer or floating point type");
2360
2361     // Verify that all the vector elements have the same type.
2362     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2363       if (Elts[i]->getType() != Elts[0]->getType())
2364         return Error(FirstEltLoc,
2365                      "vector element #" + Twine(i) +
2366                     " is not of type '" + getTypeString(Elts[0]->getType()));
2367
2368     ID.ConstantVal = ConstantVector::get(Elts);
2369     ID.Kind = ValID::t_Constant;
2370     return false;
2371   }
2372   case lltok::lsquare: {   // Array Constant
2373     Lex.Lex();
2374     SmallVector<Constant*, 16> Elts;
2375     LocTy FirstEltLoc = Lex.getLoc();
2376     if (ParseGlobalValueVector(Elts) ||
2377         ParseToken(lltok::rsquare, "expected end of array constant"))
2378       return true;
2379
2380     // Handle empty element.
2381     if (Elts.empty()) {
2382       // Use undef instead of an array because it's inconvenient to determine
2383       // the element type at this point, there being no elements to examine.
2384       ID.Kind = ValID::t_EmptyArray;
2385       return false;
2386     }
2387
2388     if (!Elts[0]->getType()->isFirstClassType())
2389       return Error(FirstEltLoc, "invalid array element type: " +
2390                    getTypeString(Elts[0]->getType()));
2391
2392     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2393
2394     // Verify all elements are correct type!
2395     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2396       if (Elts[i]->getType() != Elts[0]->getType())
2397         return Error(FirstEltLoc,
2398                      "array element #" + Twine(i) +
2399                      " is not of type '" + getTypeString(Elts[0]->getType()));
2400     }
2401
2402     ID.ConstantVal = ConstantArray::get(ATy, Elts);
2403     ID.Kind = ValID::t_Constant;
2404     return false;
2405   }
2406   case lltok::kw_c:  // c "foo"
2407     Lex.Lex();
2408     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2409                                                   false);
2410     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2411     ID.Kind = ValID::t_Constant;
2412     return false;
2413
2414   case lltok::kw_asm: {
2415     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2416     //             STRINGCONSTANT
2417     bool HasSideEffect, AlignStack, AsmDialect;
2418     Lex.Lex();
2419     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2420         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2421         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2422         ParseStringConstant(ID.StrVal) ||
2423         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2424         ParseToken(lltok::StringConstant, "expected constraint string"))
2425       return true;
2426     ID.StrVal2 = Lex.getStrVal();
2427     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2428       (unsigned(AsmDialect)<<2);
2429     ID.Kind = ValID::t_InlineAsm;
2430     return false;
2431   }
2432
2433   case lltok::kw_blockaddress: {
2434     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2435     Lex.Lex();
2436
2437     ValID Fn, Label;
2438
2439     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2440         ParseValID(Fn) ||
2441         ParseToken(lltok::comma, "expected comma in block address expression")||
2442         ParseValID(Label) ||
2443         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2444       return true;
2445
2446     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2447       return Error(Fn.Loc, "expected function name in blockaddress");
2448     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2449       return Error(Label.Loc, "expected basic block name in blockaddress");
2450
2451     // Make a global variable as a placeholder for this reference.
2452     GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2453                                            false, GlobalValue::InternalLinkage,
2454                                                 nullptr, "");
2455     ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2456     ID.ConstantVal = FwdRef;
2457     ID.Kind = ValID::t_Constant;
2458     return false;
2459   }
2460
2461   case lltok::kw_trunc:
2462   case lltok::kw_zext:
2463   case lltok::kw_sext:
2464   case lltok::kw_fptrunc:
2465   case lltok::kw_fpext:
2466   case lltok::kw_bitcast:
2467   case lltok::kw_addrspacecast:
2468   case lltok::kw_uitofp:
2469   case lltok::kw_sitofp:
2470   case lltok::kw_fptoui:
2471   case lltok::kw_fptosi:
2472   case lltok::kw_inttoptr:
2473   case lltok::kw_ptrtoint: {
2474     unsigned Opc = Lex.getUIntVal();
2475     Type *DestTy = nullptr;
2476     Constant *SrcVal;
2477     Lex.Lex();
2478     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2479         ParseGlobalTypeAndValue(SrcVal) ||
2480         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2481         ParseType(DestTy) ||
2482         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2483       return true;
2484     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2485       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2486                    getTypeString(SrcVal->getType()) + "' to '" +
2487                    getTypeString(DestTy) + "'");
2488     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2489                                                  SrcVal, DestTy);
2490     ID.Kind = ValID::t_Constant;
2491     return false;
2492   }
2493   case lltok::kw_extractvalue: {
2494     Lex.Lex();
2495     Constant *Val;
2496     SmallVector<unsigned, 4> Indices;
2497     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2498         ParseGlobalTypeAndValue(Val) ||
2499         ParseIndexList(Indices) ||
2500         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2501       return true;
2502
2503     if (!Val->getType()->isAggregateType())
2504       return Error(ID.Loc, "extractvalue operand must be aggregate type");
2505     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2506       return Error(ID.Loc, "invalid indices for extractvalue");
2507     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2508     ID.Kind = ValID::t_Constant;
2509     return false;
2510   }
2511   case lltok::kw_insertvalue: {
2512     Lex.Lex();
2513     Constant *Val0, *Val1;
2514     SmallVector<unsigned, 4> Indices;
2515     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2516         ParseGlobalTypeAndValue(Val0) ||
2517         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2518         ParseGlobalTypeAndValue(Val1) ||
2519         ParseIndexList(Indices) ||
2520         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2521       return true;
2522     if (!Val0->getType()->isAggregateType())
2523       return Error(ID.Loc, "insertvalue operand must be aggregate type");
2524     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2525       return Error(ID.Loc, "invalid indices for insertvalue");
2526     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2527     ID.Kind = ValID::t_Constant;
2528     return false;
2529   }
2530   case lltok::kw_icmp:
2531   case lltok::kw_fcmp: {
2532     unsigned PredVal, Opc = Lex.getUIntVal();
2533     Constant *Val0, *Val1;
2534     Lex.Lex();
2535     if (ParseCmpPredicate(PredVal, Opc) ||
2536         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2537         ParseGlobalTypeAndValue(Val0) ||
2538         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2539         ParseGlobalTypeAndValue(Val1) ||
2540         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2541       return true;
2542
2543     if (Val0->getType() != Val1->getType())
2544       return Error(ID.Loc, "compare operands must have the same type");
2545
2546     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2547
2548     if (Opc == Instruction::FCmp) {
2549       if (!Val0->getType()->isFPOrFPVectorTy())
2550         return Error(ID.Loc, "fcmp requires floating point operands");
2551       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2552     } else {
2553       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2554       if (!Val0->getType()->isIntOrIntVectorTy() &&
2555           !Val0->getType()->getScalarType()->isPointerTy())
2556         return Error(ID.Loc, "icmp requires pointer or integer operands");
2557       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2558     }
2559     ID.Kind = ValID::t_Constant;
2560     return false;
2561   }
2562
2563   // Binary Operators.
2564   case lltok::kw_add:
2565   case lltok::kw_fadd:
2566   case lltok::kw_sub:
2567   case lltok::kw_fsub:
2568   case lltok::kw_mul:
2569   case lltok::kw_fmul:
2570   case lltok::kw_udiv:
2571   case lltok::kw_sdiv:
2572   case lltok::kw_fdiv:
2573   case lltok::kw_urem:
2574   case lltok::kw_srem:
2575   case lltok::kw_frem:
2576   case lltok::kw_shl:
2577   case lltok::kw_lshr:
2578   case lltok::kw_ashr: {
2579     bool NUW = false;
2580     bool NSW = false;
2581     bool Exact = false;
2582     unsigned Opc = Lex.getUIntVal();
2583     Constant *Val0, *Val1;
2584     Lex.Lex();
2585     LocTy ModifierLoc = Lex.getLoc();
2586     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2587         Opc == Instruction::Mul || Opc == Instruction::Shl) {
2588       if (EatIfPresent(lltok::kw_nuw))
2589         NUW = true;
2590       if (EatIfPresent(lltok::kw_nsw)) {
2591         NSW = true;
2592         if (EatIfPresent(lltok::kw_nuw))
2593           NUW = true;
2594       }
2595     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2596                Opc == Instruction::LShr || Opc == Instruction::AShr) {
2597       if (EatIfPresent(lltok::kw_exact))
2598         Exact = true;
2599     }
2600     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2601         ParseGlobalTypeAndValue(Val0) ||
2602         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2603         ParseGlobalTypeAndValue(Val1) ||
2604         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2605       return true;
2606     if (Val0->getType() != Val1->getType())
2607       return Error(ID.Loc, "operands of constexpr must have same type");
2608     if (!Val0->getType()->isIntOrIntVectorTy()) {
2609       if (NUW)
2610         return Error(ModifierLoc, "nuw only applies to integer operations");
2611       if (NSW)
2612         return Error(ModifierLoc, "nsw only applies to integer operations");
2613     }
2614     // Check that the type is valid for the operator.
2615     switch (Opc) {
2616     case Instruction::Add:
2617     case Instruction::Sub:
2618     case Instruction::Mul:
2619     case Instruction::UDiv:
2620     case Instruction::SDiv:
2621     case Instruction::URem:
2622     case Instruction::SRem:
2623     case Instruction::Shl:
2624     case Instruction::AShr:
2625     case Instruction::LShr:
2626       if (!Val0->getType()->isIntOrIntVectorTy())
2627         return Error(ID.Loc, "constexpr requires integer operands");
2628       break;
2629     case Instruction::FAdd:
2630     case Instruction::FSub:
2631     case Instruction::FMul:
2632     case Instruction::FDiv:
2633     case Instruction::FRem:
2634       if (!Val0->getType()->isFPOrFPVectorTy())
2635         return Error(ID.Loc, "constexpr requires fp operands");
2636       break;
2637     default: llvm_unreachable("Unknown binary operator!");
2638     }
2639     unsigned Flags = 0;
2640     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2641     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2642     if (Exact) Flags |= PossiblyExactOperator::IsExact;
2643     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2644     ID.ConstantVal = C;
2645     ID.Kind = ValID::t_Constant;
2646     return false;
2647   }
2648
2649   // Logical Operations
2650   case lltok::kw_and:
2651   case lltok::kw_or:
2652   case lltok::kw_xor: {
2653     unsigned Opc = Lex.getUIntVal();
2654     Constant *Val0, *Val1;
2655     Lex.Lex();
2656     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2657         ParseGlobalTypeAndValue(Val0) ||
2658         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2659         ParseGlobalTypeAndValue(Val1) ||
2660         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2661       return true;
2662     if (Val0->getType() != Val1->getType())
2663       return Error(ID.Loc, "operands of constexpr must have same type");
2664     if (!Val0->getType()->isIntOrIntVectorTy())
2665       return Error(ID.Loc,
2666                    "constexpr requires integer or integer vector operands");
2667     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2668     ID.Kind = ValID::t_Constant;
2669     return false;
2670   }
2671
2672   case lltok::kw_getelementptr:
2673   case lltok::kw_shufflevector:
2674   case lltok::kw_insertelement:
2675   case lltok::kw_extractelement:
2676   case lltok::kw_select: {
2677     unsigned Opc = Lex.getUIntVal();
2678     SmallVector<Constant*, 16> Elts;
2679     bool InBounds = false;
2680     Lex.Lex();
2681     if (Opc == Instruction::GetElementPtr)
2682       InBounds = EatIfPresent(lltok::kw_inbounds);
2683     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2684         ParseGlobalValueVector(Elts) ||
2685         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2686       return true;
2687
2688     if (Opc == Instruction::GetElementPtr) {
2689       if (Elts.size() == 0 ||
2690           !Elts[0]->getType()->getScalarType()->isPointerTy())
2691         return Error(ID.Loc, "getelementptr requires pointer operand");
2692
2693       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2694       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2695         return Error(ID.Loc, "invalid indices for getelementptr");
2696       ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2697                                                       InBounds);
2698     } else if (Opc == Instruction::Select) {
2699       if (Elts.size() != 3)
2700         return Error(ID.Loc, "expected three operands to select");
2701       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2702                                                               Elts[2]))
2703         return Error(ID.Loc, Reason);
2704       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2705     } else if (Opc == Instruction::ShuffleVector) {
2706       if (Elts.size() != 3)
2707         return Error(ID.Loc, "expected three operands to shufflevector");
2708       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2709         return Error(ID.Loc, "invalid operands to shufflevector");
2710       ID.ConstantVal =
2711                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2712     } else if (Opc == Instruction::ExtractElement) {
2713       if (Elts.size() != 2)
2714         return Error(ID.Loc, "expected two operands to extractelement");
2715       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2716         return Error(ID.Loc, "invalid extractelement operands");
2717       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2718     } else {
2719       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2720       if (Elts.size() != 3)
2721       return Error(ID.Loc, "expected three operands to insertelement");
2722       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2723         return Error(ID.Loc, "invalid insertelement operands");
2724       ID.ConstantVal =
2725                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2726     }
2727
2728     ID.Kind = ValID::t_Constant;
2729     return false;
2730   }
2731   }
2732
2733   Lex.Lex();
2734   return false;
2735 }
2736
2737 /// ParseGlobalValue - Parse a global value with the specified type.
2738 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2739   C = nullptr;
2740   ValID ID;
2741   Value *V = nullptr;
2742   bool Parsed = ParseValID(ID) ||
2743                 ConvertValIDToValue(Ty, ID, V, nullptr);
2744   if (V && !(C = dyn_cast<Constant>(V)))
2745     return Error(ID.Loc, "global values must be constants");
2746   return Parsed;
2747 }
2748
2749 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2750   Type *Ty = nullptr;
2751   return ParseType(Ty) ||
2752          ParseGlobalValue(Ty, V);
2753 }
2754
2755 /// ParseGlobalValueVector
2756 ///   ::= /*empty*/
2757 ///   ::= TypeAndValue (',' TypeAndValue)*
2758 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2759   // Empty list.
2760   if (Lex.getKind() == lltok::rbrace ||
2761       Lex.getKind() == lltok::rsquare ||
2762       Lex.getKind() == lltok::greater ||
2763       Lex.getKind() == lltok::rparen)
2764     return false;
2765
2766   Constant *C;
2767   if (ParseGlobalTypeAndValue(C)) return true;
2768   Elts.push_back(C);
2769
2770   while (EatIfPresent(lltok::comma)) {
2771     if (ParseGlobalTypeAndValue(C)) return true;
2772     Elts.push_back(C);
2773   }
2774
2775   return false;
2776 }
2777
2778 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2779   assert(Lex.getKind() == lltok::lbrace);
2780   Lex.Lex();
2781
2782   SmallVector<Value*, 16> Elts;
2783   if (ParseMDNodeVector(Elts, PFS) ||
2784       ParseToken(lltok::rbrace, "expected end of metadata node"))
2785     return true;
2786
2787   ID.MDNodeVal = MDNode::get(Context, Elts);
2788   ID.Kind = ValID::t_MDNode;
2789   return false;
2790 }
2791
2792 /// ParseMetadataValue
2793 ///  ::= !42
2794 ///  ::= !{...}
2795 ///  ::= !"string"
2796 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2797   assert(Lex.getKind() == lltok::exclaim);
2798   Lex.Lex();
2799
2800   // MDNode:
2801   // !{ ... }
2802   if (Lex.getKind() == lltok::lbrace)
2803     return ParseMetadataListValue(ID, PFS);
2804
2805   // Standalone metadata reference
2806   // !42
2807   if (Lex.getKind() == lltok::APSInt) {
2808     if (ParseMDNodeID(ID.MDNodeVal)) return true;
2809     ID.Kind = ValID::t_MDNode;
2810     return false;
2811   }
2812
2813   // MDString:
2814   //   ::= '!' STRINGCONSTANT
2815   if (ParseMDString(ID.MDStringVal)) return true;
2816   ID.Kind = ValID::t_MDString;
2817   return false;
2818 }
2819
2820
2821 //===----------------------------------------------------------------------===//
2822 // Function Parsing.
2823 //===----------------------------------------------------------------------===//
2824
2825 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2826                                    PerFunctionState *PFS) {
2827   if (Ty->isFunctionTy())
2828     return Error(ID.Loc, "functions are not values, refer to them as pointers");
2829
2830   switch (ID.Kind) {
2831   case ValID::t_LocalID:
2832     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2833     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2834     return V == nullptr;
2835   case ValID::t_LocalName:
2836     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2837     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2838     return V == nullptr;
2839   case ValID::t_InlineAsm: {
2840     PointerType *PTy = dyn_cast<PointerType>(Ty);
2841     FunctionType *FTy =
2842       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2843     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2844       return Error(ID.Loc, "invalid type for inline asm constraint string");
2845     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2846                        (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2847     return false;
2848   }
2849   case ValID::t_MDNode:
2850     if (!Ty->isMetadataTy())
2851       return Error(ID.Loc, "metadata value must have metadata type");
2852     V = ID.MDNodeVal;
2853     return false;
2854   case ValID::t_MDString:
2855     if (!Ty->isMetadataTy())
2856       return Error(ID.Loc, "metadata value must have metadata type");
2857     V = ID.MDStringVal;
2858     return false;
2859   case ValID::t_GlobalName:
2860     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2861     return V == nullptr;
2862   case ValID::t_GlobalID:
2863     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2864     return V == nullptr;
2865   case ValID::t_APSInt:
2866     if (!Ty->isIntegerTy())
2867       return Error(ID.Loc, "integer constant must have integer type");
2868     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2869     V = ConstantInt::get(Context, ID.APSIntVal);
2870     return false;
2871   case ValID::t_APFloat:
2872     if (!Ty->isFloatingPointTy() ||
2873         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2874       return Error(ID.Loc, "floating point constant invalid for type");
2875
2876     // The lexer has no type info, so builds all half, float, and double FP
2877     // constants as double.  Fix this here.  Long double does not need this.
2878     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2879       bool Ignored;
2880       if (Ty->isHalfTy())
2881         ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2882                               &Ignored);
2883       else if (Ty->isFloatTy())
2884         ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2885                               &Ignored);
2886     }
2887     V = ConstantFP::get(Context, ID.APFloatVal);
2888
2889     if (V->getType() != Ty)
2890       return Error(ID.Loc, "floating point constant does not have type '" +
2891                    getTypeString(Ty) + "'");
2892
2893     return false;
2894   case ValID::t_Null:
2895     if (!Ty->isPointerTy())
2896       return Error(ID.Loc, "null must be a pointer type");
2897     V = ConstantPointerNull::get(cast<PointerType>(Ty));
2898     return false;
2899   case ValID::t_Undef:
2900     // FIXME: LabelTy should not be a first-class type.
2901     if (!Ty->isFirstClassType() || Ty->isLabelTy())
2902       return Error(ID.Loc, "invalid type for undef constant");
2903     V = UndefValue::get(Ty);
2904     return false;
2905   case ValID::t_EmptyArray:
2906     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2907       return Error(ID.Loc, "invalid empty array initializer");
2908     V = UndefValue::get(Ty);
2909     return false;
2910   case ValID::t_Zero:
2911     // FIXME: LabelTy should not be a first-class type.
2912     if (!Ty->isFirstClassType() || Ty->isLabelTy())
2913       return Error(ID.Loc, "invalid type for null constant");
2914     V = Constant::getNullValue(Ty);
2915     return false;
2916   case ValID::t_Constant:
2917     if (ID.ConstantVal->getType() != Ty)
2918       return Error(ID.Loc, "constant expression type mismatch");
2919
2920     V = ID.ConstantVal;
2921     return false;
2922   case ValID::t_ConstantStruct:
2923   case ValID::t_PackedConstantStruct:
2924     if (StructType *ST = dyn_cast<StructType>(Ty)) {
2925       if (ST->getNumElements() != ID.UIntVal)
2926         return Error(ID.Loc,
2927                      "initializer with struct type has wrong # elements");
2928       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2929         return Error(ID.Loc, "packed'ness of initializer and type don't match");
2930
2931       // Verify that the elements are compatible with the structtype.
2932       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2933         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2934           return Error(ID.Loc, "element " + Twine(i) +
2935                     " of struct initializer doesn't match struct element type");
2936
2937       V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2938                                                ID.UIntVal));
2939     } else
2940       return Error(ID.Loc, "constant expression type mismatch");
2941     return false;
2942   }
2943   llvm_unreachable("Invalid ValID");
2944 }
2945
2946 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2947   V = nullptr;
2948   ValID ID;
2949   return ParseValID(ID, PFS) ||
2950          ConvertValIDToValue(Ty, ID, V, PFS);
2951 }
2952
2953 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2954   Type *Ty = nullptr;
2955   return ParseType(Ty) ||
2956          ParseValue(Ty, V, PFS);
2957 }
2958
2959 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2960                                       PerFunctionState &PFS) {
2961   Value *V;
2962   Loc = Lex.getLoc();
2963   if (ParseTypeAndValue(V, PFS)) return true;
2964   if (!isa<BasicBlock>(V))
2965     return Error(Loc, "expected a basic block");
2966   BB = cast<BasicBlock>(V);
2967   return false;
2968 }
2969
2970
2971 /// FunctionHeader
2972 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2973 ///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2974 ///       OptionalAlign OptGC OptionalPrefix
2975 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2976   // Parse the linkage.
2977   LocTy LinkageLoc = Lex.getLoc();
2978   unsigned Linkage;
2979
2980   unsigned Visibility;
2981   unsigned DLLStorageClass;
2982   AttrBuilder RetAttrs;
2983   CallingConv::ID CC;
2984   Type *RetType = nullptr;
2985   LocTy RetTypeLoc = Lex.getLoc();
2986   if (ParseOptionalLinkage(Linkage) ||
2987       ParseOptionalVisibility(Visibility) ||
2988       ParseOptionalDLLStorageClass(DLLStorageClass) ||
2989       ParseOptionalCallingConv(CC) ||
2990       ParseOptionalReturnAttrs(RetAttrs) ||
2991       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2992     return true;
2993
2994   // Verify that the linkage is ok.
2995   switch ((GlobalValue::LinkageTypes)Linkage) {
2996   case GlobalValue::ExternalLinkage:
2997     break; // always ok.
2998   case GlobalValue::ExternalWeakLinkage:
2999     if (isDefine)
3000       return Error(LinkageLoc, "invalid linkage for function definition");
3001     break;
3002   case GlobalValue::PrivateLinkage:
3003   case GlobalValue::InternalLinkage:
3004   case GlobalValue::AvailableExternallyLinkage:
3005   case GlobalValue::LinkOnceAnyLinkage:
3006   case GlobalValue::LinkOnceODRLinkage:
3007   case GlobalValue::WeakAnyLinkage:
3008   case GlobalValue::WeakODRLinkage:
3009     if (!isDefine)
3010       return Error(LinkageLoc, "invalid linkage for function declaration");
3011     break;
3012   case GlobalValue::AppendingLinkage:
3013   case GlobalValue::CommonLinkage:
3014     return Error(LinkageLoc, "invalid function linkage type");
3015   }
3016
3017   if (!FunctionType::isValidReturnType(RetType))
3018     return Error(RetTypeLoc, "invalid function return type");
3019
3020   LocTy NameLoc = Lex.getLoc();
3021
3022   std::string FunctionName;
3023   if (Lex.getKind() == lltok::GlobalVar) {
3024     FunctionName = Lex.getStrVal();
3025   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
3026     unsigned NameID = Lex.getUIntVal();
3027
3028     if (NameID != NumberedVals.size())
3029       return TokError("function expected to be numbered '%" +
3030                       Twine(NumberedVals.size()) + "'");
3031   } else {
3032     return TokError("expected function name");
3033   }
3034
3035   Lex.Lex();
3036
3037   if (Lex.getKind() != lltok::lparen)
3038     return TokError("expected '(' in function argument list");
3039
3040   SmallVector<ArgInfo, 8> ArgList;
3041   bool isVarArg;
3042   AttrBuilder FuncAttrs;
3043   std::vector<unsigned> FwdRefAttrGrps;
3044   LocTy BuiltinLoc;
3045   std::string Section;
3046   unsigned Alignment;
3047   std::string GC;
3048   bool UnnamedAddr;
3049   LocTy UnnamedAddrLoc;
3050   Constant *Prefix = nullptr;
3051
3052   if (ParseArgumentList(ArgList, isVarArg) ||
3053       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3054                          &UnnamedAddrLoc) ||
3055       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3056                                  BuiltinLoc) ||
3057       (EatIfPresent(lltok::kw_section) &&
3058        ParseStringConstant(Section)) ||
3059       ParseOptionalAlignment(Alignment) ||
3060       (EatIfPresent(lltok::kw_gc) &&
3061        ParseStringConstant(GC)) ||
3062       (EatIfPresent(lltok::kw_prefix) &&
3063        ParseGlobalTypeAndValue(Prefix)))
3064     return true;
3065
3066   if (FuncAttrs.contains(Attribute::Builtin))
3067     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3068
3069   // If the alignment was parsed as an attribute, move to the alignment field.
3070   if (FuncAttrs.hasAlignmentAttr()) {
3071     Alignment = FuncAttrs.getAlignment();
3072     FuncAttrs.removeAttribute(Attribute::Alignment);
3073   }
3074
3075   // Okay, if we got here, the function is syntactically valid.  Convert types
3076   // and do semantic checks.
3077   std::vector<Type*> ParamTypeList;
3078   SmallVector<AttributeSet, 8> Attrs;
3079
3080   if (RetAttrs.hasAttributes())
3081     Attrs.push_back(AttributeSet::get(RetType->getContext(),
3082                                       AttributeSet::ReturnIndex,
3083                                       RetAttrs));
3084
3085   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3086     ParamTypeList.push_back(ArgList[i].Ty);
3087     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3088       AttrBuilder B(ArgList[i].Attrs, i + 1);
3089       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3090     }
3091   }
3092
3093   if (FuncAttrs.hasAttributes())
3094     Attrs.push_back(AttributeSet::get(RetType->getContext(),
3095                                       AttributeSet::FunctionIndex,
3096                                       FuncAttrs));
3097
3098   AttributeSet PAL = AttributeSet::get(Context, Attrs);
3099
3100   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3101     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3102
3103   FunctionType *FT =
3104     FunctionType::get(RetType, ParamTypeList, isVarArg);
3105   PointerType *PFT = PointerType::getUnqual(FT);
3106
3107   Fn = nullptr;
3108   if (!FunctionName.empty()) {
3109     // If this was a definition of a forward reference, remove the definition
3110     // from the forward reference table and fill in the forward ref.
3111     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3112       ForwardRefVals.find(FunctionName);
3113     if (FRVI != ForwardRefVals.end()) {
3114       Fn = M->getFunction(FunctionName);
3115       if (!Fn)
3116         return Error(FRVI->second.second, "invalid forward reference to "
3117                      "function as global value!");
3118       if (Fn->getType() != PFT)
3119         return Error(FRVI->second.second, "invalid forward reference to "
3120                      "function '" + FunctionName + "' with wrong type!");
3121
3122       ForwardRefVals.erase(FRVI);
3123     } else if ((Fn = M->getFunction(FunctionName))) {
3124       // Reject redefinitions.
3125       return Error(NameLoc, "invalid redefinition of function '" +
3126                    FunctionName + "'");
3127     } else if (M->getNamedValue(FunctionName)) {
3128       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3129     }
3130
3131   } else {
3132     // If this is a definition of a forward referenced function, make sure the
3133     // types agree.
3134     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3135       = ForwardRefValIDs.find(NumberedVals.size());
3136     if (I != ForwardRefValIDs.end()) {
3137       Fn = cast<Function>(I->second.first);
3138       if (Fn->getType() != PFT)
3139         return Error(NameLoc, "type of definition and forward reference of '@" +
3140                      Twine(NumberedVals.size()) + "' disagree");
3141       ForwardRefValIDs.erase(I);
3142     }
3143   }
3144
3145   if (!Fn)
3146     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3147   else // Move the forward-reference to the correct spot in the module.
3148     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3149
3150   if (FunctionName.empty())
3151     NumberedVals.push_back(Fn);
3152
3153   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3154   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3155   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3156   Fn->setCallingConv(CC);
3157   Fn->setAttributes(PAL);
3158   Fn->setUnnamedAddr(UnnamedAddr);
3159   Fn->setAlignment(Alignment);
3160   Fn->setSection(Section);
3161   if (!GC.empty()) Fn->setGC(GC.c_str());
3162   Fn->setPrefixData(Prefix);
3163   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3164
3165   // Add all of the arguments we parsed to the function.
3166   Function::arg_iterator ArgIt = Fn->arg_begin();
3167   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3168     // If the argument has a name, insert it into the argument symbol table.
3169     if (ArgList[i].Name.empty()) continue;
3170
3171     // Set the name, if it conflicted, it will be auto-renamed.
3172     ArgIt->setName(ArgList[i].Name);
3173
3174     if (ArgIt->getName() != ArgList[i].Name)
3175       return Error(ArgList[i].Loc, "redefinition of argument '%" +
3176                    ArgList[i].Name + "'");
3177   }
3178
3179   return false;
3180 }
3181
3182
3183 /// ParseFunctionBody
3184 ///   ::= '{' BasicBlock+ '}'
3185 ///
3186 bool LLParser::ParseFunctionBody(Function &Fn) {
3187   if (Lex.getKind() != lltok::lbrace)
3188     return TokError("expected '{' in function body");
3189   Lex.Lex();  // eat the {.
3190
3191   int FunctionNumber = -1;
3192   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3193
3194   PerFunctionState PFS(*this, Fn, FunctionNumber);
3195
3196   // We need at least one basic block.
3197   if (Lex.getKind() == lltok::rbrace)
3198     return TokError("function body requires at least one basic block");
3199
3200   while (Lex.getKind() != lltok::rbrace)
3201     if (ParseBasicBlock(PFS)) return true;
3202
3203   // Eat the }.
3204   Lex.Lex();
3205
3206   // Verify function is ok.
3207   return PFS.FinishFunction();
3208 }
3209
3210 /// ParseBasicBlock
3211 ///   ::= LabelStr? Instruction*
3212 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3213   // If this basic block starts out with a name, remember it.
3214   std::string Name;
3215   LocTy NameLoc = Lex.getLoc();
3216   if (Lex.getKind() == lltok::LabelStr) {
3217     Name = Lex.getStrVal();
3218     Lex.Lex();
3219   }
3220
3221   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3222   if (!BB) return true;
3223
3224   std::string NameStr;
3225
3226   // Parse the instructions in this block until we get a terminator.
3227   Instruction *Inst;
3228   do {
3229     // This instruction may have three possibilities for a name: a) none
3230     // specified, b) name specified "%foo =", c) number specified: "%4 =".
3231     LocTy NameLoc = Lex.getLoc();
3232     int NameID = -1;
3233     NameStr = "";
3234
3235     if (Lex.getKind() == lltok::LocalVarID) {
3236       NameID = Lex.getUIntVal();
3237       Lex.Lex();
3238       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3239         return true;
3240     } else if (Lex.getKind() == lltok::LocalVar) {
3241       NameStr = Lex.getStrVal();
3242       Lex.Lex();
3243       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3244         return true;
3245     }
3246
3247     switch (ParseInstruction(Inst, BB, PFS)) {
3248     default: llvm_unreachable("Unknown ParseInstruction result!");
3249     case InstError: return true;
3250     case InstNormal:
3251       BB->getInstList().push_back(Inst);
3252
3253       // With a normal result, we check to see if the instruction is followed by
3254       // a comma and metadata.
3255       if (EatIfPresent(lltok::comma))
3256         if (ParseInstructionMetadata(Inst, &PFS))
3257           return true;
3258       break;
3259     case InstExtraComma:
3260       BB->getInstList().push_back(Inst);
3261
3262       // If the instruction parser ate an extra comma at the end of it, it
3263       // *must* be followed by metadata.
3264       if (ParseInstructionMetadata(Inst, &PFS))
3265         return true;
3266       break;
3267     }
3268
3269     // Set the name on the instruction.
3270     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3271   } while (!isa<TerminatorInst>(Inst));
3272
3273   return false;
3274 }
3275
3276 //===----------------------------------------------------------------------===//
3277 // Instruction Parsing.
3278 //===----------------------------------------------------------------------===//
3279
3280 /// ParseInstruction - Parse one of the many different instructions.
3281 ///
3282 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3283                                PerFunctionState &PFS) {
3284   lltok::Kind Token = Lex.getKind();
3285   if (Token == lltok::Eof)
3286     return TokError("found end of file when expecting more instructions");
3287   LocTy Loc = Lex.getLoc();
3288   unsigned KeywordVal = Lex.getUIntVal();
3289   Lex.Lex();  // Eat the keyword.
3290
3291   switch (Token) {
3292   default:                    return Error(Loc, "expected instruction opcode");
3293   // Terminator Instructions.
3294   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3295   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
3296   case lltok::kw_br:          return ParseBr(Inst, PFS);
3297   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
3298   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
3299   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
3300   case lltok::kw_resume:      return ParseResume(Inst, PFS);
3301   // Binary Operators.
3302   case lltok::kw_add:
3303   case lltok::kw_sub:
3304   case lltok::kw_mul:
3305   case lltok::kw_shl: {
3306     bool NUW = EatIfPresent(lltok::kw_nuw);
3307     bool NSW = EatIfPresent(lltok::kw_nsw);
3308     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3309
3310     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3311
3312     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3313     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3314     return false;
3315   }
3316   case lltok::kw_fadd:
3317   case lltok::kw_fsub:
3318   case lltok::kw_fmul:
3319   case lltok::kw_fdiv:
3320   case lltok::kw_frem: {
3321     FastMathFlags FMF = EatFastMathFlagsIfPresent();
3322     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3323     if (Res != 0)
3324       return Res;
3325     if (FMF.any())
3326       Inst->setFastMathFlags(FMF);
3327     return 0;
3328   }
3329
3330   case lltok::kw_sdiv:
3331   case lltok::kw_udiv:
3332   case lltok::kw_lshr:
3333   case lltok::kw_ashr: {
3334     bool Exact = EatIfPresent(lltok::kw_exact);
3335
3336     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3337     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3338     return false;
3339   }
3340
3341   case lltok::kw_urem:
3342   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3343   case lltok::kw_and:
3344   case lltok::kw_or:
3345   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
3346   case lltok::kw_icmp:
3347   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
3348   // Casts.
3349   case lltok::kw_trunc:
3350   case lltok::kw_zext:
3351   case lltok::kw_sext:
3352   case lltok::kw_fptrunc:
3353   case lltok::kw_fpext:
3354   case lltok::kw_bitcast:
3355   case lltok::kw_addrspacecast:
3356   case lltok::kw_uitofp:
3357   case lltok::kw_sitofp:
3358   case lltok::kw_fptoui:
3359   case lltok::kw_fptosi:
3360   case lltok::kw_inttoptr:
3361   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
3362   // Other.
3363   case lltok::kw_select:         return ParseSelect(Inst, PFS);
3364   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
3365   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3366   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
3367   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
3368   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
3369   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
3370   // Call.
3371   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
3372   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3373   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3374   // Memory.
3375   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
3376   case lltok::kw_load:           return ParseLoad(Inst, PFS);
3377   case lltok::kw_store:          return ParseStore(Inst, PFS);
3378   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
3379   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
3380   case lltok::kw_fence:          return ParseFence(Inst, PFS);
3381   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3382   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
3383   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
3384   }
3385 }
3386
3387 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3388 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3389   if (Opc == Instruction::FCmp) {
3390     switch (Lex.getKind()) {
3391     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3392     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3393     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3394     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3395     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3396     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3397     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3398     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3399     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3400     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3401     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3402     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3403     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3404     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3405     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3406     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3407     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3408     }
3409   } else {
3410     switch (Lex.getKind()) {
3411     default: return TokError("expected icmp predicate (e.g. 'eq')");
3412     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
3413     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
3414     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3415     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3416     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3417     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3418     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3419     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3420     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3421     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3422     }
3423   }
3424   Lex.Lex();
3425   return false;
3426 }
3427
3428 //===----------------------------------------------------------------------===//
3429 // Terminator Instructions.
3430 //===----------------------------------------------------------------------===//
3431
3432 /// ParseRet - Parse a return instruction.
3433 ///   ::= 'ret' void (',' !dbg, !1)*
3434 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
3435 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3436                         PerFunctionState &PFS) {
3437   SMLoc TypeLoc = Lex.getLoc();
3438   Type *Ty = nullptr;
3439   if (ParseType(Ty, true /*void allowed*/)) return true;
3440
3441   Type *ResType = PFS.getFunction().getReturnType();
3442
3443   if (Ty->isVoidTy()) {
3444     if (!ResType->isVoidTy())
3445       return Error(TypeLoc, "value doesn't match function result type '" +
3446                    getTypeString(ResType) + "'");
3447
3448     Inst = ReturnInst::Create(Context);
3449     return false;
3450   }
3451
3452   Value *RV;
3453   if (ParseValue(Ty, RV, PFS)) return true;
3454
3455   if (ResType != RV->getType())
3456     return Error(TypeLoc, "value doesn't match function result type '" +
3457                  getTypeString(ResType) + "'");
3458
3459   Inst = ReturnInst::Create(Context, RV);
3460   return false;
3461 }
3462
3463
3464 /// ParseBr
3465 ///   ::= 'br' TypeAndValue
3466 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3467 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3468   LocTy Loc, Loc2;
3469   Value *Op0;
3470   BasicBlock *Op1, *Op2;
3471   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3472
3473   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3474     Inst = BranchInst::Create(BB);
3475     return false;
3476   }
3477
3478   if (Op0->getType() != Type::getInt1Ty(Context))
3479     return Error(Loc, "branch condition must have 'i1' type");
3480
3481   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3482       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3483       ParseToken(lltok::comma, "expected ',' after true destination") ||
3484       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3485     return true;
3486
3487   Inst = BranchInst::Create(Op1, Op2, Op0);
3488   return false;
3489 }
3490
3491 /// ParseSwitch
3492 ///  Instruction
3493 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3494 ///  JumpTable
3495 ///    ::= (TypeAndValue ',' TypeAndValue)*
3496 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3497   LocTy CondLoc, BBLoc;
3498   Value *Cond;
3499   BasicBlock *DefaultBB;
3500   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3501       ParseToken(lltok::comma, "expected ',' after switch condition") ||
3502       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3503       ParseToken(lltok::lsquare, "expected '[' with switch table"))
3504     return true;
3505
3506   if (!Cond->getType()->isIntegerTy())
3507     return Error(CondLoc, "switch condition must have integer type");
3508
3509   // Parse the jump table pairs.
3510   SmallPtrSet<Value*, 32> SeenCases;
3511   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3512   while (Lex.getKind() != lltok::rsquare) {
3513     Value *Constant;
3514     BasicBlock *DestBB;
3515
3516     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3517         ParseToken(lltok::comma, "expected ',' after case value") ||
3518         ParseTypeAndBasicBlock(DestBB, PFS))
3519       return true;
3520
3521     if (!SeenCases.insert(Constant))
3522       return Error(CondLoc, "duplicate case value in switch");
3523     if (!isa<ConstantInt>(Constant))
3524       return Error(CondLoc, "case value is not a constant integer");
3525
3526     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3527   }
3528
3529   Lex.Lex();  // Eat the ']'.
3530
3531   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3532   for (unsigned i = 0, e = Table.size(); i != e; ++i)
3533     SI->addCase(Table[i].first, Table[i].second);
3534   Inst = SI;
3535   return false;
3536 }
3537
3538 /// ParseIndirectBr
3539 ///  Instruction
3540 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3541 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3542   LocTy AddrLoc;
3543   Value *Address;
3544   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3545       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3546       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3547     return true;
3548
3549   if (!Address->getType()->isPointerTy())
3550     return Error(AddrLoc, "indirectbr address must have pointer type");
3551
3552   // Parse the destination list.
3553   SmallVector<BasicBlock*, 16> DestList;
3554
3555   if (Lex.getKind() != lltok::rsquare) {
3556     BasicBlock *DestBB;
3557     if (ParseTypeAndBasicBlock(DestBB, PFS))
3558       return true;
3559     DestList.push_back(DestBB);
3560
3561     while (EatIfPresent(lltok::comma)) {
3562       if (ParseTypeAndBasicBlock(DestBB, PFS))
3563         return true;
3564       DestList.push_back(DestBB);
3565     }
3566   }
3567
3568   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3569     return true;
3570
3571   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3572   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3573     IBI->addDestination(DestList[i]);
3574   Inst = IBI;
3575   return false;
3576 }
3577
3578
3579 /// ParseInvoke
3580 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3581 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3582 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3583   LocTy CallLoc = Lex.getLoc();
3584   AttrBuilder RetAttrs, FnAttrs;
3585   std::vector<unsigned> FwdRefAttrGrps;
3586   LocTy NoBuiltinLoc;
3587   CallingConv::ID CC;
3588   Type *RetType = nullptr;
3589   LocTy RetTypeLoc;
3590   ValID CalleeID;
3591   SmallVector<ParamInfo, 16> ArgList;
3592
3593   BasicBlock *NormalBB, *UnwindBB;
3594   if (ParseOptionalCallingConv(CC) ||
3595       ParseOptionalReturnAttrs(RetAttrs) ||
3596       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3597       ParseValID(CalleeID) ||
3598       ParseParameterList(ArgList, PFS) ||
3599       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3600                                  NoBuiltinLoc) ||
3601       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3602       ParseTypeAndBasicBlock(NormalBB, PFS) ||
3603       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3604       ParseTypeAndBasicBlock(UnwindBB, PFS))
3605     return true;
3606
3607   // If RetType is a non-function pointer type, then this is the short syntax
3608   // for the call, which means that RetType is just the return type.  Infer the
3609   // rest of the function argument types from the arguments that are present.
3610   PointerType *PFTy = nullptr;
3611   FunctionType *Ty = nullptr;
3612   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3613       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3614     // Pull out the types of all of the arguments...
3615     std::vector<Type*> ParamTypes;
3616     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3617       ParamTypes.push_back(ArgList[i].V->getType());
3618
3619     if (!FunctionType::isValidReturnType(RetType))
3620       return Error(RetTypeLoc, "Invalid result type for LLVM function");
3621
3622     Ty = FunctionType::get(RetType, ParamTypes, false);
3623     PFTy = PointerType::getUnqual(Ty);
3624   }
3625
3626   // Look up the callee.
3627   Value *Callee;
3628   if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3629
3630   // Set up the Attribute for the function.
3631   SmallVector<AttributeSet, 8> Attrs;
3632   if (RetAttrs.hasAttributes())
3633     Attrs.push_back(AttributeSet::get(RetType->getContext(),
3634                                       AttributeSet::ReturnIndex,
3635                                       RetAttrs));
3636
3637   SmallVector<Value*, 8> Args;
3638
3639   // Loop through FunctionType's arguments and ensure they are specified
3640   // correctly.  Also, gather any parameter attributes.
3641   FunctionType::param_iterator I = Ty->param_begin();
3642   FunctionType::param_iterator E = Ty->param_end();
3643   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3644     Type *ExpectedTy = nullptr;
3645     if (I != E) {
3646       ExpectedTy = *I++;
3647     } else if (!Ty->isVarArg()) {
3648       return Error(ArgList[i].Loc, "too many arguments specified");
3649     }
3650
3651     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3652       return Error(ArgList[i].Loc, "argument is not of expected type '" +
3653                    getTypeString(ExpectedTy) + "'");
3654     Args.push_back(ArgList[i].V);
3655     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3656       AttrBuilder B(ArgList[i].Attrs, i + 1);
3657       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3658     }
3659   }
3660
3661   if (I != E)
3662     return Error(CallLoc, "not enough parameters specified for call");
3663
3664   if (FnAttrs.hasAttributes())
3665     Attrs.push_back(AttributeSet::get(RetType->getContext(),
3666                                       AttributeSet::FunctionIndex,
3667                                       FnAttrs));
3668
3669   // Finish off the Attribute and check them
3670   AttributeSet PAL = AttributeSet::get(Context, Attrs);
3671
3672   InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3673   II->setCallingConv(CC);
3674   II->setAttributes(PAL);
3675   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3676   Inst = II;
3677   return false;
3678 }
3679
3680 /// ParseResume
3681 ///   ::= 'resume' TypeAndValue
3682 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3683   Value *Exn; LocTy ExnLoc;
3684   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3685     return true;
3686
3687   ResumeInst *RI = ResumeInst::Create(Exn);
3688   Inst = RI;
3689   return false;
3690 }
3691
3692 //===----------------------------------------------------------------------===//
3693 // Binary Operators.
3694 //===----------------------------------------------------------------------===//
3695
3696 /// ParseArithmetic
3697 ///  ::= ArithmeticOps TypeAndValue ',' Value
3698 ///
3699 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3700 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3701 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3702                                unsigned Opc, unsigned OperandType) {
3703   LocTy Loc; Value *LHS, *RHS;
3704   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3705       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3706       ParseValue(LHS->getType(), RHS, PFS))
3707     return true;
3708
3709   bool Valid;
3710   switch (OperandType) {
3711   default: llvm_unreachable("Unknown operand type!");
3712   case 0: // int or FP.
3713     Valid = LHS->getType()->isIntOrIntVectorTy() ||
3714             LHS->getType()->isFPOrFPVectorTy();
3715     break;
3716   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3717   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3718   }
3719
3720   if (!Valid)
3721     return Error(Loc, "invalid operand type for instruction");
3722
3723   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3724   return false;
3725 }
3726
3727 /// ParseLogical
3728 ///  ::= ArithmeticOps TypeAndValue ',' Value {
3729 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3730                             unsigned Opc) {
3731   LocTy Loc; Value *LHS, *RHS;
3732   if (ParseTypeAndValue(LHS, Loc, PFS) ||
3733       ParseToken(lltok::comma, "expected ',' in logical operation") ||
3734       ParseValue(LHS->getType(), RHS, PFS))
3735     return true;
3736
3737   if (!LHS->getType()->isIntOrIntVectorTy())
3738     return Error(Loc,"instruction requires integer or integer vector operands");
3739
3740   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3741   return false;
3742 }
3743
3744
3745 /// ParseCompare
3746 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3747 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3748 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3749                             unsigned Opc) {
3750   // Parse the integer/fp comparison predicate.
3751   LocTy Loc;
3752   unsigned Pred;
3753   Value *LHS, *RHS;
3754   if (ParseCmpPredicate(Pred, Opc) ||
3755       ParseTypeAndValue(LHS, Loc, PFS) ||
3756       ParseToken(lltok::comma, "expected ',' after compare value") ||
3757       ParseValue(LHS->getType(), RHS, PFS))
3758     return true;
3759
3760   if (Opc == Instruction::FCmp) {
3761     if (!LHS->getType()->isFPOrFPVectorTy())
3762       return Error(Loc, "fcmp requires floating point operands");
3763     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3764   } else {
3765     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3766     if (!LHS->getType()->isIntOrIntVectorTy() &&
3767         !LHS->getType()->getScalarType()->isPointerTy())
3768       return Error(Loc, "icmp requires integer operands");
3769     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3770   }
3771   return false;
3772 }
3773
3774 //===----------------------------------------------------------------------===//
3775 // Other Instructions.
3776 //===----------------------------------------------------------------------===//
3777
3778
3779 /// ParseCast
3780 ///   ::= CastOpc TypeAndValue 'to' Type
3781 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3782                          unsigned Opc) {
3783   LocTy Loc;
3784   Value *Op;
3785   Type *DestTy = nullptr;
3786   if (ParseTypeAndValue(Op, Loc, PFS) ||
3787       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3788       ParseType(DestTy))
3789     return true;
3790
3791   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3792     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3793     return Error(Loc, "invalid cast opcode for cast from '" +
3794                  getTypeString(Op->getType()) + "' to '" +
3795                  getTypeString(DestTy) + "'");
3796   }
3797   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3798   return false;
3799 }
3800
3801 /// ParseSelect
3802 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3803 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3804   LocTy Loc;
3805   Value *Op0, *Op1, *Op2;
3806   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3807       ParseToken(lltok::comma, "expected ',' after select condition") ||
3808       ParseTypeAndValue(Op1, PFS) ||
3809       ParseToken(lltok::comma, "expected ',' after select value") ||
3810       ParseTypeAndValue(Op2, PFS))
3811     return true;
3812
3813   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3814     return Error(Loc, Reason);
3815
3816   Inst = SelectInst::Create(Op0, Op1, Op2);
3817   return false;
3818 }
3819
3820 /// ParseVA_Arg
3821 ///   ::= 'va_arg' TypeAndValue ',' Type
3822 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3823   Value *Op;
3824   Type *EltTy = nullptr;
3825   LocTy TypeLoc;
3826   if (ParseTypeAndValue(Op, PFS) ||
3827       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3828       ParseType(EltTy, TypeLoc))
3829     return true;
3830
3831   if (!EltTy->isFirstClassType())
3832     return Error(TypeLoc, "va_arg requires operand with first class type");
3833
3834   Inst = new VAArgInst(Op, EltTy);
3835   return false;
3836 }
3837
3838 /// ParseExtractElement
3839 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3840 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3841   LocTy Loc;
3842   Value *Op0, *Op1;
3843   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3844       ParseToken(lltok::comma, "expected ',' after extract value") ||
3845       ParseTypeAndValue(Op1, PFS))
3846     return true;
3847
3848   if (!ExtractElementInst::isValidOperands(Op0, Op1))
3849     return Error(Loc, "invalid extractelement operands");
3850
3851   Inst = ExtractElementInst::Create(Op0, Op1);
3852   return false;
3853 }
3854
3855 /// ParseInsertElement
3856 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3857 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3858   LocTy Loc;
3859   Value *Op0, *Op1, *Op2;
3860   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3861       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3862       ParseTypeAndValue(Op1, PFS) ||
3863       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3864       ParseTypeAndValue(Op2, PFS))
3865     return true;
3866
3867   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3868     return Error(Loc, "invalid insertelement operands");
3869
3870   Inst = InsertElementInst::Create(Op0, Op1, Op2);
3871   return false;
3872 }
3873
3874 /// ParseShuffleVector
3875 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3876 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3877   LocTy Loc;
3878   Value *Op0, *Op1, *Op2;
3879   if (ParseTypeAndValue(Op0, Loc, PFS) ||
3880       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3881       ParseTypeAndValue(Op1, PFS) ||
3882       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3883       ParseTypeAndValue(Op2, PFS))
3884     return true;
3885
3886   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3887     return Error(Loc, "invalid shufflevector operands");
3888
3889   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3890   return false;
3891 }
3892
3893 /// ParsePHI
3894 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3895 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3896   Type *Ty = nullptr;  LocTy TypeLoc;
3897   Value *Op0, *Op1;
3898
3899   if (ParseType(Ty, TypeLoc) ||
3900       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3901       ParseValue(Ty, Op0, PFS) ||
3902       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3903       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3904       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3905     return true;
3906
3907   bool AteExtraComma = false;
3908   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3909   while (1) {
3910     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3911
3912     if (!EatIfPresent(lltok::comma))
3913       break;
3914
3915     if (Lex.getKind() == lltok::MetadataVar) {
3916       AteExtraComma = true;
3917       break;
3918     }
3919
3920     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3921         ParseValue(Ty, Op0, PFS) ||
3922         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3923         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3924         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3925       return true;
3926   }
3927
3928   if (!Ty->isFirstClassType())
3929     return Error(TypeLoc, "phi node must have first class type");
3930
3931   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3932   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3933     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3934   Inst = PN;
3935   return AteExtraComma ? InstExtraComma : InstNormal;
3936 }
3937
3938 /// ParseLandingPad
3939 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3940 /// Clause
3941 ///   ::= 'catch' TypeAndValue
3942 ///   ::= 'filter'
3943 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3944 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3945   Type *Ty = nullptr; LocTy TyLoc;
3946   Value *PersFn; LocTy PersFnLoc;
3947
3948   if (ParseType(Ty, TyLoc) ||
3949       ParseToken(lltok::kw_personality, "expected 'personality'") ||
3950       ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3951     return true;
3952
3953   LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3954   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3955
3956   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3957     LandingPadInst::ClauseType CT;
3958     if (EatIfPresent(lltok::kw_catch))
3959       CT = LandingPadInst::Catch;
3960     else if (EatIfPresent(lltok::kw_filter))
3961       CT = LandingPadInst::Filter;
3962     else
3963       return TokError("expected 'catch' or 'filter' clause type");
3964
3965     Value *V; LocTy VLoc;
3966     if (ParseTypeAndValue(V, VLoc, PFS)) {
3967       delete LP;
3968       return true;
3969     }
3970
3971     // A 'catch' type expects a non-array constant. A filter clause expects an
3972     // array constant.
3973     if (CT == LandingPadInst::Catch) {
3974       if (isa<ArrayType>(V->getType()))
3975         Error(VLoc, "'catch' clause has an invalid type");
3976     } else {
3977       if (!isa<ArrayType>(V->getType()))
3978         Error(VLoc, "'filter' clause has an invalid type");
3979     }
3980
3981     LP->addClause(V);
3982   }
3983
3984   Inst = LP;
3985   return false;
3986 }
3987
3988 /// ParseCall
3989 ///   ::= 'call' OptionalCallingConv OptionalAttrs Type Value
3990 ///       ParameterList OptionalAttrs
3991 ///   ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
3992 ///       ParameterList OptionalAttrs
3993 ///   ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
3994 ///       ParameterList OptionalAttrs
3995 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3996                          CallInst::TailCallKind TCK) {
3997   AttrBuilder RetAttrs, FnAttrs;
3998   std::vector<unsigned> FwdRefAttrGrps;
3999   LocTy BuiltinLoc;
4000   CallingConv::ID CC;
4001   Type *RetType = nullptr;
4002   LocTy RetTypeLoc;
4003   ValID CalleeID;
4004   SmallVector<ParamInfo, 16> ArgList;
4005   LocTy CallLoc = Lex.getLoc();
4006
4007   if ((TCK != CallInst::TCK_None &&
4008        ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4009       ParseOptionalCallingConv(CC) ||
4010       ParseOptionalReturnAttrs(RetAttrs) ||
4011       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4012       ParseValID(CalleeID) ||
4013       ParseParameterList(ArgList, PFS) ||
4014       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4015                                  BuiltinLoc))
4016     return true;
4017
4018   // If RetType is a non-function pointer type, then this is the short syntax
4019   // for the call, which means that RetType is just the return type.  Infer the
4020   // rest of the function argument types from the arguments that are present.
4021   PointerType *PFTy = nullptr;
4022   FunctionType *Ty = nullptr;
4023   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4024       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4025     // Pull out the types of all of the arguments...
4026     std::vector<Type*> ParamTypes;
4027     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4028       ParamTypes.push_back(ArgList[i].V->getType());
4029
4030     if (!FunctionType::isValidReturnType(RetType))
4031       return Error(RetTypeLoc, "Invalid result type for LLVM function");
4032
4033     Ty = FunctionType::get(RetType, ParamTypes, false);
4034     PFTy = PointerType::getUnqual(Ty);
4035   }
4036
4037   // Look up the callee.
4038   Value *Callee;
4039   if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4040
4041   // Set up the Attribute for the function.
4042   SmallVector<AttributeSet, 8> Attrs;
4043   if (RetAttrs.hasAttributes())
4044     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4045                                       AttributeSet::ReturnIndex,
4046                                       RetAttrs));
4047
4048   SmallVector<Value*, 8> Args;
4049
4050   // Loop through FunctionType's arguments and ensure they are specified
4051   // correctly.  Also, gather any parameter attributes.
4052   FunctionType::param_iterator I = Ty->param_begin();
4053   FunctionType::param_iterator E = Ty->param_end();
4054   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4055     Type *ExpectedTy = nullptr;
4056     if (I != E) {
4057       ExpectedTy = *I++;
4058     } else if (!Ty->isVarArg()) {
4059       return Error(ArgList[i].Loc, "too many arguments specified");
4060     }
4061
4062     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4063       return Error(ArgList[i].Loc, "argument is not of expected type '" +
4064                    getTypeString(ExpectedTy) + "'");
4065     Args.push_back(ArgList[i].V);
4066     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4067       AttrBuilder B(ArgList[i].Attrs, i + 1);
4068       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4069     }
4070   }
4071
4072   if (I != E)
4073     return Error(CallLoc, "not enough parameters specified for call");
4074
4075   if (FnAttrs.hasAttributes())
4076     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4077                                       AttributeSet::FunctionIndex,
4078                                       FnAttrs));
4079
4080   // Finish off the Attribute and check them
4081   AttributeSet PAL = AttributeSet::get(Context, Attrs);
4082
4083   CallInst *CI = CallInst::Create(Callee, Args);
4084   CI->setTailCallKind(TCK);
4085   CI->setCallingConv(CC);
4086   CI->setAttributes(PAL);
4087   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4088   Inst = CI;
4089   return false;
4090 }
4091
4092 //===----------------------------------------------------------------------===//
4093 // Memory Instructions.
4094 //===----------------------------------------------------------------------===//
4095
4096 /// ParseAlloc
4097 ///   ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4098 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4099   Value *Size = nullptr;
4100   LocTy SizeLoc;
4101   unsigned Alignment = 0;
4102   Type *Ty = nullptr;
4103
4104   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4105
4106   if (ParseType(Ty)) return true;
4107
4108   bool AteExtraComma = false;
4109   if (EatIfPresent(lltok::comma)) {
4110     if (Lex.getKind() == lltok::kw_align) {
4111       if (ParseOptionalAlignment(Alignment)) return true;
4112     } else if (Lex.getKind() == lltok::MetadataVar) {
4113       AteExtraComma = true;
4114     } else {
4115       if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4116           ParseOptionalCommaAlign(Alignment, AteExtraComma))
4117         return true;
4118     }
4119   }
4120
4121   if (Size && !Size->getType()->isIntegerTy())
4122     return Error(SizeLoc, "element count must have integer type");
4123
4124   AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4125   AI->setUsedWithInAlloca(IsInAlloca);
4126   Inst = AI;
4127   return AteExtraComma ? InstExtraComma : InstNormal;
4128 }
4129
4130 /// ParseLoad
4131 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4132 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
4133 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
4134 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4135   Value *Val; LocTy Loc;
4136   unsigned Alignment = 0;
4137   bool AteExtraComma = false;
4138   bool isAtomic = false;
4139   AtomicOrdering Ordering = NotAtomic;
4140   SynchronizationScope Scope = CrossThread;
4141
4142   if (Lex.getKind() == lltok::kw_atomic) {
4143     isAtomic = true;
4144     Lex.Lex();
4145   }
4146
4147   bool isVolatile = false;
4148   if (Lex.getKind() == lltok::kw_volatile) {
4149     isVolatile = true;
4150     Lex.Lex();
4151   }
4152
4153   if (ParseTypeAndValue(Val, Loc, PFS) ||
4154       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4155       ParseOptionalCommaAlign(Alignment, AteExtraComma))
4156     return true;
4157
4158   if (!Val->getType()->isPointerTy() ||
4159       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4160     return Error(Loc, "load operand must be a pointer to a first class type");
4161   if (isAtomic && !Alignment)
4162     return Error(Loc, "atomic load must have explicit non-zero alignment");
4163   if (Ordering == Release || Ordering == AcquireRelease)
4164     return Error(Loc, "atomic load cannot use Release ordering");
4165
4166   Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4167   return AteExtraComma ? InstExtraComma : InstNormal;
4168 }
4169
4170 /// ParseStore
4171
4172 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4173 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4174 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
4175 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4176   Value *Val, *Ptr; LocTy Loc, PtrLoc;
4177   unsigned Alignment = 0;
4178   bool AteExtraComma = false;
4179   bool isAtomic = false;
4180   AtomicOrdering Ordering = NotAtomic;
4181   SynchronizationScope Scope = CrossThread;
4182
4183   if (Lex.getKind() == lltok::kw_atomic) {
4184     isAtomic = true;
4185     Lex.Lex();
4186   }
4187
4188   bool isVolatile = false;
4189   if (Lex.getKind() == lltok::kw_volatile) {
4190     isVolatile = true;
4191     Lex.Lex();
4192   }
4193
4194   if (ParseTypeAndValue(Val, Loc, PFS) ||
4195       ParseToken(lltok::comma, "expected ',' after store operand") ||
4196       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4197       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4198       ParseOptionalCommaAlign(Alignment, AteExtraComma))
4199     return true;
4200
4201   if (!Ptr->getType()->isPointerTy())
4202     return Error(PtrLoc, "store operand must be a pointer");
4203   if (!Val->getType()->isFirstClassType())
4204     return Error(Loc, "store operand must be a first class value");
4205   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4206     return Error(Loc, "stored value and pointer type do not match");
4207   if (isAtomic && !Alignment)
4208     return Error(Loc, "atomic store must have explicit non-zero alignment");
4209   if (Ordering == Acquire || Ordering == AcquireRelease)
4210     return Error(Loc, "atomic store cannot use Acquire ordering");
4211
4212   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4213   return AteExtraComma ? InstExtraComma : InstNormal;
4214 }
4215
4216 /// ParseCmpXchg
4217 ///   ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4218 ///       'singlethread'? AtomicOrdering AtomicOrdering
4219 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4220   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4221   bool AteExtraComma = false;
4222   AtomicOrdering SuccessOrdering = NotAtomic;
4223   AtomicOrdering FailureOrdering = NotAtomic;
4224   SynchronizationScope Scope = CrossThread;
4225   bool isVolatile = false;
4226
4227   if (EatIfPresent(lltok::kw_volatile))
4228     isVolatile = true;
4229
4230   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4231       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4232       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4233       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4234       ParseTypeAndValue(New, NewLoc, PFS) ||
4235       ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4236       ParseOrdering(FailureOrdering))
4237     return true;
4238
4239   if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4240     return TokError("cmpxchg cannot be unordered");
4241   if (SuccessOrdering < FailureOrdering)
4242     return TokError("cmpxchg must be at least as ordered on success as failure");
4243   if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4244     return TokError("cmpxchg failure ordering cannot include release semantics");
4245   if (!Ptr->getType()->isPointerTy())
4246     return Error(PtrLoc, "cmpxchg operand must be a pointer");
4247   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4248     return Error(CmpLoc, "compare value and pointer type do not match");
4249   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4250     return Error(NewLoc, "new value and pointer type do not match");
4251   if (!New->getType()->isIntegerTy())
4252     return Error(NewLoc, "cmpxchg operand must be an integer");
4253   unsigned Size = New->getType()->getPrimitiveSizeInBits();
4254   if (Size < 8 || (Size & (Size - 1)))
4255     return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4256                          " integer");
4257
4258   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4259                                                  FailureOrdering, Scope);
4260   CXI->setVolatile(isVolatile);
4261   Inst = CXI;
4262   return AteExtraComma ? InstExtraComma : InstNormal;
4263 }
4264
4265 /// ParseAtomicRMW
4266 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4267 ///       'singlethread'? AtomicOrdering
4268 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4269   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4270   bool AteExtraComma = false;
4271   AtomicOrdering Ordering = NotAtomic;
4272   SynchronizationScope Scope = CrossThread;
4273   bool isVolatile = false;
4274   AtomicRMWInst::BinOp Operation;
4275
4276   if (EatIfPresent(lltok::kw_volatile))
4277     isVolatile = true;
4278
4279   switch (Lex.getKind()) {
4280   default: return TokError("expected binary operation in atomicrmw");
4281   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4282   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4283   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4284   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4285   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4286   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4287   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4288   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4289   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4290   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4291   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4292   }
4293   Lex.Lex();  // Eat the operation.
4294
4295   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4296       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4297       ParseTypeAndValue(Val, ValLoc, PFS) ||
4298       ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4299     return true;
4300
4301   if (Ordering == Unordered)
4302     return TokError("atomicrmw cannot be unordered");
4303   if (!Ptr->getType()->isPointerTy())
4304     return Error(PtrLoc, "atomicrmw operand must be a pointer");
4305   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4306     return Error(ValLoc, "atomicrmw value and pointer type do not match");
4307   if (!Val->getType()->isIntegerTy())
4308     return Error(ValLoc, "atomicrmw operand must be an integer");
4309   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4310   if (Size < 8 || (Size & (Size - 1)))
4311     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4312                          " integer");
4313
4314   AtomicRMWInst *RMWI =
4315     new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4316   RMWI->setVolatile(isVolatile);
4317   Inst = RMWI;
4318   return AteExtraComma ? InstExtraComma : InstNormal;
4319 }
4320
4321 /// ParseFence
4322 ///   ::= 'fence' 'singlethread'? AtomicOrdering
4323 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4324   AtomicOrdering Ordering = NotAtomic;
4325   SynchronizationScope Scope = CrossThread;
4326   if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4327     return true;
4328
4329   if (Ordering == Unordered)
4330     return TokError("fence cannot be unordered");
4331   if (Ordering == Monotonic)
4332     return TokError("fence cannot be monotonic");
4333
4334   Inst = new FenceInst(Context, Ordering, Scope);
4335   return InstNormal;
4336 }
4337
4338 /// ParseGetElementPtr
4339 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4340 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4341   Value *Ptr = nullptr;
4342   Value *Val = nullptr;
4343   LocTy Loc, EltLoc;
4344
4345   bool InBounds = EatIfPresent(lltok::kw_inbounds);
4346
4347   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4348
4349   Type *BaseType = Ptr->getType();
4350   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4351   if (!BasePointerType)
4352     return Error(Loc, "base of getelementptr must be a pointer");
4353
4354   SmallVector<Value*, 16> Indices;
4355   bool AteExtraComma = false;
4356   while (EatIfPresent(lltok::comma)) {
4357     if (Lex.getKind() == lltok::MetadataVar) {
4358       AteExtraComma = true;
4359       break;
4360     }
4361     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4362     if (!Val->getType()->getScalarType()->isIntegerTy())
4363       return Error(EltLoc, "getelementptr index must be an integer");
4364     if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4365       return Error(EltLoc, "getelementptr index type missmatch");
4366     if (Val->getType()->isVectorTy()) {
4367       unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4368       unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4369       if (ValNumEl != PtrNumEl)
4370         return Error(EltLoc,
4371           "getelementptr vector index has a wrong number of elements");
4372     }
4373     Indices.push_back(Val);
4374   }
4375
4376   if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4377     return Error(Loc, "base element of getelementptr must be sized");
4378
4379   if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4380     return Error(Loc, "invalid getelementptr indices");
4381   Inst = GetElementPtrInst::Create(Ptr, Indices);
4382   if (InBounds)
4383     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4384   return AteExtraComma ? InstExtraComma : InstNormal;
4385 }
4386
4387 /// ParseExtractValue
4388 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
4389 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4390   Value *Val; LocTy Loc;
4391   SmallVector<unsigned, 4> Indices;
4392   bool AteExtraComma;
4393   if (ParseTypeAndValue(Val, Loc, PFS) ||
4394       ParseIndexList(Indices, AteExtraComma))
4395     return true;
4396
4397   if (!Val->getType()->isAggregateType())
4398     return Error(Loc, "extractvalue operand must be aggregate type");
4399
4400   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4401     return Error(Loc, "invalid indices for extractvalue");
4402   Inst = ExtractValueInst::Create(Val, Indices);
4403   return AteExtraComma ? InstExtraComma : InstNormal;
4404 }
4405
4406 /// ParseInsertValue
4407 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4408 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4409   Value *Val0, *Val1; LocTy Loc0, Loc1;
4410   SmallVector<unsigned, 4> Indices;
4411   bool AteExtraComma;
4412   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4413       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4414       ParseTypeAndValue(Val1, Loc1, PFS) ||
4415       ParseIndexList(Indices, AteExtraComma))
4416     return true;
4417
4418   if (!Val0->getType()->isAggregateType())
4419     return Error(Loc0, "insertvalue operand must be aggregate type");
4420
4421   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4422     return Error(Loc0, "invalid indices for insertvalue");
4423   Inst = InsertValueInst::Create(Val0, Val1, Indices);
4424   return AteExtraComma ? InstExtraComma : InstNormal;
4425 }
4426
4427 //===----------------------------------------------------------------------===//
4428 // Embedded metadata.
4429 //===----------------------------------------------------------------------===//
4430
4431 /// ParseMDNodeVector
4432 ///   ::= Element (',' Element)*
4433 /// Element
4434 ///   ::= 'null' | TypeAndValue
4435 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4436                                  PerFunctionState *PFS) {
4437   // Check for an empty list.
4438   if (Lex.getKind() == lltok::rbrace)
4439     return false;
4440
4441   do {
4442     // Null is a special case since it is typeless.
4443     if (EatIfPresent(lltok::kw_null)) {
4444       Elts.push_back(nullptr);
4445       continue;
4446     }
4447
4448     Value *V = nullptr;
4449     if (ParseTypeAndValue(V, PFS)) return true;
4450     Elts.push_back(V);
4451   } while (EatIfPresent(lltok::comma));
4452
4453   return false;
4454 }