1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Streams.h"
35 // The following is a gross hack. In order to rid the libAsmParser library of
36 // exceptions, we have to have a way of getting the yyparse function to go into
37 // an error situation. So, whenever we want an error to occur, the GenerateError
38 // function (see bottom of file) sets TriggerError. Then, at the end of each
39 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
40 // (a goto) to put YACC in error state. Furthermore, several calls to
41 // GenerateError are made from inside productions and they must simulate the
42 // previous exception behavior by exiting the production immediately. We have
43 // replaced these with the GEN_ERROR macro which calls GeneratError and then
44 // immediately invokes YYERROR. This would be so much cleaner if it was a
45 // recursive descent parser.
46 static bool TriggerError = false;
47 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
48 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
50 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
51 int yylex(); // declaration" of xxx warnings.
55 std::string CurFilename;
58 Debug("debug-yacc", cl::desc("Print yacc debug state changes"),
59 cl::Hidden, cl::init(false));
64 static Module *ParserResult;
66 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
67 // relating to upreferences in the input stream.
69 //#define DEBUG_UPREFS 1
71 #define UR_OUT(X) cerr << X
76 #define YYERROR_VERBOSE 1
78 static GlobalVariable *CurGV;
81 // This contains info used when building the body of a function. It is
82 // destroyed when the function is completed.
84 typedef std::vector<Value *> ValueList; // Numbered defs
87 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
88 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
90 static struct PerModuleInfo {
91 Module *CurrentModule;
92 std::map<const Type *, ValueList> Values; // Module level numbered definitions
93 std::map<const Type *,ValueList> LateResolveValues;
94 std::vector<PATypeHolder> Types;
95 std::map<ValID, PATypeHolder> LateResolveTypes;
97 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
98 /// how they were referenced and on which line of the input they came from so
99 /// that we can resolve them later and print error messages as appropriate.
100 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
102 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
103 // references to global values. Global values may be referenced before they
104 // are defined, and if so, the temporary object that they represent is held
105 // here. This is used for forward references of GlobalValues.
107 typedef std::map<std::pair<const PointerType *,
108 ValID>, GlobalValue*> GlobalRefsType;
109 GlobalRefsType GlobalRefs;
112 // If we could not resolve some functions at function compilation time
113 // (calls to functions before they are defined), resolve them now... Types
114 // are resolved when the constant pool has been completely parsed.
116 ResolveDefinitions(LateResolveValues);
120 // Check to make sure that all global value forward references have been
123 if (!GlobalRefs.empty()) {
124 std::string UndefinedReferences = "Unresolved global references exist:\n";
126 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
128 UndefinedReferences += " " + I->first.first->getDescription() + " " +
129 I->first.second.getName() + "\n";
131 GenerateError(UndefinedReferences);
135 Values.clear(); // Clear out function local definitions
140 // GetForwardRefForGlobal - Check to see if there is a forward reference
141 // for this global. If so, remove it from the GlobalRefs map and return it.
142 // If not, just return null.
143 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
144 // Check to see if there is a forward reference to this global variable...
145 // if there is, eliminate it and patch the reference to use the new def'n.
146 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147 GlobalValue *Ret = 0;
148 if (I != GlobalRefs.end()) {
155 bool TypeIsUnresolved(PATypeHolder* PATy) {
156 // If it isn't abstract, its resolved
157 const Type* Ty = PATy->get();
158 if (!Ty->isAbstract())
160 // Traverse the type looking for abstract types. If it isn't abstract then
161 // we don't need to traverse that leg of the type.
162 std::vector<const Type*> WorkList, SeenList;
163 WorkList.push_back(Ty);
164 while (!WorkList.empty()) {
165 const Type* Ty = WorkList.back();
166 SeenList.push_back(Ty);
168 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
169 // Check to see if this is an unresolved type
170 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
171 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
172 for ( ; I != E; ++I) {
173 if (I->second.get() == OpTy)
176 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
177 const Type* TheTy = SeqTy->getElementType();
178 if (TheTy->isAbstract() && TheTy != Ty) {
179 std::vector<const Type*>::iterator I = SeenList.begin(),
185 WorkList.push_back(TheTy);
187 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
188 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
189 const Type* TheTy = StrTy->getElementType(i);
190 if (TheTy->isAbstract() && TheTy != Ty) {
191 std::vector<const Type*>::iterator I = SeenList.begin(),
197 WorkList.push_back(TheTy);
208 static struct PerFunctionInfo {
209 Function *CurrentFunction; // Pointer to current function being created
211 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
212 std::map<const Type*, ValueList> LateResolveValues;
213 bool isDeclare; // Is this function a forward declararation?
214 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
215 GlobalValue::VisibilityTypes Visibility;
217 /// BBForwardRefs - When we see forward references to basic blocks, keep
218 /// track of them here.
219 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
220 std::vector<BasicBlock*> NumberedBlocks;
223 inline PerFunctionInfo() {
226 Linkage = GlobalValue::ExternalLinkage;
227 Visibility = GlobalValue::DefaultVisibility;
230 inline void FunctionStart(Function *M) {
235 void FunctionDone() {
236 NumberedBlocks.clear();
238 // Any forward referenced blocks left?
239 if (!BBForwardRefs.empty()) {
240 GenerateError("Undefined reference to label " +
241 BBForwardRefs.begin()->first->getName());
245 // Resolve all forward references now.
246 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
248 Values.clear(); // Clear out function local definitions
251 Linkage = GlobalValue::ExternalLinkage;
252 Visibility = GlobalValue::DefaultVisibility;
254 } CurFun; // Info for the current function...
256 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
259 //===----------------------------------------------------------------------===//
260 // Code to handle definitions of all the types
261 //===----------------------------------------------------------------------===//
263 static int InsertValue(Value *V,
264 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
265 if (V->hasName()) return -1; // Is this a numbered definition?
267 // Yes, insert the value into the value table...
268 ValueList &List = ValueTab[V->getType()];
270 return List.size()-1;
273 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
275 case ValID::LocalID: // Is it a numbered definition?
276 // Module constants occupy the lowest numbered slots...
277 if (D.Num < CurModule.Types.size())
278 return CurModule.Types[D.Num];
280 case ValID::LocalName: // Is it a named definition?
281 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
282 D.destroy(); // Free old strdup'd memory...
287 GenerateError("Internal parser error: Invalid symbol type reference");
291 // If we reached here, we referenced either a symbol that we don't know about
292 // or an id number that hasn't been read yet. We may be referencing something
293 // forward, so just create an entry to be resolved later and get to it...
295 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
298 if (inFunctionScope()) {
299 if (D.Type == ValID::LocalName) {
300 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
303 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
308 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
309 if (I != CurModule.LateResolveTypes.end())
312 Type *Typ = OpaqueType::get();
313 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
317 // getValNonImprovising - Look up the value specified by the provided type and
318 // the provided ValID. If the value exists and has already been defined, return
319 // it. Otherwise return null.
321 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
322 if (isa<FunctionType>(Ty)) {
323 GenerateError("Functions are not values and "
324 "must be referenced as pointers");
329 case ValID::LocalID: { // Is it a numbered definition?
330 // Module constants occupy the lowest numbered slots.
331 std::map<const Type*,ValueList>::iterator VI = CurFun.Values.find(Ty);
332 // Make sure that our type is within bounds.
333 if (VI == CurFun.Values.end()) return 0;
335 // Check that the number is within bounds.
336 if (D.Num >= VI->second.size()) return 0;
338 return VI->second[D.Num];
340 case ValID::GlobalID: { // Is it a numbered definition?
341 unsigned Num = D.Num;
343 // Module constants occupy the lowest numbered slots...
344 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
345 if (VI == CurModule.Values.end())
347 if (D.Num >= VI->second.size())
349 return VI->second[Num];
352 case ValID::LocalName: { // Is it a named definition?
353 if (!inFunctionScope())
355 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
356 Value *N = SymTab.lookup(D.Name);
359 if (N->getType() != Ty)
362 D.destroy(); // Free old strdup'd memory...
365 case ValID::GlobalName: { // Is it a named definition?
366 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
367 Value *N = SymTab.lookup(D.Name);
370 if (N->getType() != Ty)
373 D.destroy(); // Free old strdup'd memory...
377 // Check to make sure that "Ty" is an integral type, and that our
378 // value will fit into the specified type...
379 case ValID::ConstSIntVal: // Is it a constant pool reference??
380 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
381 GenerateError("Signed integral constant '" +
382 itostr(D.ConstPool64) + "' is invalid for type '" +
383 Ty->getDescription() + "'");
386 return ConstantInt::get(Ty, D.ConstPool64);
388 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
389 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
390 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
391 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
392 "' is invalid or out of range");
394 } else { // This is really a signed reference. Transmogrify.
395 return ConstantInt::get(Ty, D.ConstPool64);
398 return ConstantInt::get(Ty, D.UConstPool64);
401 case ValID::ConstFPVal: // Is it a floating point const pool reference?
402 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
403 GenerateError("FP constant invalid for type");
406 return ConstantFP::get(Ty, D.ConstPoolFP);
408 case ValID::ConstNullVal: // Is it a null value?
409 if (!isa<PointerType>(Ty)) {
410 GenerateError("Cannot create a a non pointer null");
413 return ConstantPointerNull::get(cast<PointerType>(Ty));
415 case ValID::ConstUndefVal: // Is it an undef value?
416 return UndefValue::get(Ty);
418 case ValID::ConstZeroVal: // Is it a zero value?
419 return Constant::getNullValue(Ty);
421 case ValID::ConstantVal: // Fully resolved constant?
422 if (D.ConstantValue->getType() != Ty) {
423 GenerateError("Constant expression type different from required type");
426 return D.ConstantValue;
428 case ValID::InlineAsmVal: { // Inline asm expression
429 const PointerType *PTy = dyn_cast<PointerType>(Ty);
430 const FunctionType *FTy =
431 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
432 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
433 GenerateError("Invalid type for asm constraint string");
436 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
437 D.IAD->HasSideEffects);
438 D.destroy(); // Free InlineAsmDescriptor.
442 assert(0 && "Unhandled case!");
446 assert(0 && "Unhandled case!");
450 // getVal - This function is identical to getValNonImprovising, except that if a
451 // value is not already defined, it "improvises" by creating a placeholder var
452 // that looks and acts just like the requested variable. When the value is
453 // defined later, all uses of the placeholder variable are replaced with the
456 static Value *getVal(const Type *Ty, const ValID &ID) {
457 if (Ty == Type::LabelTy) {
458 GenerateError("Cannot use a basic block here");
462 // See if the value has already been defined.
463 Value *V = getValNonImprovising(Ty, ID);
465 if (TriggerError) return 0;
467 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
468 GenerateError("Invalid use of a composite type");
472 // If we reached here, we referenced either a symbol that we don't know about
473 // or an id number that hasn't been read yet. We may be referencing something
474 // forward, so just create an entry to be resolved later and get to it...
476 V = new Argument(Ty);
478 // Remember where this forward reference came from. FIXME, shouldn't we try
479 // to recycle these things??
480 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
483 if (inFunctionScope())
484 InsertValue(V, CurFun.LateResolveValues);
486 InsertValue(V, CurModule.LateResolveValues);
490 /// getBBVal - This is used for two purposes:
491 /// * If isDefinition is true, a new basic block with the specified ID is being
493 /// * If isDefinition is true, this is a reference to a basic block, which may
494 /// or may not be a forward reference.
496 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
497 assert(inFunctionScope() && "Can't get basic block at global scope!");
503 GenerateError("Illegal label reference " + ID.getName());
505 case ValID::LocalID: // Is it a numbered definition?
506 if (ID.Num >= CurFun.NumberedBlocks.size())
507 CurFun.NumberedBlocks.resize(ID.Num+1);
508 BB = CurFun.NumberedBlocks[ID.Num];
510 case ValID::LocalName: // Is it a named definition?
512 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
513 if (N && N->getType()->getTypeID() == Type::LabelTyID)
514 BB = cast<BasicBlock>(N);
518 // See if the block has already been defined.
520 // If this is the definition of the block, make sure the existing value was
521 // just a forward reference. If it was a forward reference, there will be
522 // an entry for it in the PlaceHolderInfo map.
523 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
524 // The existing value was a definition, not a forward reference.
525 GenerateError("Redefinition of label " + ID.getName());
529 ID.destroy(); // Free strdup'd memory.
533 // Otherwise this block has not been seen before.
534 BB = new BasicBlock("", CurFun.CurrentFunction);
535 if (ID.Type == ValID::LocalName) {
536 BB->setName(ID.Name);
538 CurFun.NumberedBlocks[ID.Num] = BB;
541 // If this is not a definition, keep track of it so we can use it as a forward
544 // Remember where this forward reference came from.
545 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
547 // The forward declaration could have been inserted anywhere in the
548 // function: insert it into the correct place now.
549 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
550 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
557 //===----------------------------------------------------------------------===//
558 // Code to handle forward references in instructions
559 //===----------------------------------------------------------------------===//
561 // This code handles the late binding needed with statements that reference
562 // values not defined yet... for example, a forward branch, or the PHI node for
565 // This keeps a table (CurFun.LateResolveValues) of all such forward references
566 // and back patchs after we are done.
569 // ResolveDefinitions - If we could not resolve some defs at parsing
570 // time (forward branches, phi functions for loops, etc...) resolve the
574 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
575 std::map<const Type*,ValueList> *FutureLateResolvers) {
576 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
577 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
578 E = LateResolvers.end(); LRI != E; ++LRI) {
579 ValueList &List = LRI->second;
580 while (!List.empty()) {
581 Value *V = List.back();
584 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
585 CurModule.PlaceHolderInfo.find(V);
586 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
588 ValID &DID = PHI->second.first;
590 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
594 V->replaceAllUsesWith(TheRealValue);
596 CurModule.PlaceHolderInfo.erase(PHI);
597 } else if (FutureLateResolvers) {
598 // Functions have their unresolved items forwarded to the module late
600 InsertValue(V, *FutureLateResolvers);
602 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
603 GenerateError("Reference to an invalid definition: '" +DID.getName()+
604 "' of type '" + V->getType()->getDescription() + "'",
608 GenerateError("Reference to an invalid definition: #" +
609 itostr(DID.Num) + " of type '" +
610 V->getType()->getDescription() + "'",
618 LateResolvers.clear();
621 // ResolveTypeTo - A brand new type was just declared. This means that (if
622 // name is not null) things referencing Name can be resolved. Otherwise, things
623 // refering to the number can be resolved. Do this now.
625 static void ResolveTypeTo(char *Name, const Type *ToTy) {
627 if (Name) D = ValID::createLocalName(Name);
628 else D = ValID::createLocalID(CurModule.Types.size());
630 std::map<ValID, PATypeHolder>::iterator I =
631 CurModule.LateResolveTypes.find(D);
632 if (I != CurModule.LateResolveTypes.end()) {
633 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
634 CurModule.LateResolveTypes.erase(I);
638 // setValueName - Set the specified value to the name given. The name may be
639 // null potentially, in which case this is a noop. The string passed in is
640 // assumed to be a malloc'd string buffer, and is free'd by this function.
642 static void setValueName(Value *V, char *NameStr) {
643 if (!NameStr) return;
644 std::string Name(NameStr); // Copy string
645 free(NameStr); // Free old string
647 if (V->getType() == Type::VoidTy) {
648 GenerateError("Can't assign name '" + Name+"' to value with void type");
652 assert(inFunctionScope() && "Must be in function scope!");
653 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
654 if (ST.lookup(Name)) {
655 GenerateError("Redefinition of value '" + Name + "' of type '" +
656 V->getType()->getDescription() + "'");
664 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
665 /// this is a declaration, otherwise it is a definition.
666 static GlobalVariable *
667 ParseGlobalVariable(char *NameStr,
668 GlobalValue::LinkageTypes Linkage,
669 GlobalValue::VisibilityTypes Visibility,
670 bool isConstantGlobal, const Type *Ty,
671 Constant *Initializer) {
672 if (isa<FunctionType>(Ty)) {
673 GenerateError("Cannot declare global vars of function type");
677 const PointerType *PTy = PointerType::get(Ty);
681 Name = NameStr; // Copy string
682 free(NameStr); // Free old string
685 // See if this global value was forward referenced. If so, recycle the
689 ID = ValID::createGlobalName((char*)Name.c_str());
691 ID = ValID::createGlobalID(CurModule.Values[PTy].size());
694 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
695 // Move the global to the end of the list, from whereever it was
696 // previously inserted.
697 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
698 CurModule.CurrentModule->getGlobalList().remove(GV);
699 CurModule.CurrentModule->getGlobalList().push_back(GV);
700 GV->setInitializer(Initializer);
701 GV->setLinkage(Linkage);
702 GV->setVisibility(Visibility);
703 GV->setConstant(isConstantGlobal);
704 InsertValue(GV, CurModule.Values);
708 // If this global has a name
710 // if the global we're parsing has an initializer (is a definition) and
711 // has external linkage.
712 if (Initializer && Linkage != GlobalValue::InternalLinkage)
713 // If there is already a global with external linkage with this name
714 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
715 // If we allow this GVar to get created, it will be renamed in the
716 // symbol table because it conflicts with an existing GVar. We can't
717 // allow redefinition of GVars whose linking indicates that their name
718 // must stay the same. Issue the error.
719 GenerateError("Redefinition of global variable named '" + Name +
720 "' of type '" + Ty->getDescription() + "'");
725 // Otherwise there is no existing GV to use, create one now.
727 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
728 CurModule.CurrentModule);
729 GV->setVisibility(Visibility);
730 InsertValue(GV, CurModule.Values);
734 // setTypeName - Set the specified type to the name given. The name may be
735 // null potentially, in which case this is a noop. The string passed in is
736 // assumed to be a malloc'd string buffer, and is freed by this function.
738 // This function returns true if the type has already been defined, but is
739 // allowed to be redefined in the specified context. If the name is a new name
740 // for the type plane, it is inserted and false is returned.
741 static bool setTypeName(const Type *T, char *NameStr) {
742 assert(!inFunctionScope() && "Can't give types function-local names!");
743 if (NameStr == 0) return false;
745 std::string Name(NameStr); // Copy string
746 free(NameStr); // Free old string
748 // We don't allow assigning names to void type
749 if (T == Type::VoidTy) {
750 GenerateError("Can't assign name '" + Name + "' to the void type");
754 // Set the type name, checking for conflicts as we do so.
755 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
757 if (AlreadyExists) { // Inserting a name that is already defined???
758 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
759 assert(Existing && "Conflict but no matching type?!");
761 // There is only one case where this is allowed: when we are refining an
762 // opaque type. In this case, Existing will be an opaque type.
763 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
764 // We ARE replacing an opaque type!
765 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
769 // Otherwise, this is an attempt to redefine a type. That's okay if
770 // the redefinition is identical to the original. This will be so if
771 // Existing and T point to the same Type object. In this one case we
772 // allow the equivalent redefinition.
773 if (Existing == T) return true; // Yes, it's equal.
775 // Any other kind of (non-equivalent) redefinition is an error.
776 GenerateError("Redefinition of type named '" + Name + "' of type '" +
777 T->getDescription() + "'");
783 //===----------------------------------------------------------------------===//
784 // Code for handling upreferences in type names...
787 // TypeContains - Returns true if Ty directly contains E in it.
789 static bool TypeContains(const Type *Ty, const Type *E) {
790 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
791 E) != Ty->subtype_end();
796 // NestingLevel - The number of nesting levels that need to be popped before
797 // this type is resolved.
798 unsigned NestingLevel;
800 // LastContainedTy - This is the type at the current binding level for the
801 // type. Every time we reduce the nesting level, this gets updated.
802 const Type *LastContainedTy;
804 // UpRefTy - This is the actual opaque type that the upreference is
808 UpRefRecord(unsigned NL, OpaqueType *URTy)
809 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
813 // UpRefs - A list of the outstanding upreferences that need to be resolved.
814 static std::vector<UpRefRecord> UpRefs;
816 /// HandleUpRefs - Every time we finish a new layer of types, this function is
817 /// called. It loops through the UpRefs vector, which is a list of the
818 /// currently active types. For each type, if the up reference is contained in
819 /// the newly completed type, we decrement the level count. When the level
820 /// count reaches zero, the upreferenced type is the type that is passed in:
821 /// thus we can complete the cycle.
823 static PATypeHolder HandleUpRefs(const Type *ty) {
824 // If Ty isn't abstract, or if there are no up-references in it, then there is
825 // nothing to resolve here.
826 if (!ty->isAbstract() || UpRefs.empty()) return ty;
829 UR_OUT("Type '" << Ty->getDescription() <<
830 "' newly formed. Resolving upreferences.\n" <<
831 UpRefs.size() << " upreferences active!\n");
833 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
834 // to zero), we resolve them all together before we resolve them to Ty. At
835 // the end of the loop, if there is anything to resolve to Ty, it will be in
837 OpaqueType *TypeToResolve = 0;
839 for (unsigned i = 0; i != UpRefs.size(); ++i) {
840 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
841 << UpRefs[i].second->getDescription() << ") = "
842 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
843 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
844 // Decrement level of upreference
845 unsigned Level = --UpRefs[i].NestingLevel;
846 UpRefs[i].LastContainedTy = Ty;
847 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
848 if (Level == 0) { // Upreference should be resolved!
849 if (!TypeToResolve) {
850 TypeToResolve = UpRefs[i].UpRefTy;
852 UR_OUT(" * Resolving upreference for "
853 << UpRefs[i].second->getDescription() << "\n";
854 std::string OldName = UpRefs[i].UpRefTy->getDescription());
855 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
856 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
857 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
859 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
860 --i; // Do not skip the next element...
866 UR_OUT(" * Resolving upreference for "
867 << UpRefs[i].second->getDescription() << "\n";
868 std::string OldName = TypeToResolve->getDescription());
869 TypeToResolve->refineAbstractTypeTo(Ty);
875 //===----------------------------------------------------------------------===//
876 // RunVMAsmParser - Define an interface to this parser
877 //===----------------------------------------------------------------------===//
879 static Module* RunParser(Module * M);
881 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
884 CurFilename = Filename;
885 return RunParser(new Module(CurFilename));
888 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
889 set_scan_string(AsmString);
891 CurFilename = "from_memory";
893 return RunParser(new Module (CurFilename));
902 llvm::Module *ModuleVal;
903 llvm::Function *FunctionVal;
904 llvm::BasicBlock *BasicBlockVal;
905 llvm::TerminatorInst *TermInstVal;
906 llvm::Instruction *InstVal;
907 llvm::Constant *ConstVal;
909 const llvm::Type *PrimType;
910 std::list<llvm::PATypeHolder> *TypeList;
911 llvm::PATypeHolder *TypeVal;
912 llvm::Value *ValueVal;
913 std::vector<llvm::Value*> *ValueList;
914 llvm::ArgListType *ArgList;
915 llvm::TypeWithAttrs TypeWithAttrs;
916 llvm::TypeWithAttrsList *TypeWithAttrsList;
917 llvm::ValueRefList *ValueRefList;
919 // Represent the RHS of PHI node
920 std::list<std::pair<llvm::Value*,
921 llvm::BasicBlock*> > *PHIList;
922 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
923 std::vector<llvm::Constant*> *ConstVector;
925 llvm::GlobalValue::LinkageTypes Linkage;
926 llvm::GlobalValue::VisibilityTypes Visibility;
927 llvm::FunctionType::ParameterAttributes ParamAttrs;
928 llvm::APInt *APIntVal;
936 char *StrVal; // This memory is strdup'd!
937 llvm::ValID ValIDVal; // strdup'd memory maybe!
939 llvm::Instruction::BinaryOps BinaryOpVal;
940 llvm::Instruction::TermOps TermOpVal;
941 llvm::Instruction::MemoryOps MemOpVal;
942 llvm::Instruction::CastOps CastOpVal;
943 llvm::Instruction::OtherOps OtherOpVal;
944 llvm::ICmpInst::Predicate IPredicate;
945 llvm::FCmpInst::Predicate FPredicate;
948 %type <ModuleVal> Module
949 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
950 %type <BasicBlockVal> BasicBlock InstructionList
951 %type <TermInstVal> BBTerminatorInst
952 %type <InstVal> Inst InstVal MemoryInst
953 %type <ConstVal> ConstVal ConstExpr
954 %type <ConstVector> ConstVector
955 %type <ArgList> ArgList ArgListH
956 %type <PHIList> PHIList
957 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
958 %type <ValueList> IndexList // For GEP indices
959 %type <TypeList> TypeListI
960 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
961 %type <TypeWithAttrs> ArgType
962 %type <JumpTable> JumpTable
963 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
964 %type <BoolVal> OptVolatile // 'volatile' or not
965 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
966 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
967 %type <Linkage> GVInternalLinkage GVExternalLinkage
968 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
969 %type <Visibility> GVVisibilityStyle
971 // ValueRef - Unresolved reference to a definition or BB
972 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
973 %type <ValueVal> ResolvedVal // <type> <valref> pair
974 // Tokens and types for handling constant integer values
976 // ESINT64VAL - A negative number within long long range
977 %token <SInt64Val> ESINT64VAL
979 // EUINT64VAL - A positive number within uns. long long range
980 %token <UInt64Val> EUINT64VAL
982 // ESAPINTVAL - A negative number with arbitrary precision
983 %token <APIntVal> ESAPINTVAL
985 // EUAPINTVAL - A positive number with arbitrary precision
986 %token <APIntVal> EUAPINTVAL
988 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
989 %token <FPVal> FPVAL // Float or Double constant
992 %type <TypeVal> Types ResultTypes
993 %type <PrimType> IntType FPType PrimType // Classifications
994 %token <PrimType> VOID INTTYPE
995 %token <PrimType> FLOAT DOUBLE LABEL
998 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR STRINGCONSTANT ATSTRINGCONSTANT
999 %type <StrVal> LocalName OptLocalName OptLocalAssign
1000 %type <StrVal> GlobalName OptGlobalAssign
1001 %type <UIntVal> OptAlign OptCAlign
1002 %type <StrVal> OptSection SectionString
1004 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1005 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
1006 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1007 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1008 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
1009 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1010 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1012 %type <UIntVal> OptCallingConv
1013 %type <ParamAttrs> OptParamAttrs ParamAttr
1014 %type <ParamAttrs> OptFuncAttrs FuncAttr
1016 // Basic Block Terminating Operators
1017 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1020 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1021 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1022 %token <BinaryOpVal> SHL LSHR ASHR
1024 %token <OtherOpVal> ICMP FCMP
1025 %type <IPredicate> IPredicates
1026 %type <FPredicate> FPredicates
1027 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1028 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1030 // Memory Instructions
1031 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1034 %type <CastOpVal> CastOps
1035 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1036 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1039 %token <OtherOpVal> PHI_TOK SELECT VAARG
1040 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1042 // Function Attributes
1043 %token NORETURN INREG SRET
1045 // Visibility Styles
1046 %token DEFAULT HIDDEN
1052 // Operations that are notably excluded from this list include:
1053 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1055 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1056 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1057 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1058 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1061 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1062 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1063 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1064 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1065 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1069 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1070 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1071 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1072 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1073 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1074 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1075 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1076 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1077 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1080 // These are some types that allow classification if we only want a particular
1081 // thing... for example, only a signed, unsigned, or integral type.
1083 FPType : FLOAT | DOUBLE;
1085 LocalName : LOCALVAR | STRINGCONSTANT;
1086 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1088 /// OptLocalAssign - Value producing statements have an optional assignment
1090 OptLocalAssign : LocalName '=' {
1099 GlobalName : GLOBALVAR | ATSTRINGCONSTANT;
1101 OptGlobalAssign : GlobalName '=' {
1111 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1112 | WEAK { $$ = GlobalValue::WeakLinkage; }
1113 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1114 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1115 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1119 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1120 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1121 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1125 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1126 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1129 FunctionDeclareLinkage
1130 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1131 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1132 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1135 FunctionDefineLinkage
1136 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1137 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1138 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1139 | WEAK { $$ = GlobalValue::WeakLinkage; }
1140 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1143 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1144 CCC_TOK { $$ = CallingConv::C; } |
1145 FASTCC_TOK { $$ = CallingConv::Fast; } |
1146 COLDCC_TOK { $$ = CallingConv::Cold; } |
1147 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1148 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1150 if ((unsigned)$2 != $2)
1151 GEN_ERROR("Calling conv too large");
1156 ParamAttr : ZEXT { $$ = FunctionType::ZExtAttribute; }
1157 | SEXT { $$ = FunctionType::SExtAttribute; }
1158 | INREG { $$ = FunctionType::InRegAttribute; }
1159 | SRET { $$ = FunctionType::StructRetAttribute; }
1162 OptParamAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1163 | OptParamAttrs ParamAttr {
1164 $$ = FunctionType::ParameterAttributes($1 | $2);
1168 FuncAttr : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1172 OptFuncAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1173 | OptFuncAttrs FuncAttr {
1174 $$ = FunctionType::ParameterAttributes($1 | $2);
1178 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1179 // a comma before it.
1180 OptAlign : /*empty*/ { $$ = 0; } |
1183 if ($$ != 0 && !isPowerOf2_32($$))
1184 GEN_ERROR("Alignment must be a power of two");
1187 OptCAlign : /*empty*/ { $$ = 0; } |
1188 ',' ALIGN EUINT64VAL {
1190 if ($$ != 0 && !isPowerOf2_32($$))
1191 GEN_ERROR("Alignment must be a power of two");
1196 SectionString : SECTION STRINGCONSTANT {
1197 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1198 if ($2[i] == '"' || $2[i] == '\\')
1199 GEN_ERROR("Invalid character in section name");
1204 OptSection : /*empty*/ { $$ = 0; } |
1205 SectionString { $$ = $1; };
1207 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1208 // is set to be the global we are processing.
1210 GlobalVarAttributes : /* empty */ {} |
1211 ',' GlobalVarAttribute GlobalVarAttributes {};
1212 GlobalVarAttribute : SectionString {
1213 CurGV->setSection($1);
1217 | ALIGN EUINT64VAL {
1218 if ($2 != 0 && !isPowerOf2_32($2))
1219 GEN_ERROR("Alignment must be a power of two");
1220 CurGV->setAlignment($2);
1224 //===----------------------------------------------------------------------===//
1225 // Types includes all predefined types... except void, because it can only be
1226 // used in specific contexts (function returning void for example).
1228 // Derived types are added later...
1230 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1234 $$ = new PATypeHolder(OpaqueType::get());
1238 $$ = new PATypeHolder($1);
1241 | Types '*' { // Pointer type?
1242 if (*$1 == Type::LabelTy)
1243 GEN_ERROR("Cannot form a pointer to a basic block");
1244 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1248 | SymbolicValueRef { // Named types are also simple types...
1249 const Type* tmp = getTypeVal($1);
1251 $$ = new PATypeHolder(tmp);
1253 | '\\' EUINT64VAL { // Type UpReference
1254 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1255 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1256 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1257 $$ = new PATypeHolder(OT);
1258 UR_OUT("New Upreference!\n");
1261 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1262 std::vector<const Type*> Params;
1263 std::vector<FunctionType::ParameterAttributes> Attrs;
1264 Attrs.push_back($5);
1265 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1266 Params.push_back(I->Ty->get());
1267 if (I->Ty->get() != Type::VoidTy)
1268 Attrs.push_back(I->Attrs);
1270 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1271 if (isVarArg) Params.pop_back();
1273 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1274 delete $3; // Delete the argument list
1275 delete $1; // Delete the return type handle
1276 $$ = new PATypeHolder(HandleUpRefs(FT));
1279 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1280 std::vector<const Type*> Params;
1281 std::vector<FunctionType::ParameterAttributes> Attrs;
1282 Attrs.push_back($5);
1283 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1284 Params.push_back(I->Ty->get());
1285 if (I->Ty->get() != Type::VoidTy)
1286 Attrs.push_back(I->Attrs);
1288 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1289 if (isVarArg) Params.pop_back();
1291 FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1292 delete $3; // Delete the argument list
1293 $$ = new PATypeHolder(HandleUpRefs(FT));
1297 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1298 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1302 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1303 const llvm::Type* ElemTy = $4->get();
1304 if ((unsigned)$2 != $2)
1305 GEN_ERROR("Unsigned result not equal to signed result");
1306 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1307 GEN_ERROR("Element type of a VectorType must be primitive");
1308 if (!isPowerOf2_32($2))
1309 GEN_ERROR("Vector length should be a power of 2");
1310 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1314 | '{' TypeListI '}' { // Structure type?
1315 std::vector<const Type*> Elements;
1316 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1317 E = $2->end(); I != E; ++I)
1318 Elements.push_back(*I);
1320 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1324 | '{' '}' { // Empty structure type?
1325 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1328 | '<' '{' TypeListI '}' '>' {
1329 std::vector<const Type*> Elements;
1330 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1331 E = $3->end(); I != E; ++I)
1332 Elements.push_back(*I);
1334 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1338 | '<' '{' '}' '>' { // Empty structure type?
1339 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1345 : Types OptParamAttrs {
1353 if (!UpRefs.empty())
1354 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1355 if (!(*$1)->isFirstClassType())
1356 GEN_ERROR("LLVM functions cannot return aggregate types");
1360 $$ = new PATypeHolder(Type::VoidTy);
1364 ArgTypeList : ArgType {
1365 $$ = new TypeWithAttrsList();
1369 | ArgTypeList ',' ArgType {
1370 ($$=$1)->push_back($3);
1377 | ArgTypeList ',' DOTDOTDOT {
1379 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1380 TWA.Ty = new PATypeHolder(Type::VoidTy);
1385 $$ = new TypeWithAttrsList;
1386 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1387 TWA.Ty = new PATypeHolder(Type::VoidTy);
1392 $$ = new TypeWithAttrsList();
1396 // TypeList - Used for struct declarations and as a basis for function type
1397 // declaration type lists
1400 $$ = new std::list<PATypeHolder>();
1401 $$->push_back(*$1); delete $1;
1404 | TypeListI ',' Types {
1405 ($$=$1)->push_back(*$3); delete $3;
1409 // ConstVal - The various declarations that go into the constant pool. This
1410 // production is used ONLY to represent constants that show up AFTER a 'const',
1411 // 'constant' or 'global' token at global scope. Constants that can be inlined
1412 // into other expressions (such as integers and constexprs) are handled by the
1413 // ResolvedVal, ValueRef and ConstValueRef productions.
1415 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1416 if (!UpRefs.empty())
1417 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1418 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1420 GEN_ERROR("Cannot make array constant with type: '" +
1421 (*$1)->getDescription() + "'");
1422 const Type *ETy = ATy->getElementType();
1423 int NumElements = ATy->getNumElements();
1425 // Verify that we have the correct size...
1426 if (NumElements != -1 && NumElements != (int)$3->size())
1427 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1428 utostr($3->size()) + " arguments, but has size of " +
1429 itostr(NumElements) + "");
1431 // Verify all elements are correct type!
1432 for (unsigned i = 0; i < $3->size(); i++) {
1433 if (ETy != (*$3)[i]->getType())
1434 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1435 ETy->getDescription() +"' as required!\nIt is of type '"+
1436 (*$3)[i]->getType()->getDescription() + "'.");
1439 $$ = ConstantArray::get(ATy, *$3);
1440 delete $1; delete $3;
1444 if (!UpRefs.empty())
1445 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1446 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1448 GEN_ERROR("Cannot make array constant with type: '" +
1449 (*$1)->getDescription() + "'");
1451 int NumElements = ATy->getNumElements();
1452 if (NumElements != -1 && NumElements != 0)
1453 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1454 " arguments, but has size of " + itostr(NumElements) +"");
1455 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1459 | Types 'c' STRINGCONSTANT {
1460 if (!UpRefs.empty())
1461 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1462 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1464 GEN_ERROR("Cannot make array constant with type: '" +
1465 (*$1)->getDescription() + "'");
1467 int NumElements = ATy->getNumElements();
1468 const Type *ETy = ATy->getElementType();
1469 char *EndStr = UnEscapeLexed($3, true);
1470 if (NumElements != -1 && NumElements != (EndStr-$3))
1471 GEN_ERROR("Can't build string constant of size " +
1472 itostr((int)(EndStr-$3)) +
1473 " when array has size " + itostr(NumElements) + "");
1474 std::vector<Constant*> Vals;
1475 if (ETy == Type::Int8Ty) {
1476 for (unsigned char *C = (unsigned char *)$3;
1477 C != (unsigned char*)EndStr; ++C)
1478 Vals.push_back(ConstantInt::get(ETy, *C));
1481 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1484 $$ = ConstantArray::get(ATy, Vals);
1488 | Types '<' ConstVector '>' { // Nonempty unsized arr
1489 if (!UpRefs.empty())
1490 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1491 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1493 GEN_ERROR("Cannot make packed constant with type: '" +
1494 (*$1)->getDescription() + "'");
1495 const Type *ETy = PTy->getElementType();
1496 int NumElements = PTy->getNumElements();
1498 // Verify that we have the correct size...
1499 if (NumElements != -1 && NumElements != (int)$3->size())
1500 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1501 utostr($3->size()) + " arguments, but has size of " +
1502 itostr(NumElements) + "");
1504 // Verify all elements are correct type!
1505 for (unsigned i = 0; i < $3->size(); i++) {
1506 if (ETy != (*$3)[i]->getType())
1507 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1508 ETy->getDescription() +"' as required!\nIt is of type '"+
1509 (*$3)[i]->getType()->getDescription() + "'.");
1512 $$ = ConstantVector::get(PTy, *$3);
1513 delete $1; delete $3;
1516 | Types '{' ConstVector '}' {
1517 const StructType *STy = dyn_cast<StructType>($1->get());
1519 GEN_ERROR("Cannot make struct constant with type: '" +
1520 (*$1)->getDescription() + "'");
1522 if ($3->size() != STy->getNumContainedTypes())
1523 GEN_ERROR("Illegal number of initializers for structure type");
1525 // Check to ensure that constants are compatible with the type initializer!
1526 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1527 if ((*$3)[i]->getType() != STy->getElementType(i))
1528 GEN_ERROR("Expected type '" +
1529 STy->getElementType(i)->getDescription() +
1530 "' for element #" + utostr(i) +
1531 " of structure initializer");
1533 // Check to ensure that Type is not packed
1534 if (STy->isPacked())
1535 GEN_ERROR("Unpacked Initializer to vector type '" + STy->getDescription() + "'");
1537 $$ = ConstantStruct::get(STy, *$3);
1538 delete $1; delete $3;
1542 if (!UpRefs.empty())
1543 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1544 const StructType *STy = dyn_cast<StructType>($1->get());
1546 GEN_ERROR("Cannot make struct constant with type: '" +
1547 (*$1)->getDescription() + "'");
1549 if (STy->getNumContainedTypes() != 0)
1550 GEN_ERROR("Illegal number of initializers for structure type");
1552 // Check to ensure that Type is not packed
1553 if (STy->isPacked())
1554 GEN_ERROR("Unpacked Initializer to vector type '" + STy->getDescription() + "'");
1556 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1560 | Types '<' '{' ConstVector '}' '>' {
1561 const StructType *STy = dyn_cast<StructType>($1->get());
1563 GEN_ERROR("Cannot make struct constant with type: '" +
1564 (*$1)->getDescription() + "'");
1566 if ($4->size() != STy->getNumContainedTypes())
1567 GEN_ERROR("Illegal number of initializers for structure type");
1569 // Check to ensure that constants are compatible with the type initializer!
1570 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1571 if ((*$4)[i]->getType() != STy->getElementType(i))
1572 GEN_ERROR("Expected type '" +
1573 STy->getElementType(i)->getDescription() +
1574 "' for element #" + utostr(i) +
1575 " of structure initializer");
1577 // Check to ensure that Type is packed
1578 if (!STy->isPacked())
1579 GEN_ERROR("Vector initializer to non-vector type '" +
1580 STy->getDescription() + "'");
1582 $$ = ConstantStruct::get(STy, *$4);
1583 delete $1; delete $4;
1586 | Types '<' '{' '}' '>' {
1587 if (!UpRefs.empty())
1588 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1589 const StructType *STy = dyn_cast<StructType>($1->get());
1591 GEN_ERROR("Cannot make struct constant with type: '" +
1592 (*$1)->getDescription() + "'");
1594 if (STy->getNumContainedTypes() != 0)
1595 GEN_ERROR("Illegal number of initializers for structure type");
1597 // Check to ensure that Type is packed
1598 if (!STy->isPacked())
1599 GEN_ERROR("Vector initializer to non-vector type '" +
1600 STy->getDescription() + "'");
1602 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1607 if (!UpRefs.empty())
1608 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1609 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1611 GEN_ERROR("Cannot make null pointer constant with type: '" +
1612 (*$1)->getDescription() + "'");
1614 $$ = ConstantPointerNull::get(PTy);
1619 if (!UpRefs.empty())
1620 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1621 $$ = UndefValue::get($1->get());
1625 | Types SymbolicValueRef {
1626 if (!UpRefs.empty())
1627 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1628 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1630 GEN_ERROR("Global const reference must be a pointer type");
1632 // ConstExprs can exist in the body of a function, thus creating
1633 // GlobalValues whenever they refer to a variable. Because we are in
1634 // the context of a function, getValNonImprovising will search the functions
1635 // symbol table instead of the module symbol table for the global symbol,
1636 // which throws things all off. To get around this, we just tell
1637 // getValNonImprovising that we are at global scope here.
1639 Function *SavedCurFn = CurFun.CurrentFunction;
1640 CurFun.CurrentFunction = 0;
1642 Value *V = getValNonImprovising(Ty, $2);
1645 CurFun.CurrentFunction = SavedCurFn;
1647 // If this is an initializer for a constant pointer, which is referencing a
1648 // (currently) undefined variable, create a stub now that shall be replaced
1649 // in the future with the right type of variable.
1652 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1653 const PointerType *PT = cast<PointerType>(Ty);
1655 // First check to see if the forward references value is already created!
1656 PerModuleInfo::GlobalRefsType::iterator I =
1657 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1659 if (I != CurModule.GlobalRefs.end()) {
1660 V = I->second; // Placeholder already exists, use it...
1664 if ($2.Type == ValID::GlobalName)
1666 else if ($2.Type != ValID::GlobalID)
1667 GEN_ERROR("Invalid reference to global");
1669 // Create the forward referenced global.
1671 if (const FunctionType *FTy =
1672 dyn_cast<FunctionType>(PT->getElementType())) {
1673 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1674 CurModule.CurrentModule);
1676 GV = new GlobalVariable(PT->getElementType(), false,
1677 GlobalValue::ExternalLinkage, 0,
1678 Name, CurModule.CurrentModule);
1681 // Keep track of the fact that we have a forward ref to recycle it
1682 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1687 $$ = cast<GlobalValue>(V);
1688 delete $1; // Free the type handle
1692 if (!UpRefs.empty())
1693 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1694 if ($1->get() != $2->getType())
1695 GEN_ERROR("Mismatched types for constant expression: " +
1696 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1701 | Types ZEROINITIALIZER {
1702 if (!UpRefs.empty())
1703 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1704 const Type *Ty = $1->get();
1705 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1706 GEN_ERROR("Cannot create a null initialized value of this type");
1707 $$ = Constant::getNullValue(Ty);
1711 | IntType ESINT64VAL { // integral constants
1712 if (!ConstantInt::isValueValidForType($1, $2))
1713 GEN_ERROR("Constant value doesn't fit in type");
1715 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1716 Val.sextOrTrunc(BitWidth);
1717 $$ = ConstantInt::get(Val);
1720 | IntType ESAPINTVAL { // arbitrary precision integer constants
1721 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1722 if ($2->getBitWidth() > BitWidth) {
1723 GEN_ERROR("Constant value does not fit in type");
1725 $2->sextOrTrunc(BitWidth);
1726 $$ = ConstantInt::get(*$2);
1730 | IntType EUINT64VAL { // integral constants
1731 if (!ConstantInt::isValueValidForType($1, $2))
1732 GEN_ERROR("Constant value doesn't fit in type");
1733 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1734 APInt Val(BitWidth, $2);
1735 $$ = ConstantInt::get(Val);
1738 | IntType EUAPINTVAL { // arbitrary precision integer constants
1739 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1740 if ($2->getBitWidth() > BitWidth) {
1741 GEN_ERROR("Constant value does not fit in type");
1743 $2->zextOrTrunc(BitWidth);
1744 $$ = ConstantInt::get(*$2);
1748 | INTTYPE TRUETOK { // Boolean constants
1749 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1750 $$ = ConstantInt::getTrue();
1753 | INTTYPE FALSETOK { // Boolean constants
1754 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1755 $$ = ConstantInt::getFalse();
1758 | FPType FPVAL { // Float & Double constants
1759 if (!ConstantFP::isValueValidForType($1, $2))
1760 GEN_ERROR("Floating point constant invalid for type");
1761 $$ = ConstantFP::get($1, $2);
1766 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1767 if (!UpRefs.empty())
1768 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1770 const Type *DestTy = $5->get();
1771 if (!CastInst::castIsValid($1, $3, DestTy))
1772 GEN_ERROR("invalid cast opcode for cast from '" +
1773 Val->getType()->getDescription() + "' to '" +
1774 DestTy->getDescription() + "'");
1775 $$ = ConstantExpr::getCast($1, $3, DestTy);
1778 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1779 if (!isa<PointerType>($3->getType()))
1780 GEN_ERROR("GetElementPtr requires a pointer operand");
1783 GetElementPtrInst::getIndexedType($3->getType(), &(*$4)[0], $4->size(),
1786 GEN_ERROR("Index list invalid for constant getelementptr");
1788 SmallVector<Constant*, 8> IdxVec;
1789 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1790 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1791 IdxVec.push_back(C);
1793 GEN_ERROR("Indices to constant getelementptr must be constants");
1797 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1800 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1801 if ($3->getType() != Type::Int1Ty)
1802 GEN_ERROR("Select condition must be of boolean type");
1803 if ($5->getType() != $7->getType())
1804 GEN_ERROR("Select operand types must match");
1805 $$ = ConstantExpr::getSelect($3, $5, $7);
1808 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1809 if ($3->getType() != $5->getType())
1810 GEN_ERROR("Binary operator types must match");
1812 $$ = ConstantExpr::get($1, $3, $5);
1814 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1815 if ($3->getType() != $5->getType())
1816 GEN_ERROR("Logical operator types must match");
1817 if (!$3->getType()->isInteger()) {
1818 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1819 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1820 GEN_ERROR("Logical operator requires integral operands");
1822 $$ = ConstantExpr::get($1, $3, $5);
1825 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1826 if ($4->getType() != $6->getType())
1827 GEN_ERROR("icmp operand types must match");
1828 $$ = ConstantExpr::getICmp($2, $4, $6);
1830 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1831 if ($4->getType() != $6->getType())
1832 GEN_ERROR("fcmp operand types must match");
1833 $$ = ConstantExpr::getFCmp($2, $4, $6);
1835 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1836 if (!ExtractElementInst::isValidOperands($3, $5))
1837 GEN_ERROR("Invalid extractelement operands");
1838 $$ = ConstantExpr::getExtractElement($3, $5);
1841 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1842 if (!InsertElementInst::isValidOperands($3, $5, $7))
1843 GEN_ERROR("Invalid insertelement operands");
1844 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1847 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1848 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1849 GEN_ERROR("Invalid shufflevector operands");
1850 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1855 // ConstVector - A list of comma separated constants.
1856 ConstVector : ConstVector ',' ConstVal {
1857 ($$ = $1)->push_back($3);
1861 $$ = new std::vector<Constant*>();
1867 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1868 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1871 //===----------------------------------------------------------------------===//
1872 // Rules to match Modules
1873 //===----------------------------------------------------------------------===//
1875 // Module rule: Capture the result of parsing the whole file into a result
1880 $$ = ParserResult = CurModule.CurrentModule;
1881 CurModule.ModuleDone();
1885 $$ = ParserResult = CurModule.CurrentModule;
1886 CurModule.ModuleDone();
1893 | DefinitionList Definition
1897 : DEFINE { CurFun.isDeclare = false; } Function {
1898 CurFun.FunctionDone();
1901 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1904 | MODULE ASM_TOK AsmBlock {
1908 // Emit an error if there are any unresolved types left.
1909 if (!CurModule.LateResolveTypes.empty()) {
1910 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1911 if (DID.Type == ValID::LocalName) {
1912 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1914 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1919 | OptLocalAssign TYPE Types {
1920 if (!UpRefs.empty())
1921 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1922 // Eagerly resolve types. This is not an optimization, this is a
1923 // requirement that is due to the fact that we could have this:
1925 // %list = type { %list * }
1926 // %list = type { %list * } ; repeated type decl
1928 // If types are not resolved eagerly, then the two types will not be
1929 // determined to be the same type!
1931 ResolveTypeTo($1, *$3);
1933 if (!setTypeName(*$3, $1) && !$1) {
1935 // If this is a named type that is not a redefinition, add it to the slot
1937 CurModule.Types.push_back(*$3);
1943 | OptLocalAssign TYPE VOID {
1944 ResolveTypeTo($1, $3);
1946 if (!setTypeName($3, $1) && !$1) {
1948 // If this is a named type that is not a redefinition, add it to the slot
1950 CurModule.Types.push_back($3);
1954 | OptGlobalAssign GVVisibilityStyle GlobalType ConstVal {
1955 /* "Externally Visible" Linkage */
1957 GEN_ERROR("Global value initializer is not a constant");
1958 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
1959 $2, $3, $4->getType(), $4);
1961 } GlobalVarAttributes {
1964 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle GlobalType ConstVal {
1966 GEN_ERROR("Global value initializer is not a constant");
1967 CurGV = ParseGlobalVariable($1, $2, $3, $4, $5->getType(), $5);
1969 } GlobalVarAttributes {
1972 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle GlobalType Types {
1973 if (!UpRefs.empty())
1974 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1975 CurGV = ParseGlobalVariable($1, $2, $3, $4, *$5, 0);
1978 } GlobalVarAttributes {
1982 | TARGET TargetDefinition {
1985 | DEPLIBS '=' LibrariesDefinition {
1991 AsmBlock : STRINGCONSTANT {
1992 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1993 char *EndStr = UnEscapeLexed($1, true);
1994 std::string NewAsm($1, EndStr);
1997 if (AsmSoFar.empty())
1998 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2000 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2004 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2005 CurModule.CurrentModule->setTargetTriple($3);
2008 | DATALAYOUT '=' STRINGCONSTANT {
2009 CurModule.CurrentModule->setDataLayout($3);
2013 LibrariesDefinition : '[' LibList ']';
2015 LibList : LibList ',' STRINGCONSTANT {
2016 CurModule.CurrentModule->addLibrary($3);
2021 CurModule.CurrentModule->addLibrary($1);
2025 | /* empty: end of list */ {
2030 //===----------------------------------------------------------------------===//
2031 // Rules to match Function Headers
2032 //===----------------------------------------------------------------------===//
2034 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2035 if (!UpRefs.empty())
2036 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2037 if (*$3 == Type::VoidTy)
2038 GEN_ERROR("void typed arguments are invalid");
2039 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2044 | Types OptParamAttrs OptLocalName {
2045 if (!UpRefs.empty())
2046 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2047 if (*$1 == Type::VoidTy)
2048 GEN_ERROR("void typed arguments are invalid");
2049 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2050 $$ = new ArgListType;
2055 ArgList : ArgListH {
2059 | ArgListH ',' DOTDOTDOT {
2061 struct ArgListEntry E;
2062 E.Ty = new PATypeHolder(Type::VoidTy);
2064 E.Attrs = FunctionType::NoAttributeSet;
2069 $$ = new ArgListType;
2070 struct ArgListEntry E;
2071 E.Ty = new PATypeHolder(Type::VoidTy);
2073 E.Attrs = FunctionType::NoAttributeSet;
2082 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2083 OptFuncAttrs OptSection OptAlign {
2085 std::string FunctionName($3);
2086 free($3); // Free strdup'd memory!
2088 // Check the function result for abstractness if this is a define. We should
2089 // have no abstract types at this point
2090 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2091 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2093 std::vector<const Type*> ParamTypeList;
2094 std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2095 ParamAttrs.push_back($7);
2096 if ($5) { // If there are arguments...
2097 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2098 const Type* Ty = I->Ty->get();
2099 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2100 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2101 ParamTypeList.push_back(Ty);
2102 if (Ty != Type::VoidTy)
2103 ParamAttrs.push_back(I->Attrs);
2107 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2108 if (isVarArg) ParamTypeList.pop_back();
2110 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2112 const PointerType *PFT = PointerType::get(FT);
2116 if (!FunctionName.empty()) {
2117 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2119 ID = ValID::createGlobalID(CurModule.Values[PFT].size());
2123 // See if this function was forward referenced. If so, recycle the object.
2124 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2125 // Move the function to the end of the list, from whereever it was
2126 // previously inserted.
2127 Fn = cast<Function>(FWRef);
2128 CurModule.CurrentModule->getFunctionList().remove(Fn);
2129 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2130 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2131 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2132 if (Fn->getFunctionType() != FT ) {
2133 // The existing function doesn't have the same type. This is an overload
2135 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2136 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2137 // Neither the existing or the current function is a declaration and they
2138 // have the same name and same type. Clearly this is a redefinition.
2139 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2140 } if (Fn->isDeclaration()) {
2141 // Make sure to strip off any argument names so we can't get conflicts.
2142 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2146 } else { // Not already defined?
2147 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2148 CurModule.CurrentModule);
2150 InsertValue(Fn, CurModule.Values);
2153 CurFun.FunctionStart(Fn);
2155 if (CurFun.isDeclare) {
2156 // If we have declaration, always overwrite linkage. This will allow us to
2157 // correctly handle cases, when pointer to function is passed as argument to
2158 // another function.
2159 Fn->setLinkage(CurFun.Linkage);
2160 Fn->setVisibility(CurFun.Visibility);
2162 Fn->setCallingConv($1);
2163 Fn->setAlignment($9);
2169 // Add all of the arguments we parsed to the function...
2170 if ($5) { // Is null if empty...
2171 if (isVarArg) { // Nuke the last entry
2172 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2173 "Not a varargs marker!");
2174 delete $5->back().Ty;
2175 $5->pop_back(); // Delete the last entry
2177 Function::arg_iterator ArgIt = Fn->arg_begin();
2178 Function::arg_iterator ArgEnd = Fn->arg_end();
2180 for (ArgListType::iterator I = $5->begin();
2181 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2182 delete I->Ty; // Delete the typeholder...
2183 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2189 delete $5; // We're now done with the argument list
2194 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2196 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2197 $$ = CurFun.CurrentFunction;
2199 // Make sure that we keep track of the linkage type even if there was a
2200 // previous "declare".
2202 $$->setVisibility($2);
2205 END : ENDTOK | '}'; // Allow end of '}' to end a function
2207 Function : BasicBlockList END {
2212 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2213 CurFun.CurrentFunction->setLinkage($1);
2214 CurFun.CurrentFunction->setVisibility($2);
2215 $$ = CurFun.CurrentFunction;
2216 CurFun.FunctionDone();
2220 //===----------------------------------------------------------------------===//
2221 // Rules to match Basic Blocks
2222 //===----------------------------------------------------------------------===//
2224 OptSideEffect : /* empty */ {
2233 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2234 $$ = ValID::create($1);
2238 $$ = ValID::create($1);
2241 | FPVAL { // Perhaps it's an FP constant?
2242 $$ = ValID::create($1);
2246 $$ = ValID::create(ConstantInt::getTrue());
2250 $$ = ValID::create(ConstantInt::getFalse());
2254 $$ = ValID::createNull();
2258 $$ = ValID::createUndef();
2261 | ZEROINITIALIZER { // A vector zero constant.
2262 $$ = ValID::createZeroInit();
2265 | '<' ConstVector '>' { // Nonempty unsized packed vector
2266 const Type *ETy = (*$2)[0]->getType();
2267 int NumElements = $2->size();
2269 VectorType* pt = VectorType::get(ETy, NumElements);
2270 PATypeHolder* PTy = new PATypeHolder(
2278 // Verify all elements are correct type!
2279 for (unsigned i = 0; i < $2->size(); i++) {
2280 if (ETy != (*$2)[i]->getType())
2281 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2282 ETy->getDescription() +"' as required!\nIt is of type '" +
2283 (*$2)[i]->getType()->getDescription() + "'.");
2286 $$ = ValID::create(ConstantVector::get(pt, *$2));
2287 delete PTy; delete $2;
2291 $$ = ValID::create($1);
2294 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2295 char *End = UnEscapeLexed($3, true);
2296 std::string AsmStr = std::string($3, End);
2297 End = UnEscapeLexed($5, true);
2298 std::string Constraints = std::string($5, End);
2299 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2305 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2308 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2309 $$ = ValID::createLocalID($1);
2313 $$ = ValID::createGlobalID($1);
2316 | LocalName { // Is it a named reference...?
2317 $$ = ValID::createLocalName($1);
2320 | GlobalName { // Is it a named reference...?
2321 $$ = ValID::createGlobalName($1);
2325 // ValueRef - A reference to a definition... either constant or symbolic
2326 ValueRef : SymbolicValueRef | ConstValueRef;
2329 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2330 // type immediately preceeds the value reference, and allows complex constant
2331 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2332 ResolvedVal : Types ValueRef {
2333 if (!UpRefs.empty())
2334 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2335 $$ = getVal(*$1, $2);
2341 BasicBlockList : BasicBlockList BasicBlock {
2345 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2351 // Basic blocks are terminated by branching instructions:
2352 // br, br/cc, switch, ret
2354 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2355 setValueName($3, $2);
2358 $1->getInstList().push_back($3);
2364 InstructionList : InstructionList Inst {
2365 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2366 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2367 if (CI2->getParent() == 0)
2368 $1->getInstList().push_back(CI2);
2369 $1->getInstList().push_back($2);
2374 $$ = getBBVal(ValID::createLocalID(CurFun.NextBBNum++), true);
2377 // Make sure to move the basic block to the correct location in the
2378 // function, instead of leaving it inserted wherever it was first
2380 Function::BasicBlockListType &BBL =
2381 CurFun.CurrentFunction->getBasicBlockList();
2382 BBL.splice(BBL.end(), BBL, $$);
2386 $$ = getBBVal(ValID::createLocalName($1), true);
2389 // Make sure to move the basic block to the correct location in the
2390 // function, instead of leaving it inserted wherever it was first
2392 Function::BasicBlockListType &BBL =
2393 CurFun.CurrentFunction->getBasicBlockList();
2394 BBL.splice(BBL.end(), BBL, $$);
2398 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2399 $$ = new ReturnInst($2);
2402 | RET VOID { // Return with no result...
2403 $$ = new ReturnInst();
2406 | BR LABEL ValueRef { // Unconditional Branch...
2407 BasicBlock* tmpBB = getBBVal($3);
2409 $$ = new BranchInst(tmpBB);
2410 } // Conditional Branch...
2411 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2412 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2413 BasicBlock* tmpBBA = getBBVal($6);
2415 BasicBlock* tmpBBB = getBBVal($9);
2417 Value* tmpVal = getVal(Type::Int1Ty, $3);
2419 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2421 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2422 Value* tmpVal = getVal($2, $3);
2424 BasicBlock* tmpBB = getBBVal($6);
2426 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2429 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2431 for (; I != E; ++I) {
2432 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2433 S->addCase(CI, I->second);
2435 GEN_ERROR("Switch case is constant, but not a simple integer");
2440 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2441 Value* tmpVal = getVal($2, $3);
2443 BasicBlock* tmpBB = getBBVal($6);
2445 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2449 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2450 TO LABEL ValueRef UNWIND LABEL ValueRef {
2452 // Handle the short syntax
2453 const PointerType *PFTy = 0;
2454 const FunctionType *Ty = 0;
2455 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2456 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2457 // Pull out the types of all of the arguments...
2458 std::vector<const Type*> ParamTypes;
2459 FunctionType::ParamAttrsList ParamAttrs;
2460 ParamAttrs.push_back($8);
2461 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2462 const Type *Ty = I->Val->getType();
2463 if (Ty == Type::VoidTy)
2464 GEN_ERROR("Short call syntax cannot be used with varargs");
2465 ParamTypes.push_back(Ty);
2466 ParamAttrs.push_back(I->Attrs);
2469 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2470 PFTy = PointerType::get(Ty);
2473 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2475 BasicBlock *Normal = getBBVal($11);
2477 BasicBlock *Except = getBBVal($14);
2480 // Check the arguments
2482 if ($6->empty()) { // Has no arguments?
2483 // Make sure no arguments is a good thing!
2484 if (Ty->getNumParams() != 0)
2485 GEN_ERROR("No arguments passed to a function that "
2486 "expects arguments");
2487 } else { // Has arguments?
2488 // Loop through FunctionType's arguments and ensure they are specified
2490 FunctionType::param_iterator I = Ty->param_begin();
2491 FunctionType::param_iterator E = Ty->param_end();
2492 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2494 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2495 if (ArgI->Val->getType() != *I)
2496 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2497 (*I)->getDescription() + "'");
2498 Args.push_back(ArgI->Val);
2501 if (Ty->isVarArg()) {
2503 for (; ArgI != ArgE; ++ArgI)
2504 Args.push_back(ArgI->Val); // push the remaining varargs
2505 } else if (I != E || ArgI != ArgE)
2506 GEN_ERROR("Invalid number of parameters detected");
2509 // Create the InvokeInst
2510 InvokeInst *II = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
2511 II->setCallingConv($2);
2517 $$ = new UnwindInst();
2521 $$ = new UnreachableInst();
2527 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2529 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2532 GEN_ERROR("May only switch on a constant pool value");
2534 BasicBlock* tmpBB = getBBVal($6);
2536 $$->push_back(std::make_pair(V, tmpBB));
2538 | IntType ConstValueRef ',' LABEL ValueRef {
2539 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2540 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2544 GEN_ERROR("May only switch on a constant pool value");
2546 BasicBlock* tmpBB = getBBVal($5);
2548 $$->push_back(std::make_pair(V, tmpBB));
2551 Inst : OptLocalAssign InstVal {
2552 // Is this definition named?? if so, assign the name...
2553 setValueName($2, $1);
2561 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2562 if (!UpRefs.empty())
2563 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2564 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2565 Value* tmpVal = getVal(*$1, $3);
2567 BasicBlock* tmpBB = getBBVal($5);
2569 $$->push_back(std::make_pair(tmpVal, tmpBB));
2572 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2574 Value* tmpVal = getVal($1->front().first->getType(), $4);
2576 BasicBlock* tmpBB = getBBVal($6);
2578 $1->push_back(std::make_pair(tmpVal, tmpBB));
2582 ValueRefList : Types ValueRef OptParamAttrs {
2583 if (!UpRefs.empty())
2584 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2585 // Used for call and invoke instructions
2586 $$ = new ValueRefList();
2587 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2590 | ValueRefList ',' Types ValueRef OptParamAttrs {
2591 if (!UpRefs.empty())
2592 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2594 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2598 | /*empty*/ { $$ = new ValueRefList(); };
2600 IndexList // Used for gep instructions and constant expressions
2601 : /*empty*/ { $$ = new std::vector<Value*>(); }
2602 | IndexList ',' ResolvedVal {
2609 OptTailCall : TAIL CALL {
2618 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2619 if (!UpRefs.empty())
2620 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2621 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2622 !isa<VectorType>((*$2).get()))
2624 "Arithmetic operator requires integer, FP, or packed operands");
2625 if (isa<VectorType>((*$2).get()) &&
2626 ($1 == Instruction::URem ||
2627 $1 == Instruction::SRem ||
2628 $1 == Instruction::FRem))
2629 GEN_ERROR("Remainder not supported on vector types");
2630 Value* val1 = getVal(*$2, $3);
2632 Value* val2 = getVal(*$2, $5);
2634 $$ = BinaryOperator::create($1, val1, val2);
2636 GEN_ERROR("binary operator returned null");
2639 | LogicalOps Types ValueRef ',' ValueRef {
2640 if (!UpRefs.empty())
2641 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2642 if (!(*$2)->isInteger()) {
2643 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2644 !cast<VectorType>($2->get())->getElementType()->isInteger())
2645 GEN_ERROR("Logical operator requires integral operands");
2647 Value* tmpVal1 = getVal(*$2, $3);
2649 Value* tmpVal2 = getVal(*$2, $5);
2651 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2653 GEN_ERROR("binary operator returned null");
2656 | ICMP IPredicates Types ValueRef ',' ValueRef {
2657 if (!UpRefs.empty())
2658 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2659 if (isa<VectorType>((*$3).get()))
2660 GEN_ERROR("Vector types not supported by icmp instruction");
2661 Value* tmpVal1 = getVal(*$3, $4);
2663 Value* tmpVal2 = getVal(*$3, $6);
2665 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2667 GEN_ERROR("icmp operator returned null");
2669 | FCMP FPredicates Types ValueRef ',' ValueRef {
2670 if (!UpRefs.empty())
2671 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2672 if (isa<VectorType>((*$3).get()))
2673 GEN_ERROR("Vector types not supported by fcmp instruction");
2674 Value* tmpVal1 = getVal(*$3, $4);
2676 Value* tmpVal2 = getVal(*$3, $6);
2678 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2680 GEN_ERROR("fcmp operator returned null");
2682 | CastOps ResolvedVal TO Types {
2683 if (!UpRefs.empty())
2684 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2686 const Type* DestTy = $4->get();
2687 if (!CastInst::castIsValid($1, Val, DestTy))
2688 GEN_ERROR("invalid cast opcode for cast from '" +
2689 Val->getType()->getDescription() + "' to '" +
2690 DestTy->getDescription() + "'");
2691 $$ = CastInst::create($1, Val, DestTy);
2694 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2695 if ($2->getType() != Type::Int1Ty)
2696 GEN_ERROR("select condition must be boolean");
2697 if ($4->getType() != $6->getType())
2698 GEN_ERROR("select value types should match");
2699 $$ = new SelectInst($2, $4, $6);
2702 | VAARG ResolvedVal ',' Types {
2703 if (!UpRefs.empty())
2704 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2705 $$ = new VAArgInst($2, *$4);
2709 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2710 if (!ExtractElementInst::isValidOperands($2, $4))
2711 GEN_ERROR("Invalid extractelement operands");
2712 $$ = new ExtractElementInst($2, $4);
2715 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2716 if (!InsertElementInst::isValidOperands($2, $4, $6))
2717 GEN_ERROR("Invalid insertelement operands");
2718 $$ = new InsertElementInst($2, $4, $6);
2721 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2722 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2723 GEN_ERROR("Invalid shufflevector operands");
2724 $$ = new ShuffleVectorInst($2, $4, $6);
2728 const Type *Ty = $2->front().first->getType();
2729 if (!Ty->isFirstClassType())
2730 GEN_ERROR("PHI node operands must be of first class type");
2731 $$ = new PHINode(Ty);
2732 ((PHINode*)$$)->reserveOperandSpace($2->size());
2733 while ($2->begin() != $2->end()) {
2734 if ($2->front().first->getType() != Ty)
2735 GEN_ERROR("All elements of a PHI node must be of the same type");
2736 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2739 delete $2; // Free the list...
2742 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2745 // Handle the short syntax
2746 const PointerType *PFTy = 0;
2747 const FunctionType *Ty = 0;
2748 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2749 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2750 // Pull out the types of all of the arguments...
2751 std::vector<const Type*> ParamTypes;
2752 FunctionType::ParamAttrsList ParamAttrs;
2753 ParamAttrs.push_back($8);
2754 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2755 const Type *Ty = I->Val->getType();
2756 if (Ty == Type::VoidTy)
2757 GEN_ERROR("Short call syntax cannot be used with varargs");
2758 ParamTypes.push_back(Ty);
2759 ParamAttrs.push_back(I->Attrs);
2762 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2763 PFTy = PointerType::get(Ty);
2766 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2769 // Check the arguments
2771 if ($6->empty()) { // Has no arguments?
2772 // Make sure no arguments is a good thing!
2773 if (Ty->getNumParams() != 0)
2774 GEN_ERROR("No arguments passed to a function that "
2775 "expects arguments");
2776 } else { // Has arguments?
2777 // Loop through FunctionType's arguments and ensure they are specified
2780 FunctionType::param_iterator I = Ty->param_begin();
2781 FunctionType::param_iterator E = Ty->param_end();
2782 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2784 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2785 if (ArgI->Val->getType() != *I)
2786 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2787 (*I)->getDescription() + "'");
2788 Args.push_back(ArgI->Val);
2790 if (Ty->isVarArg()) {
2792 for (; ArgI != ArgE; ++ArgI)
2793 Args.push_back(ArgI->Val); // push the remaining varargs
2794 } else if (I != E || ArgI != ArgE)
2795 GEN_ERROR("Invalid number of parameters detected");
2797 // Create the call node
2798 CallInst *CI = new CallInst(V, &Args[0], Args.size());
2799 CI->setTailCall($1);
2800 CI->setCallingConv($2);
2811 OptVolatile : VOLATILE {
2822 MemoryInst : MALLOC Types OptCAlign {
2823 if (!UpRefs.empty())
2824 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2825 $$ = new MallocInst(*$2, 0, $3);
2829 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2830 if (!UpRefs.empty())
2831 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2832 Value* tmpVal = getVal($4, $5);
2834 $$ = new MallocInst(*$2, tmpVal, $6);
2837 | ALLOCA Types OptCAlign {
2838 if (!UpRefs.empty())
2839 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2840 $$ = new AllocaInst(*$2, 0, $3);
2844 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2845 if (!UpRefs.empty())
2846 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2847 Value* tmpVal = getVal($4, $5);
2849 $$ = new AllocaInst(*$2, tmpVal, $6);
2852 | FREE ResolvedVal {
2853 if (!isa<PointerType>($2->getType()))
2854 GEN_ERROR("Trying to free nonpointer type " +
2855 $2->getType()->getDescription() + "");
2856 $$ = new FreeInst($2);
2860 | OptVolatile LOAD Types ValueRef {
2861 if (!UpRefs.empty())
2862 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2863 if (!isa<PointerType>($3->get()))
2864 GEN_ERROR("Can't load from nonpointer type: " +
2865 (*$3)->getDescription());
2866 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2867 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2868 (*$3)->getDescription());
2869 Value* tmpVal = getVal(*$3, $4);
2871 $$ = new LoadInst(tmpVal, "", $1);
2874 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2875 if (!UpRefs.empty())
2876 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2877 const PointerType *PT = dyn_cast<PointerType>($5->get());
2879 GEN_ERROR("Can't store to a nonpointer type: " +
2880 (*$5)->getDescription());
2881 const Type *ElTy = PT->getElementType();
2882 if (ElTy != $3->getType())
2883 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2884 "' into space of type '" + ElTy->getDescription() + "'");
2886 Value* tmpVal = getVal(*$5, $6);
2888 $$ = new StoreInst($3, tmpVal, $1);
2891 | GETELEMENTPTR Types ValueRef IndexList {
2892 if (!UpRefs.empty())
2893 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2894 if (!isa<PointerType>($2->get()))
2895 GEN_ERROR("getelementptr insn requires pointer operand");
2897 if (!GetElementPtrInst::getIndexedType(*$2, &(*$4)[0], $4->size(), true))
2898 GEN_ERROR("Invalid getelementptr indices for type '" +
2899 (*$2)->getDescription()+ "'");
2900 Value* tmpVal = getVal(*$2, $3);
2902 $$ = new GetElementPtrInst(tmpVal, &(*$4)[0], $4->size());
2910 // common code from the two 'RunVMAsmParser' functions
2911 static Module* RunParser(Module * M) {
2913 llvmAsmlineno = 1; // Reset the current line number...
2914 CurModule.CurrentModule = M;
2919 // Check to make sure the parser succeeded
2922 delete ParserResult;
2926 // Check to make sure that parsing produced a result
2930 // Reset ParserResult variable while saving its value for the result.
2931 Module *Result = ParserResult;
2937 void llvm::GenerateError(const std::string &message, int LineNo) {
2938 if (LineNo == -1) LineNo = llvmAsmlineno;
2939 // TODO: column number in exception
2941 TheParseError->setError(CurFilename, message, LineNo);
2945 int yyerror(const char *ErrorMsg) {
2947 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2948 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2949 std::string errMsg = where + "error: " + std::string(ErrorMsg);
2950 if (yychar != YYEMPTY && yychar != 0)
2951 errMsg += " while reading token: '" + std::string(llvmAsmtext, llvmAsmleng)+
2953 GenerateError(errMsg);