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