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