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