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