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