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/SymbolTable.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"
34 // The following is a gross hack. In order to rid the libAsmParser library of
35 // exceptions, we have to have a way of getting the yyparse function to go into
36 // an error situation. So, whenever we want an error to occur, the GenerateError
37 // function (see bottom of file) sets TriggerError. Then, at the end of each
38 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
39 // (a goto) to put YACC in error state. Furthermore, several calls to
40 // GenerateError are made from inside productions and they must simulate the
41 // previous exception behavior by exiting the production immediately. We have
42 // replaced these with the GEN_ERROR macro which calls GeneratError and then
43 // immediately invokes YYERROR. This would be so much cleaner if it was a
44 // recursive descent parser.
45 static bool TriggerError = false;
46 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
47 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
49 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
50 int yylex(); // declaration" of xxx warnings.
54 std::string CurFilename;
57 Debug("debug-yacc", cl::desc("Print yacc debug state changes"),
58 cl::Hidden, cl::init(false));
63 static Module *ParserResult;
65 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
66 // relating to upreferences in the input stream.
68 //#define DEBUG_UPREFS 1
70 #define UR_OUT(X) cerr << X
75 #define YYERROR_VERBOSE 1
77 static GlobalVariable *CurGV;
80 // This contains info used when building the body of a function. It is
81 // destroyed when the function is completed.
83 typedef std::vector<Value *> ValueList; // Numbered defs
86 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
87 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
89 static struct PerModuleInfo {
90 Module *CurrentModule;
91 std::map<const Type *, ValueList> Values; // Module level numbered definitions
92 std::map<const Type *,ValueList> LateResolveValues;
93 std::vector<PATypeHolder> Types;
94 std::map<ValID, PATypeHolder> LateResolveTypes;
96 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
97 /// how they were referenced and on which line of the input they came from so
98 /// that we can resolve them later and print error messages as appropriate.
99 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
101 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
102 // references to global values. Global values may be referenced before they
103 // are defined, and if so, the temporary object that they represent is held
104 // here. This is used for forward references of GlobalValues.
106 typedef std::map<std::pair<const PointerType *,
107 ValID>, GlobalValue*> GlobalRefsType;
108 GlobalRefsType GlobalRefs;
111 // If we could not resolve some functions at function compilation time
112 // (calls to functions before they are defined), resolve them now... Types
113 // are resolved when the constant pool has been completely parsed.
115 ResolveDefinitions(LateResolveValues);
119 // Check to make sure that all global value forward references have been
122 if (!GlobalRefs.empty()) {
123 std::string UndefinedReferences = "Unresolved global references exist:\n";
125 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
127 UndefinedReferences += " " + I->first.first->getDescription() + " " +
128 I->first.second.getName() + "\n";
130 GenerateError(UndefinedReferences);
134 Values.clear(); // Clear out function local definitions
139 // GetForwardRefForGlobal - Check to see if there is a forward reference
140 // for this global. If so, remove it from the GlobalRefs map and return it.
141 // If not, just return null.
142 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
143 // Check to see if there is a forward reference to this global variable...
144 // if there is, eliminate it and patch the reference to use the new def'n.
145 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
146 GlobalValue *Ret = 0;
147 if (I != GlobalRefs.end()) {
154 bool TypeIsUnresolved(PATypeHolder* PATy) {
155 // If it isn't abstract, its resolved
156 const Type* Ty = PATy->get();
157 if (!Ty->isAbstract())
159 // Traverse the type looking for abstract types. If it isn't abstract then
160 // we don't need to traverse that leg of the type.
161 std::vector<const Type*> WorkList, SeenList;
162 WorkList.push_back(Ty);
163 while (!WorkList.empty()) {
164 const Type* Ty = WorkList.back();
165 SeenList.push_back(Ty);
167 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
168 // Check to see if this is an unresolved type
169 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
170 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
171 for ( ; I != E; ++I) {
172 if (I->second.get() == OpTy)
175 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
176 const Type* TheTy = SeqTy->getElementType();
177 if (TheTy->isAbstract() && TheTy != Ty) {
178 std::vector<const Type*>::iterator I = SeenList.begin(),
184 WorkList.push_back(TheTy);
186 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
187 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
188 const Type* TheTy = StrTy->getElementType(i);
189 if (TheTy->isAbstract() && TheTy != Ty) {
190 std::vector<const Type*>::iterator I = SeenList.begin(),
196 WorkList.push_back(TheTy);
207 static struct PerFunctionInfo {
208 Function *CurrentFunction; // Pointer to current function being created
210 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
211 std::map<const Type*, ValueList> LateResolveValues;
212 bool isDeclare; // Is this function a forward declararation?
213 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
214 GlobalValue::VisibilityTypes Visibility;
216 /// BBForwardRefs - When we see forward references to basic blocks, keep
217 /// track of them here.
218 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
219 std::vector<BasicBlock*> NumberedBlocks;
222 inline PerFunctionInfo() {
225 Linkage = GlobalValue::ExternalLinkage;
226 Visibility = GlobalValue::DefaultVisibility;
229 inline void FunctionStart(Function *M) {
234 void FunctionDone() {
235 NumberedBlocks.clear();
237 // Any forward referenced blocks left?
238 if (!BBForwardRefs.empty()) {
239 GenerateError("Undefined reference to label " +
240 BBForwardRefs.begin()->first->getName());
244 // Resolve all forward references now.
245 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
247 Values.clear(); // Clear out function local definitions
250 Linkage = GlobalValue::ExternalLinkage;
251 Visibility = GlobalValue::DefaultVisibility;
253 } CurFun; // Info for the current function...
255 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
258 //===----------------------------------------------------------------------===//
259 // Code to handle definitions of all the types
260 //===----------------------------------------------------------------------===//
262 static int InsertValue(Value *V,
263 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
264 if (V->hasName()) return -1; // Is this a numbered definition?
266 // Yes, insert the value into the value table...
267 ValueList &List = ValueTab[V->getType()];
269 return List.size()-1;
272 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
274 case ValID::LocalID: // Is it a numbered definition?
275 // Module constants occupy the lowest numbered slots...
276 if (D.Num < CurModule.Types.size())
277 return CurModule.Types[D.Num];
279 case ValID::LocalName: // Is it a named definition?
280 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
281 D.destroy(); // Free old strdup'd memory...
286 GenerateError("Internal parser error: Invalid symbol type reference!");
290 // If we reached here, we referenced either a symbol that we don't know about
291 // or an id number that hasn't been read yet. We may be referencing something
292 // forward, so just create an entry to be resolved later and get to it...
294 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
297 if (inFunctionScope()) {
298 if (D.Type == ValID::LocalName) {
299 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
302 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
307 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
308 if (I != CurModule.LateResolveTypes.end())
311 Type *Typ = OpaqueType::get();
312 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
316 // getValNonImprovising - Look up the value specified by the provided type and
317 // the provided ValID. If the value exists and has already been defined, return
318 // it. Otherwise return null.
320 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
321 if (isa<FunctionType>(Ty)) {
322 GenerateError("Functions are not values and "
323 "must be referenced as pointers");
328 case ValID::LocalID: { // Is it a numbered definition?
329 // Module constants occupy the lowest numbered slots.
330 std::map<const Type*,ValueList>::iterator VI = CurFun.Values.find(Ty);
331 // Make sure that our type is within bounds.
332 if (VI == CurFun.Values.end()) return 0;
334 // Check that the number is within bounds.
335 if (D.Num >= VI->second.size()) return 0;
337 return VI->second[D.Num];
339 case ValID::GlobalID: { // Is it a numbered definition?
340 unsigned Num = D.Num;
342 // Module constants occupy the lowest numbered slots...
343 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
344 if (VI == CurModule.Values.end()) return 0;
345 if (D.Num >= VI->second.size()) return 0;
346 return VI->second[Num];
349 case ValID::LocalName: { // Is it a named definition?
350 if (!inFunctionScope()) return 0;
351 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
352 Value *N = SymTab.lookup(Ty, D.Name);
353 if (N == 0) return 0;
355 D.destroy(); // Free old strdup'd memory...
358 case ValID::GlobalName: { // Is it a named definition?
359 SymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
360 Value *N = SymTab.lookup(Ty, D.Name);
361 if (N == 0) return 0;
363 D.destroy(); // Free old strdup'd memory...
367 // Check to make sure that "Ty" is an integral type, and that our
368 // value will fit into the specified type...
369 case ValID::ConstSIntVal: // Is it a constant pool reference??
370 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
371 GenerateError("Signed integral constant '" +
372 itostr(D.ConstPool64) + "' is invalid for type '" +
373 Ty->getDescription() + "'!");
376 return ConstantInt::get(Ty, D.ConstPool64);
378 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
379 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
380 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
381 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
382 "' is invalid or out of range!");
384 } else { // This is really a signed reference. Transmogrify.
385 return ConstantInt::get(Ty, D.ConstPool64);
388 return ConstantInt::get(Ty, D.UConstPool64);
391 case ValID::ConstFPVal: // Is it a floating point const pool reference?
392 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
393 GenerateError("FP constant invalid for type!!");
396 return ConstantFP::get(Ty, D.ConstPoolFP);
398 case ValID::ConstNullVal: // Is it a null value?
399 if (!isa<PointerType>(Ty)) {
400 GenerateError("Cannot create a a non pointer null!");
403 return ConstantPointerNull::get(cast<PointerType>(Ty));
405 case ValID::ConstUndefVal: // Is it an undef value?
406 return UndefValue::get(Ty);
408 case ValID::ConstZeroVal: // Is it a zero value?
409 return Constant::getNullValue(Ty);
411 case ValID::ConstantVal: // Fully resolved constant?
412 if (D.ConstantValue->getType() != Ty) {
413 GenerateError("Constant expression type different from required type!");
416 return D.ConstantValue;
418 case ValID::InlineAsmVal: { // Inline asm expression
419 const PointerType *PTy = dyn_cast<PointerType>(Ty);
420 const FunctionType *FTy =
421 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
422 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
423 GenerateError("Invalid type for asm constraint string!");
426 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
427 D.IAD->HasSideEffects);
428 D.destroy(); // Free InlineAsmDescriptor.
432 assert(0 && "Unhandled case!");
436 assert(0 && "Unhandled case!");
440 // getVal - This function is identical to getValNonImprovising, except that if a
441 // value is not already defined, it "improvises" by creating a placeholder var
442 // that looks and acts just like the requested variable. When the value is
443 // defined later, all uses of the placeholder variable are replaced with the
446 static Value *getVal(const Type *Ty, const ValID &ID) {
447 if (Ty == Type::LabelTy) {
448 GenerateError("Cannot use a basic block here");
452 // See if the value has already been defined.
453 Value *V = getValNonImprovising(Ty, ID);
455 if (TriggerError) return 0;
457 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
458 GenerateError("Invalid use of a composite type!");
462 // If we reached here, we referenced either a symbol that we don't know about
463 // or an id number that hasn't been read yet. We may be referencing something
464 // forward, so just create an entry to be resolved later and get to it...
466 V = new Argument(Ty);
468 // Remember where this forward reference came from. FIXME, shouldn't we try
469 // to recycle these things??
470 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
473 if (inFunctionScope())
474 InsertValue(V, CurFun.LateResolveValues);
476 InsertValue(V, CurModule.LateResolveValues);
480 /// getBBVal - This is used for two purposes:
481 /// * If isDefinition is true, a new basic block with the specified ID is being
483 /// * If isDefinition is true, this is a reference to a basic block, which may
484 /// or may not be a forward reference.
486 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
487 assert(inFunctionScope() && "Can't get basic block at global scope!");
493 GenerateError("Illegal label reference " + ID.getName());
495 case ValID::LocalID: // Is it a numbered definition?
496 if (ID.Num >= CurFun.NumberedBlocks.size())
497 CurFun.NumberedBlocks.resize(ID.Num+1);
498 BB = CurFun.NumberedBlocks[ID.Num];
500 case ValID::LocalName: // Is it a named definition?
502 if (Value *N = CurFun.CurrentFunction->
503 getValueSymbolTable().lookup(Type::LabelTy, Name))
504 BB = cast<BasicBlock>(N);
508 // See if the block has already been defined.
510 // If this is the definition of the block, make sure the existing value was
511 // just a forward reference. If it was a forward reference, there will be
512 // an entry for it in the PlaceHolderInfo map.
513 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
514 // The existing value was a definition, not a forward reference.
515 GenerateError("Redefinition of label " + ID.getName());
519 ID.destroy(); // Free strdup'd memory.
523 // Otherwise this block has not been seen before.
524 BB = new BasicBlock("", CurFun.CurrentFunction);
525 if (ID.Type == ValID::LocalName) {
526 BB->setName(ID.Name);
528 CurFun.NumberedBlocks[ID.Num] = BB;
531 // If this is not a definition, keep track of it so we can use it as a forward
534 // Remember where this forward reference came from.
535 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
537 // The forward declaration could have been inserted anywhere in the
538 // function: insert it into the correct place now.
539 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
540 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
547 //===----------------------------------------------------------------------===//
548 // Code to handle forward references in instructions
549 //===----------------------------------------------------------------------===//
551 // This code handles the late binding needed with statements that reference
552 // values not defined yet... for example, a forward branch, or the PHI node for
555 // This keeps a table (CurFun.LateResolveValues) of all such forward references
556 // and back patchs after we are done.
559 // ResolveDefinitions - If we could not resolve some defs at parsing
560 // time (forward branches, phi functions for loops, etc...) resolve the
564 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
565 std::map<const Type*,ValueList> *FutureLateResolvers) {
566 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
567 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
568 E = LateResolvers.end(); LRI != E; ++LRI) {
569 ValueList &List = LRI->second;
570 while (!List.empty()) {
571 Value *V = List.back();
574 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
575 CurModule.PlaceHolderInfo.find(V);
576 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
578 ValID &DID = PHI->second.first;
580 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
584 V->replaceAllUsesWith(TheRealValue);
586 CurModule.PlaceHolderInfo.erase(PHI);
587 } else if (FutureLateResolvers) {
588 // Functions have their unresolved items forwarded to the module late
590 InsertValue(V, *FutureLateResolvers);
592 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
593 GenerateError("Reference to an invalid definition: '" +DID.getName()+
594 "' of type '" + V->getType()->getDescription() + "'",
598 GenerateError("Reference to an invalid definition: #" +
599 itostr(DID.Num) + " of type '" +
600 V->getType()->getDescription() + "'",
608 LateResolvers.clear();
611 // ResolveTypeTo - A brand new type was just declared. This means that (if
612 // name is not null) things referencing Name can be resolved. Otherwise, things
613 // refering to the number can be resolved. Do this now.
615 static void ResolveTypeTo(char *Name, const Type *ToTy) {
617 if (Name) D = ValID::createLocalName(Name);
618 else D = ValID::createLocalID(CurModule.Types.size());
620 std::map<ValID, PATypeHolder>::iterator I =
621 CurModule.LateResolveTypes.find(D);
622 if (I != CurModule.LateResolveTypes.end()) {
623 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
624 CurModule.LateResolveTypes.erase(I);
628 // setValueName - Set the specified value to the name given. The name may be
629 // null potentially, in which case this is a noop. The string passed in is
630 // assumed to be a malloc'd string buffer, and is free'd by this function.
632 static void setValueName(Value *V, char *NameStr) {
633 if (!NameStr) return;
634 std::string Name(NameStr); // Copy string
635 free(NameStr); // Free old string
637 if (V->getType() == Type::VoidTy) {
638 GenerateError("Can't assign name '" + Name+"' to value with void type!");
642 assert(inFunctionScope() && "Must be in function scope!");
643 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
644 if (ST.lookup(V->getType(), Name)) {
645 GenerateError("Redefinition of value '" + Name + "' of type '" +
646 V->getType()->getDescription() + "'!");
654 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
655 /// this is a declaration, otherwise it is a definition.
656 static GlobalVariable *
657 ParseGlobalVariable(char *NameStr,
658 GlobalValue::LinkageTypes Linkage,
659 GlobalValue::VisibilityTypes Visibility,
660 bool isConstantGlobal, const Type *Ty,
661 Constant *Initializer) {
662 if (isa<FunctionType>(Ty)) {
663 GenerateError("Cannot declare global vars of function type!");
667 const PointerType *PTy = PointerType::get(Ty);
671 Name = NameStr; // Copy string
672 free(NameStr); // Free old string
675 // See if this global value was forward referenced. If so, recycle the
679 ID = ValID::createGlobalName((char*)Name.c_str());
681 ID = ValID::createGlobalID(CurModule.Values[PTy].size());
684 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
685 // Move the global to the end of the list, from whereever it was
686 // previously inserted.
687 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
688 CurModule.CurrentModule->getGlobalList().remove(GV);
689 CurModule.CurrentModule->getGlobalList().push_back(GV);
690 GV->setInitializer(Initializer);
691 GV->setLinkage(Linkage);
692 GV->setVisibility(Visibility);
693 GV->setConstant(isConstantGlobal);
694 InsertValue(GV, CurModule.Values);
698 // If this global has a name, check to see if there is already a definition
699 // of this global in the module. If so, it is an error.
701 // We are a simple redefinition of a value, check to see if it is defined
702 // the same as the old one.
703 if (CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
704 GenerateError("Redefinition of global variable named '" + Name +
705 "' of type '" + Ty->getDescription() + "'!");
710 // Otherwise there is no existing GV to use, create one now.
712 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
713 CurModule.CurrentModule);
714 GV->setVisibility(Visibility);
715 InsertValue(GV, CurModule.Values);
719 // setTypeName - Set the specified type to the name given. The name may be
720 // null potentially, in which case this is a noop. The string passed in is
721 // assumed to be a malloc'd string buffer, and is freed by this function.
723 // This function returns true if the type has already been defined, but is
724 // allowed to be redefined in the specified context. If the name is a new name
725 // for the type plane, it is inserted and false is returned.
726 static bool setTypeName(const Type *T, char *NameStr) {
727 assert(!inFunctionScope() && "Can't give types function-local names!");
728 if (NameStr == 0) return false;
730 std::string Name(NameStr); // Copy string
731 free(NameStr); // Free old string
733 // We don't allow assigning names to void type
734 if (T == Type::VoidTy) {
735 GenerateError("Can't assign name '" + Name + "' to the void type!");
739 // Set the type name, checking for conflicts as we do so.
740 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
742 if (AlreadyExists) { // Inserting a name that is already defined???
743 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
744 assert(Existing && "Conflict but no matching type?");
746 // There is only one case where this is allowed: when we are refining an
747 // opaque type. In this case, Existing will be an opaque type.
748 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
749 // We ARE replacing an opaque type!
750 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
754 // Otherwise, this is an attempt to redefine a type. That's okay if
755 // the redefinition is identical to the original. This will be so if
756 // Existing and T point to the same Type object. In this one case we
757 // allow the equivalent redefinition.
758 if (Existing == T) return true; // Yes, it's equal.
760 // Any other kind of (non-equivalent) redefinition is an error.
761 GenerateError("Redefinition of type named '" + Name + "' of type '" +
762 T->getDescription() + "'!");
768 //===----------------------------------------------------------------------===//
769 // Code for handling upreferences in type names...
772 // TypeContains - Returns true if Ty directly contains E in it.
774 static bool TypeContains(const Type *Ty, const Type *E) {
775 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
776 E) != Ty->subtype_end();
781 // NestingLevel - The number of nesting levels that need to be popped before
782 // this type is resolved.
783 unsigned NestingLevel;
785 // LastContainedTy - This is the type at the current binding level for the
786 // type. Every time we reduce the nesting level, this gets updated.
787 const Type *LastContainedTy;
789 // UpRefTy - This is the actual opaque type that the upreference is
793 UpRefRecord(unsigned NL, OpaqueType *URTy)
794 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
798 // UpRefs - A list of the outstanding upreferences that need to be resolved.
799 static std::vector<UpRefRecord> UpRefs;
801 /// HandleUpRefs - Every time we finish a new layer of types, this function is
802 /// called. It loops through the UpRefs vector, which is a list of the
803 /// currently active types. For each type, if the up reference is contained in
804 /// the newly completed type, we decrement the level count. When the level
805 /// count reaches zero, the upreferenced type is the type that is passed in:
806 /// thus we can complete the cycle.
808 static PATypeHolder HandleUpRefs(const Type *ty) {
809 // If Ty isn't abstract, or if there are no up-references in it, then there is
810 // nothing to resolve here.
811 if (!ty->isAbstract() || UpRefs.empty()) return ty;
814 UR_OUT("Type '" << Ty->getDescription() <<
815 "' newly formed. Resolving upreferences.\n" <<
816 UpRefs.size() << " upreferences active!\n");
818 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
819 // to zero), we resolve them all together before we resolve them to Ty. At
820 // the end of the loop, if there is anything to resolve to Ty, it will be in
822 OpaqueType *TypeToResolve = 0;
824 for (unsigned i = 0; i != UpRefs.size(); ++i) {
825 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
826 << UpRefs[i].second->getDescription() << ") = "
827 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
828 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
829 // Decrement level of upreference
830 unsigned Level = --UpRefs[i].NestingLevel;
831 UpRefs[i].LastContainedTy = Ty;
832 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
833 if (Level == 0) { // Upreference should be resolved!
834 if (!TypeToResolve) {
835 TypeToResolve = UpRefs[i].UpRefTy;
837 UR_OUT(" * Resolving upreference for "
838 << UpRefs[i].second->getDescription() << "\n";
839 std::string OldName = UpRefs[i].UpRefTy->getDescription());
840 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
841 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
842 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
844 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
845 --i; // Do not skip the next element...
851 UR_OUT(" * Resolving upreference for "
852 << UpRefs[i].second->getDescription() << "\n";
853 std::string OldName = TypeToResolve->getDescription());
854 TypeToResolve->refineAbstractTypeTo(Ty);
860 //===----------------------------------------------------------------------===//
861 // RunVMAsmParser - Define an interface to this parser
862 //===----------------------------------------------------------------------===//
864 static Module* RunParser(Module * M);
866 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
869 CurFilename = Filename;
870 return RunParser(new Module(CurFilename));
873 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
874 set_scan_string(AsmString);
876 CurFilename = "from_memory";
878 return RunParser(new Module (CurFilename));
887 llvm::Module *ModuleVal;
888 llvm::Function *FunctionVal;
889 llvm::BasicBlock *BasicBlockVal;
890 llvm::TerminatorInst *TermInstVal;
891 llvm::Instruction *InstVal;
892 llvm::Constant *ConstVal;
894 const llvm::Type *PrimType;
895 std::list<llvm::PATypeHolder> *TypeList;
896 llvm::PATypeHolder *TypeVal;
897 llvm::Value *ValueVal;
898 std::vector<llvm::Value*> *ValueList;
899 llvm::ArgListType *ArgList;
900 llvm::TypeWithAttrs TypeWithAttrs;
901 llvm::TypeWithAttrsList *TypeWithAttrsList;
902 llvm::ValueRefList *ValueRefList;
904 // Represent the RHS of PHI node
905 std::list<std::pair<llvm::Value*,
906 llvm::BasicBlock*> > *PHIList;
907 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
908 std::vector<llvm::Constant*> *ConstVector;
910 llvm::GlobalValue::LinkageTypes Linkage;
911 llvm::GlobalValue::VisibilityTypes Visibility;
912 llvm::FunctionType::ParameterAttributes ParamAttrs;
920 char *StrVal; // This memory is strdup'd!
921 llvm::ValID ValIDVal; // strdup'd memory maybe!
923 llvm::Instruction::BinaryOps BinaryOpVal;
924 llvm::Instruction::TermOps TermOpVal;
925 llvm::Instruction::MemoryOps MemOpVal;
926 llvm::Instruction::CastOps CastOpVal;
927 llvm::Instruction::OtherOps OtherOpVal;
928 llvm::ICmpInst::Predicate IPredicate;
929 llvm::FCmpInst::Predicate FPredicate;
932 %type <ModuleVal> Module
933 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
934 %type <BasicBlockVal> BasicBlock InstructionList
935 %type <TermInstVal> BBTerminatorInst
936 %type <InstVal> Inst InstVal MemoryInst
937 %type <ConstVal> ConstVal ConstExpr
938 %type <ConstVector> ConstVector
939 %type <ArgList> ArgList ArgListH
940 %type <PHIList> PHIList
941 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
942 %type <ValueList> IndexList // For GEP indices
943 %type <TypeList> TypeListI
944 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
945 %type <TypeWithAttrs> ArgType
946 %type <JumpTable> JumpTable
947 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
948 %type <BoolVal> OptVolatile // 'volatile' or not
949 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
950 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
951 %type <Linkage> GVInternalLinkage GVExternalLinkage
952 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
953 %type <Visibility> GVVisibilityStyle
955 // ValueRef - Unresolved reference to a definition or BB
956 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
957 %type <ValueVal> ResolvedVal // <type> <valref> pair
958 // Tokens and types for handling constant integer values
960 // ESINT64VAL - A negative number within long long range
961 %token <SInt64Val> ESINT64VAL
963 // EUINT64VAL - A positive number within uns. long long range
964 %token <UInt64Val> EUINT64VAL
966 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
967 %token <FPVal> FPVAL // Float or Double constant
970 %type <TypeVal> Types ResultTypes
971 %type <PrimType> IntType FPType PrimType // Classifications
972 %token <PrimType> VOID INTTYPE
973 %token <PrimType> FLOAT DOUBLE LABEL
976 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR STRINGCONSTANT ATSTRINGCONSTANT
977 %type <StrVal> LocalName OptLocalName OptLocalAssign
978 %type <StrVal> GlobalName OptGlobalAssign
979 %type <UIntVal> OptAlign OptCAlign
980 %type <StrVal> OptSection SectionString
982 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
983 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
984 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
985 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
986 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
987 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
988 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
990 %type <UIntVal> OptCallingConv
991 %type <ParamAttrs> OptParamAttrs ParamAttr
992 %type <ParamAttrs> OptFuncAttrs FuncAttr
994 // Basic Block Terminating Operators
995 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
998 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
999 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1000 %token <OtherOpVal> ICMP FCMP
1001 %type <IPredicate> IPredicates
1002 %type <FPredicate> FPredicates
1003 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1004 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1006 // Memory Instructions
1007 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1010 %type <CastOpVal> CastOps
1011 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1012 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1015 %type <OtherOpVal> ShiftOps
1016 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1017 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1019 // Function Attributes
1020 %token NORETURN INREG SRET
1022 // Visibility Styles
1023 %token DEFAULT HIDDEN
1029 // Operations that are notably excluded from this list include:
1030 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1032 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1033 LogicalOps : AND | OR | XOR;
1034 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1035 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1036 ShiftOps : SHL | LSHR | ASHR;
1038 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1039 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1040 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1041 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1042 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1046 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1047 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1048 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1049 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1050 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1051 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1052 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1053 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1054 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1057 // These are some types that allow classification if we only want a particular
1058 // thing... for example, only a signed, unsigned, or integral type.
1060 FPType : FLOAT | DOUBLE;
1062 LocalName : LOCALVAR | STRINGCONSTANT;
1063 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1065 /// OptLocalAssign - Value producing statements have an optional assignment
1067 OptLocalAssign : LocalName '=' {
1076 GlobalName : GLOBALVAR | ATSTRINGCONSTANT;
1078 OptGlobalAssign : GlobalName '=' {
1088 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1089 | WEAK { $$ = GlobalValue::WeakLinkage; }
1090 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1091 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1092 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1096 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1097 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1098 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1102 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1103 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1106 FunctionDeclareLinkage
1107 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1108 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1109 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1112 FunctionDefineLinkage
1113 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1114 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1115 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1116 | WEAK { $$ = GlobalValue::WeakLinkage; }
1117 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1120 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1121 CCC_TOK { $$ = CallingConv::C; } |
1122 FASTCC_TOK { $$ = CallingConv::Fast; } |
1123 COLDCC_TOK { $$ = CallingConv::Cold; } |
1124 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1125 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1127 if ((unsigned)$2 != $2)
1128 GEN_ERROR("Calling conv too large!");
1133 ParamAttr : ZEXT { $$ = FunctionType::ZExtAttribute; }
1134 | SEXT { $$ = FunctionType::SExtAttribute; }
1135 | INREG { $$ = FunctionType::InRegAttribute; }
1136 | SRET { $$ = FunctionType::StructRetAttribute; }
1139 OptParamAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1140 | OptParamAttrs ParamAttr {
1141 $$ = FunctionType::ParameterAttributes($1 | $2);
1145 FuncAttr : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1149 OptFuncAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1150 | OptFuncAttrs FuncAttr {
1151 $$ = FunctionType::ParameterAttributes($1 | $2);
1155 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1156 // a comma before it.
1157 OptAlign : /*empty*/ { $$ = 0; } |
1160 if ($$ != 0 && !isPowerOf2_32($$))
1161 GEN_ERROR("Alignment must be a power of two!");
1164 OptCAlign : /*empty*/ { $$ = 0; } |
1165 ',' ALIGN EUINT64VAL {
1167 if ($$ != 0 && !isPowerOf2_32($$))
1168 GEN_ERROR("Alignment must be a power of two!");
1173 SectionString : SECTION STRINGCONSTANT {
1174 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1175 if ($2[i] == '"' || $2[i] == '\\')
1176 GEN_ERROR("Invalid character in section name!");
1181 OptSection : /*empty*/ { $$ = 0; } |
1182 SectionString { $$ = $1; };
1184 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1185 // is set to be the global we are processing.
1187 GlobalVarAttributes : /* empty */ {} |
1188 ',' GlobalVarAttribute GlobalVarAttributes {};
1189 GlobalVarAttribute : SectionString {
1190 CurGV->setSection($1);
1194 | ALIGN EUINT64VAL {
1195 if ($2 != 0 && !isPowerOf2_32($2))
1196 GEN_ERROR("Alignment must be a power of two!");
1197 CurGV->setAlignment($2);
1201 //===----------------------------------------------------------------------===//
1202 // Types includes all predefined types... except void, because it can only be
1203 // used in specific contexts (function returning void for example).
1205 // Derived types are added later...
1207 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1211 $$ = new PATypeHolder(OpaqueType::get());
1215 $$ = new PATypeHolder($1);
1218 | Types '*' { // Pointer type?
1219 if (*$1 == Type::LabelTy)
1220 GEN_ERROR("Cannot form a pointer to a basic block");
1221 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1225 | SymbolicValueRef { // Named types are also simple types...
1226 const Type* tmp = getTypeVal($1);
1228 $$ = new PATypeHolder(tmp);
1230 | '\\' EUINT64VAL { // Type UpReference
1231 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1232 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1233 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1234 $$ = new PATypeHolder(OT);
1235 UR_OUT("New Upreference!\n");
1238 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1239 std::vector<const Type*> Params;
1240 std::vector<FunctionType::ParameterAttributes> Attrs;
1241 Attrs.push_back($5);
1242 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1243 Params.push_back(I->Ty->get());
1244 if (I->Ty->get() != Type::VoidTy)
1245 Attrs.push_back(I->Attrs);
1247 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1248 if (isVarArg) Params.pop_back();
1250 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1251 delete $3; // Delete the argument list
1252 delete $1; // Delete the return type handle
1253 $$ = new PATypeHolder(HandleUpRefs(FT));
1256 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1257 std::vector<const Type*> Params;
1258 std::vector<FunctionType::ParameterAttributes> Attrs;
1259 Attrs.push_back($5);
1260 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1261 Params.push_back(I->Ty->get());
1262 if (I->Ty->get() != Type::VoidTy)
1263 Attrs.push_back(I->Attrs);
1265 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1266 if (isVarArg) Params.pop_back();
1268 FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1269 delete $3; // Delete the argument list
1270 $$ = new PATypeHolder(HandleUpRefs(FT));
1274 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1275 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1279 | '<' EUINT64VAL 'x' Types '>' { // Packed array type?
1280 const llvm::Type* ElemTy = $4->get();
1281 if ((unsigned)$2 != $2)
1282 GEN_ERROR("Unsigned result not equal to signed result");
1283 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1284 GEN_ERROR("Element type of a PackedType must be primitive");
1285 if (!isPowerOf2_32($2))
1286 GEN_ERROR("Vector length should be a power of 2!");
1287 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1291 | '{' TypeListI '}' { // Structure type?
1292 std::vector<const Type*> Elements;
1293 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1294 E = $2->end(); I != E; ++I)
1295 Elements.push_back(*I);
1297 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1301 | '{' '}' { // Empty structure type?
1302 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1305 | '<' '{' TypeListI '}' '>' {
1306 std::vector<const Type*> Elements;
1307 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1308 E = $3->end(); I != E; ++I)
1309 Elements.push_back(*I);
1311 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1315 | '<' '{' '}' '>' { // Empty structure type?
1316 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1322 : Types OptParamAttrs {
1330 if (!UpRefs.empty())
1331 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1332 if (!(*$1)->isFirstClassType())
1333 GEN_ERROR("LLVM functions cannot return aggregate types!");
1337 $$ = new PATypeHolder(Type::VoidTy);
1341 ArgTypeList : ArgType {
1342 $$ = new TypeWithAttrsList();
1346 | ArgTypeList ',' ArgType {
1347 ($$=$1)->push_back($3);
1354 | ArgTypeList ',' DOTDOTDOT {
1356 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1357 TWA.Ty = new PATypeHolder(Type::VoidTy);
1362 $$ = new TypeWithAttrsList;
1363 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1364 TWA.Ty = new PATypeHolder(Type::VoidTy);
1369 $$ = new TypeWithAttrsList();
1373 // TypeList - Used for struct declarations and as a basis for function type
1374 // declaration type lists
1377 $$ = new std::list<PATypeHolder>();
1378 $$->push_back(*$1); delete $1;
1381 | TypeListI ',' Types {
1382 ($$=$1)->push_back(*$3); delete $3;
1386 // ConstVal - The various declarations that go into the constant pool. This
1387 // production is used ONLY to represent constants that show up AFTER a 'const',
1388 // 'constant' or 'global' token at global scope. Constants that can be inlined
1389 // into other expressions (such as integers and constexprs) are handled by the
1390 // ResolvedVal, ValueRef and ConstValueRef productions.
1392 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1393 if (!UpRefs.empty())
1394 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1395 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1397 GEN_ERROR("Cannot make array constant with type: '" +
1398 (*$1)->getDescription() + "'!");
1399 const Type *ETy = ATy->getElementType();
1400 int NumElements = ATy->getNumElements();
1402 // Verify that we have the correct size...
1403 if (NumElements != -1 && NumElements != (int)$3->size())
1404 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1405 utostr($3->size()) + " arguments, but has size of " +
1406 itostr(NumElements) + "!");
1408 // Verify all elements are correct type!
1409 for (unsigned i = 0; i < $3->size(); i++) {
1410 if (ETy != (*$3)[i]->getType())
1411 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1412 ETy->getDescription() +"' as required!\nIt is of type '"+
1413 (*$3)[i]->getType()->getDescription() + "'.");
1416 $$ = ConstantArray::get(ATy, *$3);
1417 delete $1; delete $3;
1421 if (!UpRefs.empty())
1422 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1423 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1425 GEN_ERROR("Cannot make array constant with type: '" +
1426 (*$1)->getDescription() + "'!");
1428 int NumElements = ATy->getNumElements();
1429 if (NumElements != -1 && NumElements != 0)
1430 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1431 " arguments, but has size of " + itostr(NumElements) +"!");
1432 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1436 | Types 'c' STRINGCONSTANT {
1437 if (!UpRefs.empty())
1438 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1439 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1441 GEN_ERROR("Cannot make array constant with type: '" +
1442 (*$1)->getDescription() + "'!");
1444 int NumElements = ATy->getNumElements();
1445 const Type *ETy = ATy->getElementType();
1446 char *EndStr = UnEscapeLexed($3, true);
1447 if (NumElements != -1 && NumElements != (EndStr-$3))
1448 GEN_ERROR("Can't build string constant of size " +
1449 itostr((int)(EndStr-$3)) +
1450 " when array has size " + itostr(NumElements) + "!");
1451 std::vector<Constant*> Vals;
1452 if (ETy == Type::Int8Ty) {
1453 for (unsigned char *C = (unsigned char *)$3;
1454 C != (unsigned char*)EndStr; ++C)
1455 Vals.push_back(ConstantInt::get(ETy, *C));
1458 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1461 $$ = ConstantArray::get(ATy, Vals);
1465 | Types '<' ConstVector '>' { // Nonempty unsized arr
1466 if (!UpRefs.empty())
1467 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1468 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1470 GEN_ERROR("Cannot make packed constant with type: '" +
1471 (*$1)->getDescription() + "'!");
1472 const Type *ETy = PTy->getElementType();
1473 int NumElements = PTy->getNumElements();
1475 // Verify that we have the correct size...
1476 if (NumElements != -1 && NumElements != (int)$3->size())
1477 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1478 utostr($3->size()) + " arguments, but has size of " +
1479 itostr(NumElements) + "!");
1481 // Verify all elements are correct type!
1482 for (unsigned i = 0; i < $3->size(); i++) {
1483 if (ETy != (*$3)[i]->getType())
1484 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1485 ETy->getDescription() +"' as required!\nIt is of type '"+
1486 (*$3)[i]->getType()->getDescription() + "'.");
1489 $$ = ConstantPacked::get(PTy, *$3);
1490 delete $1; delete $3;
1493 | Types '{' ConstVector '}' {
1494 const StructType *STy = dyn_cast<StructType>($1->get());
1496 GEN_ERROR("Cannot make struct constant with type: '" +
1497 (*$1)->getDescription() + "'!");
1499 if ($3->size() != STy->getNumContainedTypes())
1500 GEN_ERROR("Illegal number of initializers for structure type!");
1502 // Check to ensure that constants are compatible with the type initializer!
1503 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1504 if ((*$3)[i]->getType() != STy->getElementType(i))
1505 GEN_ERROR("Expected type '" +
1506 STy->getElementType(i)->getDescription() +
1507 "' for element #" + utostr(i) +
1508 " of structure initializer!");
1510 // Check to ensure that Type is not packed
1511 if (STy->isPacked())
1512 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1514 $$ = ConstantStruct::get(STy, *$3);
1515 delete $1; delete $3;
1519 if (!UpRefs.empty())
1520 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1521 const StructType *STy = dyn_cast<StructType>($1->get());
1523 GEN_ERROR("Cannot make struct constant with type: '" +
1524 (*$1)->getDescription() + "'!");
1526 if (STy->getNumContainedTypes() != 0)
1527 GEN_ERROR("Illegal number of initializers for structure type!");
1529 // Check to ensure that Type is not packed
1530 if (STy->isPacked())
1531 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1533 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1537 | Types '<' '{' ConstVector '}' '>' {
1538 const StructType *STy = dyn_cast<StructType>($1->get());
1540 GEN_ERROR("Cannot make struct constant with type: '" +
1541 (*$1)->getDescription() + "'!");
1543 if ($4->size() != STy->getNumContainedTypes())
1544 GEN_ERROR("Illegal number of initializers for structure type!");
1546 // Check to ensure that constants are compatible with the type initializer!
1547 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1548 if ((*$4)[i]->getType() != STy->getElementType(i))
1549 GEN_ERROR("Expected type '" +
1550 STy->getElementType(i)->getDescription() +
1551 "' for element #" + utostr(i) +
1552 " of structure initializer!");
1554 // Check to ensure that Type is packed
1555 if (!STy->isPacked())
1556 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1558 $$ = ConstantStruct::get(STy, *$4);
1559 delete $1; delete $4;
1562 | Types '<' '{' '}' '>' {
1563 if (!UpRefs.empty())
1564 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1565 const StructType *STy = dyn_cast<StructType>($1->get());
1567 GEN_ERROR("Cannot make struct constant with type: '" +
1568 (*$1)->getDescription() + "'!");
1570 if (STy->getNumContainedTypes() != 0)
1571 GEN_ERROR("Illegal number of initializers for structure type!");
1573 // Check to ensure that Type is packed
1574 if (!STy->isPacked())
1575 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1577 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1582 if (!UpRefs.empty())
1583 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1584 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1586 GEN_ERROR("Cannot make null pointer constant with type: '" +
1587 (*$1)->getDescription() + "'!");
1589 $$ = ConstantPointerNull::get(PTy);
1594 if (!UpRefs.empty())
1595 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1596 $$ = UndefValue::get($1->get());
1600 | Types SymbolicValueRef {
1601 if (!UpRefs.empty())
1602 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1603 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1605 GEN_ERROR("Global const reference must be a pointer type!");
1607 // ConstExprs can exist in the body of a function, thus creating
1608 // GlobalValues whenever they refer to a variable. Because we are in
1609 // the context of a function, getValNonImprovising will search the functions
1610 // symbol table instead of the module symbol table for the global symbol,
1611 // which throws things all off. To get around this, we just tell
1612 // getValNonImprovising that we are at global scope here.
1614 Function *SavedCurFn = CurFun.CurrentFunction;
1615 CurFun.CurrentFunction = 0;
1617 Value *V = getValNonImprovising(Ty, $2);
1620 CurFun.CurrentFunction = SavedCurFn;
1622 // If this is an initializer for a constant pointer, which is referencing a
1623 // (currently) undefined variable, create a stub now that shall be replaced
1624 // in the future with the right type of variable.
1627 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1628 const PointerType *PT = cast<PointerType>(Ty);
1630 // First check to see if the forward references value is already created!
1631 PerModuleInfo::GlobalRefsType::iterator I =
1632 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1634 if (I != CurModule.GlobalRefs.end()) {
1635 V = I->second; // Placeholder already exists, use it...
1639 if ($2.Type == ValID::GlobalName)
1641 else if ($2.Type != ValID::GlobalID)
1642 GEN_ERROR("Invalid reference to global");
1644 // Create the forward referenced global.
1646 if (const FunctionType *FTy =
1647 dyn_cast<FunctionType>(PT->getElementType())) {
1648 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1649 CurModule.CurrentModule);
1651 GV = new GlobalVariable(PT->getElementType(), false,
1652 GlobalValue::ExternalLinkage, 0,
1653 Name, CurModule.CurrentModule);
1656 // Keep track of the fact that we have a forward ref to recycle it
1657 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1662 $$ = cast<GlobalValue>(V);
1663 delete $1; // Free the type handle
1667 if (!UpRefs.empty())
1668 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1669 if ($1->get() != $2->getType())
1670 GEN_ERROR("Mismatched types for constant expression: " +
1671 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1676 | Types ZEROINITIALIZER {
1677 if (!UpRefs.empty())
1678 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1679 const Type *Ty = $1->get();
1680 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1681 GEN_ERROR("Cannot create a null initialized value of this type!");
1682 $$ = Constant::getNullValue(Ty);
1686 | IntType ESINT64VAL { // integral constants
1687 if (!ConstantInt::isValueValidForType($1, $2))
1688 GEN_ERROR("Constant value doesn't fit in type!");
1689 $$ = ConstantInt::get($1, $2);
1692 | IntType EUINT64VAL { // integral constants
1693 if (!ConstantInt::isValueValidForType($1, $2))
1694 GEN_ERROR("Constant value doesn't fit in type!");
1695 $$ = ConstantInt::get($1, $2);
1698 | INTTYPE TRUETOK { // Boolean constants
1699 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1700 $$ = ConstantInt::getTrue();
1703 | INTTYPE FALSETOK { // Boolean constants
1704 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1705 $$ = ConstantInt::getFalse();
1708 | FPType FPVAL { // Float & Double constants
1709 if (!ConstantFP::isValueValidForType($1, $2))
1710 GEN_ERROR("Floating point constant invalid for type!!");
1711 $$ = ConstantFP::get($1, $2);
1716 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1717 if (!UpRefs.empty())
1718 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1720 const Type *DestTy = $5->get();
1721 if (!CastInst::castIsValid($1, $3, DestTy))
1722 GEN_ERROR("invalid cast opcode for cast from '" +
1723 Val->getType()->getDescription() + "' to '" +
1724 DestTy->getDescription() + "'!");
1725 $$ = ConstantExpr::getCast($1, $3, DestTy);
1728 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1729 if (!isa<PointerType>($3->getType()))
1730 GEN_ERROR("GetElementPtr requires a pointer operand!");
1733 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1735 GEN_ERROR("Index list invalid for constant getelementptr!");
1737 SmallVector<Constant*, 8> IdxVec;
1738 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1739 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1740 IdxVec.push_back(C);
1742 GEN_ERROR("Indices to constant getelementptr must be constants!");
1746 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1749 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1750 if ($3->getType() != Type::Int1Ty)
1751 GEN_ERROR("Select condition must be of boolean type!");
1752 if ($5->getType() != $7->getType())
1753 GEN_ERROR("Select operand types must match!");
1754 $$ = ConstantExpr::getSelect($3, $5, $7);
1757 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1758 if ($3->getType() != $5->getType())
1759 GEN_ERROR("Binary operator types must match!");
1761 $$ = ConstantExpr::get($1, $3, $5);
1763 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1764 if ($3->getType() != $5->getType())
1765 GEN_ERROR("Logical operator types must match!");
1766 if (!$3->getType()->isInteger()) {
1767 if (!isa<PackedType>($3->getType()) ||
1768 !cast<PackedType>($3->getType())->getElementType()->isInteger())
1769 GEN_ERROR("Logical operator requires integral operands!");
1771 $$ = ConstantExpr::get($1, $3, $5);
1774 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1775 if ($4->getType() != $6->getType())
1776 GEN_ERROR("icmp operand types must match!");
1777 $$ = ConstantExpr::getICmp($2, $4, $6);
1779 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1780 if ($4->getType() != $6->getType())
1781 GEN_ERROR("fcmp operand types must match!");
1782 $$ = ConstantExpr::getFCmp($2, $4, $6);
1784 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1785 if ($5->getType() != Type::Int8Ty)
1786 GEN_ERROR("Shift count for shift constant must be i8 type!");
1787 if (!$3->getType()->isInteger())
1788 GEN_ERROR("Shift constant expression requires integer operand!");
1790 $$ = ConstantExpr::get($1, $3, $5);
1793 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1794 if (!ExtractElementInst::isValidOperands($3, $5))
1795 GEN_ERROR("Invalid extractelement operands!");
1796 $$ = ConstantExpr::getExtractElement($3, $5);
1799 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1800 if (!InsertElementInst::isValidOperands($3, $5, $7))
1801 GEN_ERROR("Invalid insertelement operands!");
1802 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1805 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1806 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1807 GEN_ERROR("Invalid shufflevector operands!");
1808 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1813 // ConstVector - A list of comma separated constants.
1814 ConstVector : ConstVector ',' ConstVal {
1815 ($$ = $1)->push_back($3);
1819 $$ = new std::vector<Constant*>();
1825 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1826 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1829 //===----------------------------------------------------------------------===//
1830 // Rules to match Modules
1831 //===----------------------------------------------------------------------===//
1833 // Module rule: Capture the result of parsing the whole file into a result
1838 $$ = ParserResult = CurModule.CurrentModule;
1839 CurModule.ModuleDone();
1843 $$ = ParserResult = CurModule.CurrentModule;
1844 CurModule.ModuleDone();
1851 | DefinitionList Definition
1855 : DEFINE { CurFun.isDeclare = false; } Function {
1856 CurFun.FunctionDone();
1859 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1862 | MODULE ASM_TOK AsmBlock {
1866 // Emit an error if there are any unresolved types left.
1867 if (!CurModule.LateResolveTypes.empty()) {
1868 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1869 if (DID.Type == ValID::LocalName) {
1870 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1872 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1877 | OptLocalAssign TYPE Types {
1878 if (!UpRefs.empty())
1879 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1880 // Eagerly resolve types. This is not an optimization, this is a
1881 // requirement that is due to the fact that we could have this:
1883 // %list = type { %list * }
1884 // %list = type { %list * } ; repeated type decl
1886 // If types are not resolved eagerly, then the two types will not be
1887 // determined to be the same type!
1889 ResolveTypeTo($1, *$3);
1891 if (!setTypeName(*$3, $1) && !$1) {
1893 // If this is a named type that is not a redefinition, add it to the slot
1895 CurModule.Types.push_back(*$3);
1901 | OptLocalAssign TYPE VOID {
1902 ResolveTypeTo($1, $3);
1904 if (!setTypeName($3, $1) && !$1) {
1906 // If this is a named type that is not a redefinition, add it to the slot
1908 CurModule.Types.push_back($3);
1912 | OptGlobalAssign GVVisibilityStyle GlobalType ConstVal {
1913 /* "Externally Visible" Linkage */
1915 GEN_ERROR("Global value initializer is not a constant!");
1916 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
1917 $2, $3, $4->getType(), $4);
1919 } GlobalVarAttributes {
1922 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle GlobalType ConstVal {
1924 GEN_ERROR("Global value initializer is not a constant!");
1925 CurGV = ParseGlobalVariable($1, $2, $3, $4, $5->getType(), $5);
1927 } GlobalVarAttributes {
1930 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle GlobalType Types {
1931 if (!UpRefs.empty())
1932 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1933 CurGV = ParseGlobalVariable($1, $2, $3, $4, *$5, 0);
1936 } GlobalVarAttributes {
1940 | TARGET TargetDefinition {
1943 | DEPLIBS '=' LibrariesDefinition {
1949 AsmBlock : STRINGCONSTANT {
1950 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1951 char *EndStr = UnEscapeLexed($1, true);
1952 std::string NewAsm($1, EndStr);
1955 if (AsmSoFar.empty())
1956 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1958 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1962 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
1963 CurModule.CurrentModule->setTargetTriple($3);
1966 | DATALAYOUT '=' STRINGCONSTANT {
1967 CurModule.CurrentModule->setDataLayout($3);
1971 LibrariesDefinition : '[' LibList ']';
1973 LibList : LibList ',' STRINGCONSTANT {
1974 CurModule.CurrentModule->addLibrary($3);
1979 CurModule.CurrentModule->addLibrary($1);
1983 | /* empty: end of list */ {
1988 //===----------------------------------------------------------------------===//
1989 // Rules to match Function Headers
1990 //===----------------------------------------------------------------------===//
1992 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
1993 if (!UpRefs.empty())
1994 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1995 if (*$3 == Type::VoidTy)
1996 GEN_ERROR("void typed arguments are invalid!");
1997 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2002 | Types OptParamAttrs OptLocalName {
2003 if (!UpRefs.empty())
2004 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2005 if (*$1 == Type::VoidTy)
2006 GEN_ERROR("void typed arguments are invalid!");
2007 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2008 $$ = new ArgListType;
2013 ArgList : ArgListH {
2017 | ArgListH ',' DOTDOTDOT {
2019 struct ArgListEntry E;
2020 E.Ty = new PATypeHolder(Type::VoidTy);
2022 E.Attrs = FunctionType::NoAttributeSet;
2027 $$ = new ArgListType;
2028 struct ArgListEntry E;
2029 E.Ty = new PATypeHolder(Type::VoidTy);
2031 E.Attrs = FunctionType::NoAttributeSet;
2040 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2041 OptFuncAttrs OptSection OptAlign {
2043 std::string FunctionName($3);
2044 free($3); // Free strdup'd memory!
2046 // Check the function result for abstractness if this is a define. We should
2047 // have no abstract types at this point
2048 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2049 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2051 std::vector<const Type*> ParamTypeList;
2052 std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2053 ParamAttrs.push_back($7);
2054 if ($5) { // If there are arguments...
2055 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2056 const Type* Ty = I->Ty->get();
2057 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2058 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2059 ParamTypeList.push_back(Ty);
2060 if (Ty != Type::VoidTy)
2061 ParamAttrs.push_back(I->Attrs);
2065 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2066 if (isVarArg) ParamTypeList.pop_back();
2068 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2070 const PointerType *PFT = PointerType::get(FT);
2074 if (!FunctionName.empty()) {
2075 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2077 ID = ValID::createGlobalID(CurModule.Values[PFT].size());
2081 // See if this function was forward referenced. If so, recycle the object.
2082 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2083 // Move the function to the end of the list, from whereever it was
2084 // previously inserted.
2085 Fn = cast<Function>(FWRef);
2086 CurModule.CurrentModule->getFunctionList().remove(Fn);
2087 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2088 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2089 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2090 // If this is the case, either we need to be a forward decl, or it needs
2092 if (!CurFun.isDeclare && !Fn->isDeclaration())
2093 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2095 // Make sure to strip off any argument names so we can't get conflicts.
2096 if (Fn->isDeclaration())
2097 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2100 } else { // Not already defined?
2101 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2102 CurModule.CurrentModule);
2104 InsertValue(Fn, CurModule.Values);
2107 CurFun.FunctionStart(Fn);
2109 if (CurFun.isDeclare) {
2110 // If we have declaration, always overwrite linkage. This will allow us to
2111 // correctly handle cases, when pointer to function is passed as argument to
2112 // another function.
2113 Fn->setLinkage(CurFun.Linkage);
2114 Fn->setVisibility(CurFun.Visibility);
2116 Fn->setCallingConv($1);
2117 Fn->setAlignment($9);
2123 // Add all of the arguments we parsed to the function...
2124 if ($5) { // Is null if empty...
2125 if (isVarArg) { // Nuke the last entry
2126 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0&&
2127 "Not a varargs marker!");
2128 delete $5->back().Ty;
2129 $5->pop_back(); // Delete the last entry
2131 Function::arg_iterator ArgIt = Fn->arg_begin();
2133 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++ArgIt) {
2134 delete I->Ty; // Delete the typeholder...
2135 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2141 delete $5; // We're now done with the argument list
2146 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2148 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2149 $$ = CurFun.CurrentFunction;
2151 // Make sure that we keep track of the linkage type even if there was a
2152 // previous "declare".
2154 $$->setVisibility($2);
2157 END : ENDTOK | '}'; // Allow end of '}' to end a function
2159 Function : BasicBlockList END {
2164 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2165 CurFun.CurrentFunction->setLinkage($1);
2166 CurFun.CurrentFunction->setVisibility($2);
2167 $$ = CurFun.CurrentFunction;
2168 CurFun.FunctionDone();
2172 //===----------------------------------------------------------------------===//
2173 // Rules to match Basic Blocks
2174 //===----------------------------------------------------------------------===//
2176 OptSideEffect : /* empty */ {
2185 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2186 $$ = ValID::create($1);
2190 $$ = ValID::create($1);
2193 | FPVAL { // Perhaps it's an FP constant?
2194 $$ = ValID::create($1);
2198 $$ = ValID::create(ConstantInt::getTrue());
2202 $$ = ValID::create(ConstantInt::getFalse());
2206 $$ = ValID::createNull();
2210 $$ = ValID::createUndef();
2213 | ZEROINITIALIZER { // A vector zero constant.
2214 $$ = ValID::createZeroInit();
2217 | '<' ConstVector '>' { // Nonempty unsized packed vector
2218 const Type *ETy = (*$2)[0]->getType();
2219 int NumElements = $2->size();
2221 PackedType* pt = PackedType::get(ETy, NumElements);
2222 PATypeHolder* PTy = new PATypeHolder(
2230 // Verify all elements are correct type!
2231 for (unsigned i = 0; i < $2->size(); i++) {
2232 if (ETy != (*$2)[i]->getType())
2233 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2234 ETy->getDescription() +"' as required!\nIt is of type '" +
2235 (*$2)[i]->getType()->getDescription() + "'.");
2238 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2239 delete PTy; delete $2;
2243 $$ = ValID::create($1);
2246 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2247 char *End = UnEscapeLexed($3, true);
2248 std::string AsmStr = std::string($3, End);
2249 End = UnEscapeLexed($5, true);
2250 std::string Constraints = std::string($5, End);
2251 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2257 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2260 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2261 $$ = ValID::createLocalID($1);
2265 $$ = ValID::createGlobalID($1);
2268 | LocalName { // Is it a named reference...?
2269 $$ = ValID::createLocalName($1);
2272 | GlobalName { // Is it a named reference...?
2273 $$ = ValID::createGlobalName($1);
2277 // ValueRef - A reference to a definition... either constant or symbolic
2278 ValueRef : SymbolicValueRef | ConstValueRef;
2281 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2282 // type immediately preceeds the value reference, and allows complex constant
2283 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2284 ResolvedVal : Types ValueRef {
2285 if (!UpRefs.empty())
2286 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2287 $$ = getVal(*$1, $2);
2293 BasicBlockList : BasicBlockList BasicBlock {
2297 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2303 // Basic blocks are terminated by branching instructions:
2304 // br, br/cc, switch, ret
2306 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2307 setValueName($3, $2);
2311 $1->getInstList().push_back($3);
2317 InstructionList : InstructionList Inst {
2318 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2319 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2320 if (CI2->getParent() == 0)
2321 $1->getInstList().push_back(CI2);
2322 $1->getInstList().push_back($2);
2327 $$ = getBBVal(ValID::createLocalID(CurFun.NextBBNum++), true);
2330 // Make sure to move the basic block to the correct location in the
2331 // function, instead of leaving it inserted wherever it was first
2333 Function::BasicBlockListType &BBL =
2334 CurFun.CurrentFunction->getBasicBlockList();
2335 BBL.splice(BBL.end(), BBL, $$);
2339 $$ = getBBVal(ValID::createLocalName($1), true);
2342 // Make sure to move the basic block to the correct location in the
2343 // function, instead of leaving it inserted wherever it was first
2345 Function::BasicBlockListType &BBL =
2346 CurFun.CurrentFunction->getBasicBlockList();
2347 BBL.splice(BBL.end(), BBL, $$);
2351 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2352 $$ = new ReturnInst($2);
2355 | RET VOID { // Return with no result...
2356 $$ = new ReturnInst();
2359 | BR LABEL ValueRef { // Unconditional Branch...
2360 BasicBlock* tmpBB = getBBVal($3);
2362 $$ = new BranchInst(tmpBB);
2363 } // Conditional Branch...
2364 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2365 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2366 BasicBlock* tmpBBA = getBBVal($6);
2368 BasicBlock* tmpBBB = getBBVal($9);
2370 Value* tmpVal = getVal(Type::Int1Ty, $3);
2372 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2374 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2375 Value* tmpVal = getVal($2, $3);
2377 BasicBlock* tmpBB = getBBVal($6);
2379 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2382 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2384 for (; I != E; ++I) {
2385 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2386 S->addCase(CI, I->second);
2388 GEN_ERROR("Switch case is constant, but not a simple integer!");
2393 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2394 Value* tmpVal = getVal($2, $3);
2396 BasicBlock* tmpBB = getBBVal($6);
2398 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2402 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2403 TO LABEL ValueRef UNWIND LABEL ValueRef {
2405 // Handle the short syntax
2406 const PointerType *PFTy = 0;
2407 const FunctionType *Ty = 0;
2408 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2409 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2410 // Pull out the types of all of the arguments...
2411 std::vector<const Type*> ParamTypes;
2412 FunctionType::ParamAttrsList ParamAttrs;
2413 ParamAttrs.push_back($8);
2414 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2415 const Type *Ty = I->Val->getType();
2416 if (Ty == Type::VoidTy)
2417 GEN_ERROR("Short call syntax cannot be used with varargs");
2418 ParamTypes.push_back(Ty);
2419 ParamAttrs.push_back(I->Attrs);
2422 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2423 PFTy = PointerType::get(Ty);
2426 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2428 BasicBlock *Normal = getBBVal($11);
2430 BasicBlock *Except = getBBVal($14);
2433 // Check the arguments
2435 if ($6->empty()) { // Has no arguments?
2436 // Make sure no arguments is a good thing!
2437 if (Ty->getNumParams() != 0)
2438 GEN_ERROR("No arguments passed to a function that "
2439 "expects arguments!");
2440 } else { // Has arguments?
2441 // Loop through FunctionType's arguments and ensure they are specified
2443 FunctionType::param_iterator I = Ty->param_begin();
2444 FunctionType::param_iterator E = Ty->param_end();
2445 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2447 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2448 if (ArgI->Val->getType() != *I)
2449 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2450 (*I)->getDescription() + "'!");
2451 Args.push_back(ArgI->Val);
2454 if (Ty->isVarArg()) {
2456 for (; ArgI != ArgE; ++ArgI)
2457 Args.push_back(ArgI->Val); // push the remaining varargs
2458 } else if (I != E || ArgI != ArgE)
2459 GEN_ERROR("Invalid number of parameters detected!");
2462 // Create the InvokeInst
2463 InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2464 II->setCallingConv($2);
2470 $$ = new UnwindInst();
2474 $$ = new UnreachableInst();
2480 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2482 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2485 GEN_ERROR("May only switch on a constant pool value!");
2487 BasicBlock* tmpBB = getBBVal($6);
2489 $$->push_back(std::make_pair(V, tmpBB));
2491 | IntType ConstValueRef ',' LABEL ValueRef {
2492 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2493 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2497 GEN_ERROR("May only switch on a constant pool value!");
2499 BasicBlock* tmpBB = getBBVal($5);
2501 $$->push_back(std::make_pair(V, tmpBB));
2504 Inst : OptLocalAssign InstVal {
2505 // Is this definition named?? if so, assign the name...
2506 setValueName($2, $1);
2513 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2514 if (!UpRefs.empty())
2515 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2516 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2517 Value* tmpVal = getVal(*$1, $3);
2519 BasicBlock* tmpBB = getBBVal($5);
2521 $$->push_back(std::make_pair(tmpVal, tmpBB));
2524 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2526 Value* tmpVal = getVal($1->front().first->getType(), $4);
2528 BasicBlock* tmpBB = getBBVal($6);
2530 $1->push_back(std::make_pair(tmpVal, tmpBB));
2534 ValueRefList : Types ValueRef OptParamAttrs {
2535 if (!UpRefs.empty())
2536 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2537 // Used for call and invoke instructions
2538 $$ = new ValueRefList();
2539 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2542 | ValueRefList ',' Types ValueRef OptParamAttrs {
2543 if (!UpRefs.empty())
2544 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2546 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2550 | /*empty*/ { $$ = new ValueRefList(); };
2552 IndexList // Used for gep instructions and constant expressions
2553 : /*empty*/ { $$ = new std::vector<Value*>(); }
2554 | IndexList ',' ResolvedVal {
2561 OptTailCall : TAIL CALL {
2570 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2571 if (!UpRefs.empty())
2572 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2573 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2574 !isa<PackedType>((*$2).get()))
2576 "Arithmetic operator requires integer, FP, or packed operands!");
2577 if (isa<PackedType>((*$2).get()) &&
2578 ($1 == Instruction::URem ||
2579 $1 == Instruction::SRem ||
2580 $1 == Instruction::FRem))
2581 GEN_ERROR("U/S/FRem not supported on packed types!");
2582 Value* val1 = getVal(*$2, $3);
2584 Value* val2 = getVal(*$2, $5);
2586 $$ = BinaryOperator::create($1, val1, val2);
2588 GEN_ERROR("binary operator returned null!");
2591 | LogicalOps Types ValueRef ',' ValueRef {
2592 if (!UpRefs.empty())
2593 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2594 if (!(*$2)->isInteger()) {
2595 if (!isa<PackedType>($2->get()) ||
2596 !cast<PackedType>($2->get())->getElementType()->isInteger())
2597 GEN_ERROR("Logical operator requires integral operands!");
2599 Value* tmpVal1 = getVal(*$2, $3);
2601 Value* tmpVal2 = getVal(*$2, $5);
2603 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2605 GEN_ERROR("binary operator returned null!");
2608 | ICMP IPredicates Types ValueRef ',' ValueRef {
2609 if (!UpRefs.empty())
2610 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2611 if (isa<PackedType>((*$3).get()))
2612 GEN_ERROR("Packed types not supported by icmp instruction");
2613 Value* tmpVal1 = getVal(*$3, $4);
2615 Value* tmpVal2 = getVal(*$3, $6);
2617 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2619 GEN_ERROR("icmp operator returned null!");
2621 | FCMP FPredicates Types ValueRef ',' ValueRef {
2622 if (!UpRefs.empty())
2623 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2624 if (isa<PackedType>((*$3).get()))
2625 GEN_ERROR("Packed types not supported by fcmp instruction");
2626 Value* tmpVal1 = getVal(*$3, $4);
2628 Value* tmpVal2 = getVal(*$3, $6);
2630 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2632 GEN_ERROR("fcmp operator returned null!");
2634 | ShiftOps ResolvedVal ',' ResolvedVal {
2635 if ($4->getType() != Type::Int8Ty)
2636 GEN_ERROR("Shift amount must be i8 type!");
2637 if (!$2->getType()->isInteger())
2638 GEN_ERROR("Shift constant expression requires integer operand!");
2640 $$ = new ShiftInst($1, $2, $4);
2643 | CastOps ResolvedVal TO Types {
2644 if (!UpRefs.empty())
2645 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2647 const Type* DestTy = $4->get();
2648 if (!CastInst::castIsValid($1, Val, DestTy))
2649 GEN_ERROR("invalid cast opcode for cast from '" +
2650 Val->getType()->getDescription() + "' to '" +
2651 DestTy->getDescription() + "'!");
2652 $$ = CastInst::create($1, Val, DestTy);
2655 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2656 if ($2->getType() != Type::Int1Ty)
2657 GEN_ERROR("select condition must be boolean!");
2658 if ($4->getType() != $6->getType())
2659 GEN_ERROR("select value types should match!");
2660 $$ = new SelectInst($2, $4, $6);
2663 | VAARG ResolvedVal ',' Types {
2664 if (!UpRefs.empty())
2665 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2666 $$ = new VAArgInst($2, *$4);
2670 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2671 if (!ExtractElementInst::isValidOperands($2, $4))
2672 GEN_ERROR("Invalid extractelement operands!");
2673 $$ = new ExtractElementInst($2, $4);
2676 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2677 if (!InsertElementInst::isValidOperands($2, $4, $6))
2678 GEN_ERROR("Invalid insertelement operands!");
2679 $$ = new InsertElementInst($2, $4, $6);
2682 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2683 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2684 GEN_ERROR("Invalid shufflevector operands!");
2685 $$ = new ShuffleVectorInst($2, $4, $6);
2689 const Type *Ty = $2->front().first->getType();
2690 if (!Ty->isFirstClassType())
2691 GEN_ERROR("PHI node operands must be of first class type!");
2692 $$ = new PHINode(Ty);
2693 ((PHINode*)$$)->reserveOperandSpace($2->size());
2694 while ($2->begin() != $2->end()) {
2695 if ($2->front().first->getType() != Ty)
2696 GEN_ERROR("All elements of a PHI node must be of the same type!");
2697 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2700 delete $2; // Free the list...
2703 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2706 // Handle the short syntax
2707 const PointerType *PFTy = 0;
2708 const FunctionType *Ty = 0;
2709 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2710 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2711 // Pull out the types of all of the arguments...
2712 std::vector<const Type*> ParamTypes;
2713 FunctionType::ParamAttrsList ParamAttrs;
2714 ParamAttrs.push_back($8);
2715 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2716 const Type *Ty = I->Val->getType();
2717 if (Ty == Type::VoidTy)
2718 GEN_ERROR("Short call syntax cannot be used with varargs");
2719 ParamTypes.push_back(Ty);
2720 ParamAttrs.push_back(I->Attrs);
2723 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2724 PFTy = PointerType::get(Ty);
2727 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2730 // Check the arguments
2732 if ($6->empty()) { // Has no arguments?
2733 // Make sure no arguments is a good thing!
2734 if (Ty->getNumParams() != 0)
2735 GEN_ERROR("No arguments passed to a function that "
2736 "expects arguments!");
2737 } else { // Has arguments?
2738 // Loop through FunctionType's arguments and ensure they are specified
2741 FunctionType::param_iterator I = Ty->param_begin();
2742 FunctionType::param_iterator E = Ty->param_end();
2743 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2745 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2746 if (ArgI->Val->getType() != *I)
2747 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2748 (*I)->getDescription() + "'!");
2749 Args.push_back(ArgI->Val);
2751 if (Ty->isVarArg()) {
2753 for (; ArgI != ArgE; ++ArgI)
2754 Args.push_back(ArgI->Val); // push the remaining varargs
2755 } else if (I != E || ArgI != ArgE)
2756 GEN_ERROR("Invalid number of parameters detected!");
2758 // Create the call node
2759 CallInst *CI = new CallInst(V, Args);
2760 CI->setTailCall($1);
2761 CI->setCallingConv($2);
2772 OptVolatile : VOLATILE {
2783 MemoryInst : MALLOC Types OptCAlign {
2784 if (!UpRefs.empty())
2785 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2786 $$ = new MallocInst(*$2, 0, $3);
2790 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2791 if (!UpRefs.empty())
2792 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2793 Value* tmpVal = getVal($4, $5);
2795 $$ = new MallocInst(*$2, tmpVal, $6);
2798 | ALLOCA Types OptCAlign {
2799 if (!UpRefs.empty())
2800 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2801 $$ = new AllocaInst(*$2, 0, $3);
2805 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2806 if (!UpRefs.empty())
2807 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2808 Value* tmpVal = getVal($4, $5);
2810 $$ = new AllocaInst(*$2, tmpVal, $6);
2813 | FREE ResolvedVal {
2814 if (!isa<PointerType>($2->getType()))
2815 GEN_ERROR("Trying to free nonpointer type " +
2816 $2->getType()->getDescription() + "!");
2817 $$ = new FreeInst($2);
2821 | OptVolatile LOAD Types ValueRef {
2822 if (!UpRefs.empty())
2823 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2824 if (!isa<PointerType>($3->get()))
2825 GEN_ERROR("Can't load from nonpointer type: " +
2826 (*$3)->getDescription());
2827 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2828 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2829 (*$3)->getDescription());
2830 Value* tmpVal = getVal(*$3, $4);
2832 $$ = new LoadInst(tmpVal, "", $1);
2835 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2836 if (!UpRefs.empty())
2837 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2838 const PointerType *PT = dyn_cast<PointerType>($5->get());
2840 GEN_ERROR("Can't store to a nonpointer type: " +
2841 (*$5)->getDescription());
2842 const Type *ElTy = PT->getElementType();
2843 if (ElTy != $3->getType())
2844 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2845 "' into space of type '" + ElTy->getDescription() + "'!");
2847 Value* tmpVal = getVal(*$5, $6);
2849 $$ = new StoreInst($3, tmpVal, $1);
2852 | GETELEMENTPTR Types ValueRef IndexList {
2853 if (!UpRefs.empty())
2854 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2855 if (!isa<PointerType>($2->get()))
2856 GEN_ERROR("getelementptr insn requires pointer operand!");
2858 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2859 GEN_ERROR("Invalid getelementptr indices for type '" +
2860 (*$2)->getDescription()+ "'!");
2861 Value* tmpVal = getVal(*$2, $3);
2863 $$ = new GetElementPtrInst(tmpVal, *$4);
2871 // common code from the two 'RunVMAsmParser' functions
2872 static Module* RunParser(Module * M) {
2874 llvmAsmlineno = 1; // Reset the current line number...
2875 CurModule.CurrentModule = M;
2880 // Check to make sure the parser succeeded
2883 delete ParserResult;
2887 // Check to make sure that parsing produced a result
2891 // Reset ParserResult variable while saving its value for the result.
2892 Module *Result = ParserResult;
2898 void llvm::GenerateError(const std::string &message, int LineNo) {
2899 if (LineNo == -1) LineNo = llvmAsmlineno;
2900 // TODO: column number in exception
2902 TheParseError->setError(CurFilename, message, LineNo);
2906 int yyerror(const char *ErrorMsg) {
2908 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2909 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2910 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2911 if (yychar == YYEMPTY || yychar == 0)
2912 errMsg += "end-of-file.";
2914 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2915 GenerateError(errMsg);