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