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