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