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