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