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