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