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