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