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/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/Streams.h"
29 // The following is a gross hack. In order to rid the libAsmParser library of
30 // exceptions, we have to have a way of getting the yyparse function to go into
31 // an error situation. So, whenever we want an error to occur, the GenerateError
32 // function (see bottom of file) sets TriggerError. Then, at the end of each
33 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
34 // (a goto) to put YACC in error state. Furthermore, several calls to
35 // GenerateError are made from inside productions and they must simulate the
36 // previous exception behavior by exiting the production immediately. We have
37 // replaced these with the GEN_ERROR macro which calls GeneratError and then
38 // immediately invokes YYERROR. This would be so much cleaner if it was a
39 // recursive descent parser.
40 static bool TriggerError = false;
41 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
42 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
44 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
45 int yylex(); // declaration" of xxx warnings.
49 std::string CurFilename;
53 static Module *ParserResult;
55 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56 // relating to upreferences in the input stream.
58 //#define DEBUG_UPREFS 1
60 #define UR_OUT(X) cerr << X
65 #define YYERROR_VERBOSE 1
67 static GlobalVariable *CurGV;
70 // This contains info used when building the body of a function. It is
71 // destroyed when the function is completed.
73 typedef std::vector<Value *> ValueList; // Numbered defs
75 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
76 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
78 static struct PerModuleInfo {
79 Module *CurrentModule;
80 std::map<const Type *, ValueList> Values; // Module level numbered definitions
81 std::map<const Type *,ValueList> LateResolveValues;
82 std::vector<PATypeHolder> Types;
83 std::map<ValID, PATypeHolder> LateResolveTypes;
85 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86 /// how they were referenced and on which line of the input they came from so
87 /// that we can resolve them later and print error messages as appropriate.
88 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
90 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91 // references to global values. Global values may be referenced before they
92 // are defined, and if so, the temporary object that they represent is held
93 // here. This is used for forward references of GlobalValues.
95 typedef std::map<std::pair<const PointerType *,
96 ValID>, GlobalValue*> GlobalRefsType;
97 GlobalRefsType GlobalRefs;
100 // If we could not resolve some functions at function compilation time
101 // (calls to functions before they are defined), resolve them now... Types
102 // are resolved when the constant pool has been completely parsed.
104 ResolveDefinitions(LateResolveValues);
108 // Check to make sure that all global value forward references have been
111 if (!GlobalRefs.empty()) {
112 std::string UndefinedReferences = "Unresolved global references exist:\n";
114 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
116 UndefinedReferences += " " + I->first.first->getDescription() + " " +
117 I->first.second.getName() + "\n";
119 GenerateError(UndefinedReferences);
123 Values.clear(); // Clear out function local definitions
128 // GetForwardRefForGlobal - Check to see if there is a forward reference
129 // for this global. If so, remove it from the GlobalRefs map and return it.
130 // If not, just return null.
131 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
132 // Check to see if there is a forward reference to this global variable...
133 // if there is, eliminate it and patch the reference to use the new def'n.
134 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
135 GlobalValue *Ret = 0;
136 if (I != GlobalRefs.end()) {
144 static struct PerFunctionInfo {
145 Function *CurrentFunction; // Pointer to current function being created
147 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
148 std::map<const Type*, ValueList> LateResolveValues;
149 bool isDeclare; // Is this function a forward declararation?
150 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
152 /// BBForwardRefs - When we see forward references to basic blocks, keep
153 /// track of them here.
154 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
155 std::vector<BasicBlock*> NumberedBlocks;
158 inline PerFunctionInfo() {
161 Linkage = GlobalValue::ExternalLinkage;
164 inline void FunctionStart(Function *M) {
169 void FunctionDone() {
170 NumberedBlocks.clear();
172 // Any forward referenced blocks left?
173 if (!BBForwardRefs.empty()) {
174 GenerateError("Undefined reference to label " +
175 BBForwardRefs.begin()->first->getName());
179 // Resolve all forward references now.
180 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
182 Values.clear(); // Clear out function local definitions
185 Linkage = GlobalValue::ExternalLinkage;
187 } CurFun; // Info for the current function...
189 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
192 //===----------------------------------------------------------------------===//
193 // Code to handle definitions of all the types
194 //===----------------------------------------------------------------------===//
196 static int InsertValue(Value *V,
197 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
198 if (V->hasName()) return -1; // Is this a numbered definition?
200 // Yes, insert the value into the value table...
201 ValueList &List = ValueTab[V->getType()];
203 return List.size()-1;
206 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
208 case ValID::NumberVal: // Is it a numbered definition?
209 // Module constants occupy the lowest numbered slots...
210 if ((unsigned)D.Num < CurModule.Types.size())
211 return CurModule.Types[(unsigned)D.Num];
213 case ValID::NameVal: // Is it a named definition?
214 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
215 D.destroy(); // Free old strdup'd memory...
220 GenerateError("Internal parser error: Invalid symbol type reference!");
224 // If we reached here, we referenced either a symbol that we don't know about
225 // or an id number that hasn't been read yet. We may be referencing something
226 // forward, so just create an entry to be resolved later and get to it...
228 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
231 if (inFunctionScope()) {
232 if (D.Type == ValID::NameVal) {
233 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
236 GenerateError("Reference to an undefined type: #" + itostr(D.Num));
241 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
242 if (I != CurModule.LateResolveTypes.end())
245 Type *Typ = OpaqueType::get();
246 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
250 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
251 SymbolTable &SymTab =
252 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
253 CurModule.CurrentModule->getSymbolTable();
254 return SymTab.lookup(Ty, Name);
257 // getValNonImprovising - Look up the value specified by the provided type and
258 // the provided ValID. If the value exists and has already been defined, return
259 // it. Otherwise return null.
261 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
262 if (isa<FunctionType>(Ty)) {
263 GenerateError("Functions are not values and "
264 "must be referenced as pointers");
269 case ValID::NumberVal: { // Is it a numbered definition?
270 unsigned Num = (unsigned)D.Num;
272 // Module constants occupy the lowest numbered slots...
273 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
274 if (VI != CurModule.Values.end()) {
275 if (Num < VI->second.size())
276 return VI->second[Num];
277 Num -= VI->second.size();
280 // Make sure that our type is within bounds
281 VI = CurFun.Values.find(Ty);
282 if (VI == CurFun.Values.end()) return 0;
284 // Check that the number is within bounds...
285 if (VI->second.size() <= Num) return 0;
287 return VI->second[Num];
290 case ValID::NameVal: { // Is it a named definition?
291 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
292 if (N == 0) return 0;
294 D.destroy(); // Free old strdup'd memory...
298 // Check to make sure that "Ty" is an integral type, and that our
299 // value will fit into the specified type...
300 case ValID::ConstSIntVal: // Is it a constant pool reference??
301 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
302 GenerateError("Signed integral constant '" +
303 itostr(D.ConstPool64) + "' is invalid for type '" +
304 Ty->getDescription() + "'!");
307 return ConstantInt::get(Ty, D.ConstPool64);
309 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
310 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
311 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
312 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
313 "' is invalid or out of range!");
315 } else { // This is really a signed reference. Transmogrify.
316 return ConstantInt::get(Ty, D.ConstPool64);
319 return ConstantInt::get(Ty, D.UConstPool64);
322 case ValID::ConstFPVal: // Is it a floating point const pool reference?
323 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
324 GenerateError("FP constant invalid for type!!");
327 return ConstantFP::get(Ty, D.ConstPoolFP);
329 case ValID::ConstNullVal: // Is it a null value?
330 if (!isa<PointerType>(Ty)) {
331 GenerateError("Cannot create a a non pointer null!");
334 return ConstantPointerNull::get(cast<PointerType>(Ty));
336 case ValID::ConstUndefVal: // Is it an undef value?
337 return UndefValue::get(Ty);
339 case ValID::ConstZeroVal: // Is it a zero value?
340 return Constant::getNullValue(Ty);
342 case ValID::ConstantVal: // Fully resolved constant?
343 if (D.ConstantValue->getType() != Ty) {
344 GenerateError("Constant expression type different from required type!");
347 return D.ConstantValue;
349 case ValID::InlineAsmVal: { // Inline asm expression
350 const PointerType *PTy = dyn_cast<PointerType>(Ty);
351 const FunctionType *FTy =
352 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
353 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
354 GenerateError("Invalid type for asm constraint string!");
357 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
358 D.IAD->HasSideEffects);
359 D.destroy(); // Free InlineAsmDescriptor.
363 assert(0 && "Unhandled case!");
367 assert(0 && "Unhandled case!");
371 // getVal - This function is identical to getValNonImprovising, except that if a
372 // value is not already defined, it "improvises" by creating a placeholder var
373 // that looks and acts just like the requested variable. When the value is
374 // defined later, all uses of the placeholder variable are replaced with the
377 static Value *getVal(const Type *Ty, const ValID &ID) {
378 if (Ty == Type::LabelTy) {
379 GenerateError("Cannot use a basic block here");
383 // See if the value has already been defined.
384 Value *V = getValNonImprovising(Ty, ID);
386 if (TriggerError) return 0;
388 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
389 GenerateError("Invalid use of a composite type!");
393 // If we reached here, we referenced either a symbol that we don't know about
394 // or an id number that hasn't been read yet. We may be referencing something
395 // forward, so just create an entry to be resolved later and get to it...
397 V = new Argument(Ty);
399 // Remember where this forward reference came from. FIXME, shouldn't we try
400 // to recycle these things??
401 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
404 if (inFunctionScope())
405 InsertValue(V, CurFun.LateResolveValues);
407 InsertValue(V, CurModule.LateResolveValues);
411 /// getBBVal - This is used for two purposes:
412 /// * If isDefinition is true, a new basic block with the specified ID is being
414 /// * If isDefinition is true, this is a reference to a basic block, which may
415 /// or may not be a forward reference.
417 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
418 assert(inFunctionScope() && "Can't get basic block at global scope!");
424 GenerateError("Illegal label reference " + ID.getName());
426 case ValID::NumberVal: // Is it a numbered definition?
427 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
428 CurFun.NumberedBlocks.resize(ID.Num+1);
429 BB = CurFun.NumberedBlocks[ID.Num];
431 case ValID::NameVal: // Is it a named definition?
433 if (Value *N = CurFun.CurrentFunction->
434 getSymbolTable().lookup(Type::LabelTy, Name))
435 BB = cast<BasicBlock>(N);
439 // See if the block has already been defined.
441 // If this is the definition of the block, make sure the existing value was
442 // just a forward reference. If it was a forward reference, there will be
443 // an entry for it in the PlaceHolderInfo map.
444 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
445 // The existing value was a definition, not a forward reference.
446 GenerateError("Redefinition of label " + ID.getName());
450 ID.destroy(); // Free strdup'd memory.
454 // Otherwise this block has not been seen before.
455 BB = new BasicBlock("", CurFun.CurrentFunction);
456 if (ID.Type == ValID::NameVal) {
457 BB->setName(ID.Name);
459 CurFun.NumberedBlocks[ID.Num] = BB;
462 // If this is not a definition, keep track of it so we can use it as a forward
465 // Remember where this forward reference came from.
466 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
468 // The forward declaration could have been inserted anywhere in the
469 // function: insert it into the correct place now.
470 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
471 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
478 //===----------------------------------------------------------------------===//
479 // Code to handle forward references in instructions
480 //===----------------------------------------------------------------------===//
482 // This code handles the late binding needed with statements that reference
483 // values not defined yet... for example, a forward branch, or the PHI node for
486 // This keeps a table (CurFun.LateResolveValues) of all such forward references
487 // and back patchs after we are done.
490 // ResolveDefinitions - If we could not resolve some defs at parsing
491 // time (forward branches, phi functions for loops, etc...) resolve the
495 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
496 std::map<const Type*,ValueList> *FutureLateResolvers) {
497 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
498 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
499 E = LateResolvers.end(); LRI != E; ++LRI) {
500 ValueList &List = LRI->second;
501 while (!List.empty()) {
502 Value *V = List.back();
505 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
506 CurModule.PlaceHolderInfo.find(V);
507 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
509 ValID &DID = PHI->second.first;
511 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
515 V->replaceAllUsesWith(TheRealValue);
517 CurModule.PlaceHolderInfo.erase(PHI);
518 } else if (FutureLateResolvers) {
519 // Functions have their unresolved items forwarded to the module late
521 InsertValue(V, *FutureLateResolvers);
523 if (DID.Type == ValID::NameVal) {
524 GenerateError("Reference to an invalid definition: '" +DID.getName()+
525 "' of type '" + V->getType()->getDescription() + "'",
529 GenerateError("Reference to an invalid definition: #" +
530 itostr(DID.Num) + " of type '" +
531 V->getType()->getDescription() + "'",
539 LateResolvers.clear();
542 // ResolveTypeTo - A brand new type was just declared. This means that (if
543 // name is not null) things referencing Name can be resolved. Otherwise, things
544 // refering to the number can be resolved. Do this now.
546 static void ResolveTypeTo(char *Name, const Type *ToTy) {
548 if (Name) D = ValID::create(Name);
549 else D = ValID::create((int)CurModule.Types.size());
551 std::map<ValID, PATypeHolder>::iterator I =
552 CurModule.LateResolveTypes.find(D);
553 if (I != CurModule.LateResolveTypes.end()) {
554 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
555 CurModule.LateResolveTypes.erase(I);
559 // setValueName - Set the specified value to the name given. The name may be
560 // null potentially, in which case this is a noop. The string passed in is
561 // assumed to be a malloc'd string buffer, and is free'd by this function.
563 static void setValueName(Value *V, char *NameStr) {
565 std::string Name(NameStr); // Copy string
566 free(NameStr); // Free old string
568 if (V->getType() == Type::VoidTy) {
569 GenerateError("Can't assign name '" + Name+"' to value with void type!");
573 assert(inFunctionScope() && "Must be in function scope!");
574 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
575 if (ST.lookup(V->getType(), Name)) {
576 GenerateError("Redefinition of value named '" + Name + "' in the '" +
577 V->getType()->getDescription() + "' type plane!");
586 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
587 /// this is a declaration, otherwise it is a definition.
588 static GlobalVariable *
589 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
590 bool isConstantGlobal, const Type *Ty,
591 Constant *Initializer) {
592 if (isa<FunctionType>(Ty)) {
593 GenerateError("Cannot declare global vars of function type!");
597 const PointerType *PTy = PointerType::get(Ty);
601 Name = NameStr; // Copy string
602 free(NameStr); // Free old string
605 // See if this global value was forward referenced. If so, recycle the
609 ID = ValID::create((char*)Name.c_str());
611 ID = ValID::create((int)CurModule.Values[PTy].size());
614 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
615 // Move the global to the end of the list, from whereever it was
616 // previously inserted.
617 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
618 CurModule.CurrentModule->getGlobalList().remove(GV);
619 CurModule.CurrentModule->getGlobalList().push_back(GV);
620 GV->setInitializer(Initializer);
621 GV->setLinkage(Linkage);
622 GV->setConstant(isConstantGlobal);
623 InsertValue(GV, CurModule.Values);
627 // If this global has a name, check to see if there is already a definition
628 // of this global in the module. If so, merge as appropriate. Note that
629 // this is really just a hack around problems in the CFE. :(
631 // We are a simple redefinition of a value, check to see if it is defined
632 // the same as the old one.
633 if (GlobalVariable *EGV =
634 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
635 // We are allowed to redefine a global variable in two circumstances:
636 // 1. If at least one of the globals is uninitialized or
637 // 2. If both initializers have the same value.
639 if (!EGV->hasInitializer() || !Initializer ||
640 EGV->getInitializer() == Initializer) {
642 // Make sure the existing global version gets the initializer! Make
643 // sure that it also gets marked const if the new version is.
644 if (Initializer && !EGV->hasInitializer())
645 EGV->setInitializer(Initializer);
646 if (isConstantGlobal)
647 EGV->setConstant(true);
648 EGV->setLinkage(Linkage);
652 GenerateError("Redefinition of global variable named '" + Name +
653 "' in the '" + Ty->getDescription() + "' type plane!");
658 // Otherwise there is no existing GV to use, create one now.
660 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
661 CurModule.CurrentModule);
662 InsertValue(GV, CurModule.Values);
666 // setTypeName - Set the specified type to the name given. The name may be
667 // null potentially, in which case this is a noop. The string passed in is
668 // assumed to be a malloc'd string buffer, and is freed by this function.
670 // This function returns true if the type has already been defined, but is
671 // allowed to be redefined in the specified context. If the name is a new name
672 // for the type plane, it is inserted and false is returned.
673 static bool setTypeName(const Type *T, char *NameStr) {
674 assert(!inFunctionScope() && "Can't give types function-local names!");
675 if (NameStr == 0) return false;
677 std::string Name(NameStr); // Copy string
678 free(NameStr); // Free old string
680 // We don't allow assigning names to void type
681 if (T == Type::VoidTy) {
682 GenerateError("Can't assign name '" + Name + "' to the void type!");
686 // Set the type name, checking for conflicts as we do so.
687 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
689 if (AlreadyExists) { // Inserting a name that is already defined???
690 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
691 assert(Existing && "Conflict but no matching type?");
693 // There is only one case where this is allowed: when we are refining an
694 // opaque type. In this case, Existing will be an opaque type.
695 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
696 // We ARE replacing an opaque type!
697 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
701 // Otherwise, this is an attempt to redefine a type. That's okay if
702 // the redefinition is identical to the original. This will be so if
703 // Existing and T point to the same Type object. In this one case we
704 // allow the equivalent redefinition.
705 if (Existing == T) return true; // Yes, it's equal.
707 // Any other kind of (non-equivalent) redefinition is an error.
708 GenerateError("Redefinition of type named '" + Name + "' in the '" +
709 T->getDescription() + "' type plane!");
715 //===----------------------------------------------------------------------===//
716 // Code for handling upreferences in type names...
719 // TypeContains - Returns true if Ty directly contains E in it.
721 static bool TypeContains(const Type *Ty, const Type *E) {
722 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
723 E) != Ty->subtype_end();
728 // NestingLevel - The number of nesting levels that need to be popped before
729 // this type is resolved.
730 unsigned NestingLevel;
732 // LastContainedTy - This is the type at the current binding level for the
733 // type. Every time we reduce the nesting level, this gets updated.
734 const Type *LastContainedTy;
736 // UpRefTy - This is the actual opaque type that the upreference is
740 UpRefRecord(unsigned NL, OpaqueType *URTy)
741 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
745 // UpRefs - A list of the outstanding upreferences that need to be resolved.
746 static std::vector<UpRefRecord> UpRefs;
748 /// HandleUpRefs - Every time we finish a new layer of types, this function is
749 /// called. It loops through the UpRefs vector, which is a list of the
750 /// currently active types. For each type, if the up reference is contained in
751 /// the newly completed type, we decrement the level count. When the level
752 /// count reaches zero, the upreferenced type is the type that is passed in:
753 /// thus we can complete the cycle.
755 static PATypeHolder HandleUpRefs(const Type *ty) {
756 // If Ty isn't abstract, or if there are no up-references in it, then there is
757 // nothing to resolve here.
758 if (!ty->isAbstract() || UpRefs.empty()) return ty;
761 UR_OUT("Type '" << Ty->getDescription() <<
762 "' newly formed. Resolving upreferences.\n" <<
763 UpRefs.size() << " upreferences active!\n");
765 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
766 // to zero), we resolve them all together before we resolve them to Ty. At
767 // the end of the loop, if there is anything to resolve to Ty, it will be in
769 OpaqueType *TypeToResolve = 0;
771 for (unsigned i = 0; i != UpRefs.size(); ++i) {
772 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
773 << UpRefs[i].second->getDescription() << ") = "
774 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
775 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
776 // Decrement level of upreference
777 unsigned Level = --UpRefs[i].NestingLevel;
778 UpRefs[i].LastContainedTy = Ty;
779 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
780 if (Level == 0) { // Upreference should be resolved!
781 if (!TypeToResolve) {
782 TypeToResolve = UpRefs[i].UpRefTy;
784 UR_OUT(" * Resolving upreference for "
785 << UpRefs[i].second->getDescription() << "\n";
786 std::string OldName = UpRefs[i].UpRefTy->getDescription());
787 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
788 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
789 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
791 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
792 --i; // Do not skip the next element...
798 UR_OUT(" * Resolving upreference for "
799 << UpRefs[i].second->getDescription() << "\n";
800 std::string OldName = TypeToResolve->getDescription());
801 TypeToResolve->refineAbstractTypeTo(Ty);
807 // common code from the two 'RunVMAsmParser' functions
808 static Module* RunParser(Module * M) {
810 llvmAsmlineno = 1; // Reset the current line number...
811 CurModule.CurrentModule = M;
813 // Check to make sure the parser succeeded
820 // Check to make sure that parsing produced a result
824 // Reset ParserResult variable while saving its value for the result.
825 Module *Result = ParserResult;
831 //===----------------------------------------------------------------------===//
832 // RunVMAsmParser - Define an interface to this parser
833 //===----------------------------------------------------------------------===//
835 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
838 CurFilename = Filename;
839 return RunParser(new Module(CurFilename));
842 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
843 set_scan_string(AsmString);
845 CurFilename = "from_memory";
847 return RunParser(new Module (CurFilename));
856 llvm::Module *ModuleVal;
857 llvm::Function *FunctionVal;
858 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
859 llvm::BasicBlock *BasicBlockVal;
860 llvm::TerminatorInst *TermInstVal;
861 llvm::Instruction *InstVal;
862 llvm::Constant *ConstVal;
864 const llvm::Type *PrimType;
865 llvm::PATypeHolder *TypeVal;
866 llvm::Value *ValueVal;
868 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
869 std::vector<llvm::Value*> *ValueList;
870 std::list<llvm::PATypeHolder> *TypeList;
871 // Represent the RHS of PHI node
872 std::list<std::pair<llvm::Value*,
873 llvm::BasicBlock*> > *PHIList;
874 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
875 std::vector<llvm::Constant*> *ConstVector;
877 llvm::GlobalValue::LinkageTypes Linkage;
885 char *StrVal; // This memory is strdup'd!
886 llvm::ValID ValIDVal; // strdup'd memory maybe!
888 llvm::Instruction::BinaryOps BinaryOpVal;
889 llvm::Instruction::TermOps TermOpVal;
890 llvm::Instruction::MemoryOps MemOpVal;
891 llvm::Instruction::CastOps CastOpVal;
892 llvm::Instruction::OtherOps OtherOpVal;
893 llvm::Module::Endianness Endianness;
894 llvm::ICmpInst::Predicate IPredicate;
895 llvm::FCmpInst::Predicate FPredicate;
898 %type <ModuleVal> Module FunctionList
899 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
900 %type <BasicBlockVal> BasicBlock InstructionList
901 %type <TermInstVal> BBTerminatorInst
902 %type <InstVal> Inst InstVal MemoryInst
903 %type <ConstVal> ConstVal ConstExpr
904 %type <ConstVector> ConstVector
905 %type <ArgList> ArgList ArgListH
906 %type <ArgVal> ArgVal
907 %type <PHIList> PHIList
908 %type <ValueList> ValueRefList ValueRefListE // For call param lists
909 %type <ValueList> IndexList // For GEP derived indices
910 %type <TypeList> TypeListI ArgTypeListI
911 %type <JumpTable> JumpTable
912 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
913 %type <BoolVal> OptVolatile // 'volatile' or not
914 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
915 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
916 %type <Linkage> OptLinkage
917 %type <Endianness> BigOrLittle
919 // ValueRef - Unresolved reference to a definition or BB
920 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
921 %type <ValueVal> ResolvedVal // <type> <valref> pair
922 // Tokens and types for handling constant integer values
924 // ESINT64VAL - A negative number within long long range
925 %token <SInt64Val> ESINT64VAL
927 // EUINT64VAL - A positive number within uns. long long range
928 %token <UInt64Val> EUINT64VAL
930 %token <SIntVal> SINTVAL // Signed 32 bit ints...
931 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
932 %type <SIntVal> INTVAL
933 %token <FPVal> FPVAL // Float or Double constant
936 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
937 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
938 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
939 %token <PrimType> FLOAT DOUBLE TYPE LABEL
941 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
942 %type <StrVal> Name OptName OptAssign
943 %type <UIntVal> OptAlign OptCAlign
944 %type <StrVal> OptSection SectionString
946 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
947 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
948 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
949 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
950 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
951 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
952 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
953 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
955 %type <UIntVal> OptCallingConv
957 // Basic Block Terminating Operators
958 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
961 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
962 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
963 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
964 %token <OtherOpVal> ICMP FCMP
965 %type <IPredicate> IPredicates
966 %type <FPredicate> FPredicates
967 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
968 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
970 // Memory Instructions
971 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
974 %type <CastOpVal> CastOps
975 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
976 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
979 %type <OtherOpVal> ShiftOps
980 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
981 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
987 // Handle constant integer size restriction and conversion...
991 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
992 GEN_ERROR("Value too large for type!");
997 // Operations that are notably excluded from this list include:
998 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1000 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1001 LogicalOps : AND | OR | XOR;
1002 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1003 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1004 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1005 ShiftOps : SHL | LSHR | ASHR;
1007 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1008 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1009 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1010 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1011 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1015 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1016 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1017 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1018 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1019 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1020 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1021 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1022 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1023 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1026 // These are some types that allow classification if we only want a particular
1027 // thing... for example, only a signed, unsigned, or integral type.
1028 SIntType : LONG | INT | SHORT | SBYTE;
1029 UIntType : ULONG | UINT | USHORT | UBYTE;
1030 IntType : SIntType | UIntType;
1031 FPType : FLOAT | DOUBLE;
1033 // OptAssign - Value producing statements have an optional assignment component
1034 OptAssign : Name '=' {
1043 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1044 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1045 WEAK { $$ = GlobalValue::WeakLinkage; } |
1046 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1047 DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; } |
1048 DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; } |
1049 EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; } |
1050 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1052 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1053 CCC_TOK { $$ = CallingConv::C; } |
1054 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
1055 FASTCC_TOK { $$ = CallingConv::Fast; } |
1056 COLDCC_TOK { $$ = CallingConv::Cold; } |
1057 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1058 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1060 if ((unsigned)$2 != $2)
1061 GEN_ERROR("Calling conv too large!");
1066 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1067 // a comma before it.
1068 OptAlign : /*empty*/ { $$ = 0; } |
1071 if ($$ != 0 && !isPowerOf2_32($$))
1072 GEN_ERROR("Alignment must be a power of two!");
1075 OptCAlign : /*empty*/ { $$ = 0; } |
1076 ',' ALIGN EUINT64VAL {
1078 if ($$ != 0 && !isPowerOf2_32($$))
1079 GEN_ERROR("Alignment must be a power of two!");
1084 SectionString : SECTION STRINGCONSTANT {
1085 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1086 if ($2[i] == '"' || $2[i] == '\\')
1087 GEN_ERROR("Invalid character in section name!");
1092 OptSection : /*empty*/ { $$ = 0; } |
1093 SectionString { $$ = $1; };
1095 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1096 // is set to be the global we are processing.
1098 GlobalVarAttributes : /* empty */ {} |
1099 ',' GlobalVarAttribute GlobalVarAttributes {};
1100 GlobalVarAttribute : SectionString {
1101 CurGV->setSection($1);
1105 | ALIGN EUINT64VAL {
1106 if ($2 != 0 && !isPowerOf2_32($2))
1107 GEN_ERROR("Alignment must be a power of two!");
1108 CurGV->setAlignment($2);
1112 //===----------------------------------------------------------------------===//
1113 // Types includes all predefined types... except void, because it can only be
1114 // used in specific contexts (function returning void for example). To have
1115 // access to it, a user must explicitly use TypesV.
1118 // TypesV includes all of 'Types', but it also includes the void type.
1119 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1120 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1123 if (!UpRefs.empty())
1124 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1130 // Derived types are added later...
1132 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1133 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1135 $$ = new PATypeHolder(OpaqueType::get());
1139 $$ = new PATypeHolder($1);
1142 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1143 const Type* tmp = getTypeVal($1);
1145 $$ = new PATypeHolder(tmp);
1148 // Include derived types in the Types production.
1150 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1151 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1152 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1153 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1154 $$ = new PATypeHolder(OT);
1155 UR_OUT("New Upreference!\n");
1158 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1159 std::vector<const Type*> Params;
1160 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1161 E = $3->end(); I != E; ++I)
1162 Params.push_back(*I);
1163 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1164 if (isVarArg) Params.pop_back();
1166 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1167 delete $3; // Delete the argument list
1168 delete $1; // Delete the return type handle
1171 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1172 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1176 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1177 const llvm::Type* ElemTy = $4->get();
1178 if ((unsigned)$2 != $2)
1179 GEN_ERROR("Unsigned result not equal to signed result");
1180 if (!ElemTy->isPrimitiveType())
1181 GEN_ERROR("Elemental type of a PackedType must be primitive");
1182 if (!isPowerOf2_32($2))
1183 GEN_ERROR("Vector length should be a power of 2!");
1184 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1188 | '{' TypeListI '}' { // Structure type?
1189 std::vector<const Type*> Elements;
1190 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1191 E = $2->end(); I != E; ++I)
1192 Elements.push_back(*I);
1194 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1198 | '{' '}' { // Empty structure type?
1199 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1202 | '<' '{' TypeListI '}' '>' {
1203 std::vector<const Type*> Elements;
1204 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1205 E = $3->end(); I != E; ++I)
1206 Elements.push_back(*I);
1208 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1212 | '<' '{' '}' '>' { // Empty structure type?
1213 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1216 | UpRTypes '*' { // Pointer type?
1217 if (*$1 == Type::LabelTy)
1218 GEN_ERROR("Cannot form a pointer to a basic block");
1219 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1224 // TypeList - Used for struct declarations and as a basis for function type
1225 // declaration type lists
1227 TypeListI : UpRTypes {
1228 $$ = new std::list<PATypeHolder>();
1229 $$->push_back(*$1); delete $1;
1232 | TypeListI ',' UpRTypes {
1233 ($$=$1)->push_back(*$3); delete $3;
1237 // ArgTypeList - List of types for a function type declaration...
1238 ArgTypeListI : TypeListI
1239 | TypeListI ',' DOTDOTDOT {
1240 ($$=$1)->push_back(Type::VoidTy);
1244 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1248 $$ = new std::list<PATypeHolder>();
1252 // ConstVal - The various declarations that go into the constant pool. This
1253 // production is used ONLY to represent constants that show up AFTER a 'const',
1254 // 'constant' or 'global' token at global scope. Constants that can be inlined
1255 // into other expressions (such as integers and constexprs) are handled by the
1256 // ResolvedVal, ValueRef and ConstValueRef productions.
1258 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1259 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1261 GEN_ERROR("Cannot make array constant with type: '" +
1262 (*$1)->getDescription() + "'!");
1263 const Type *ETy = ATy->getElementType();
1264 int NumElements = ATy->getNumElements();
1266 // Verify that we have the correct size...
1267 if (NumElements != -1 && NumElements != (int)$3->size())
1268 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1269 utostr($3->size()) + " arguments, but has size of " +
1270 itostr(NumElements) + "!");
1272 // Verify all elements are correct type!
1273 for (unsigned i = 0; i < $3->size(); i++) {
1274 if (ETy != (*$3)[i]->getType())
1275 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1276 ETy->getDescription() +"' as required!\nIt is of type '"+
1277 (*$3)[i]->getType()->getDescription() + "'.");
1280 $$ = ConstantArray::get(ATy, *$3);
1281 delete $1; delete $3;
1285 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1287 GEN_ERROR("Cannot make array constant with type: '" +
1288 (*$1)->getDescription() + "'!");
1290 int NumElements = ATy->getNumElements();
1291 if (NumElements != -1 && NumElements != 0)
1292 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1293 " arguments, but has size of " + itostr(NumElements) +"!");
1294 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1298 | Types 'c' STRINGCONSTANT {
1299 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1301 GEN_ERROR("Cannot make array constant with type: '" +
1302 (*$1)->getDescription() + "'!");
1304 int NumElements = ATy->getNumElements();
1305 const Type *ETy = ATy->getElementType();
1306 char *EndStr = UnEscapeLexed($3, true);
1307 if (NumElements != -1 && NumElements != (EndStr-$3))
1308 GEN_ERROR("Can't build string constant of size " +
1309 itostr((int)(EndStr-$3)) +
1310 " when array has size " + itostr(NumElements) + "!");
1311 std::vector<Constant*> Vals;
1312 if (ETy == Type::SByteTy) {
1313 for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1314 Vals.push_back(ConstantInt::get(ETy, *C));
1315 } else if (ETy == Type::UByteTy) {
1316 for (unsigned char *C = (unsigned char *)$3;
1317 C != (unsigned char*)EndStr; ++C)
1318 Vals.push_back(ConstantInt::get(ETy, *C));
1321 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1324 $$ = ConstantArray::get(ATy, Vals);
1328 | Types '<' ConstVector '>' { // Nonempty unsized arr
1329 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1331 GEN_ERROR("Cannot make packed constant with type: '" +
1332 (*$1)->getDescription() + "'!");
1333 const Type *ETy = PTy->getElementType();
1334 int NumElements = PTy->getNumElements();
1336 // Verify that we have the correct size...
1337 if (NumElements != -1 && NumElements != (int)$3->size())
1338 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1339 utostr($3->size()) + " arguments, but has size of " +
1340 itostr(NumElements) + "!");
1342 // Verify all elements are correct type!
1343 for (unsigned i = 0; i < $3->size(); i++) {
1344 if (ETy != (*$3)[i]->getType())
1345 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1346 ETy->getDescription() +"' as required!\nIt is of type '"+
1347 (*$3)[i]->getType()->getDescription() + "'.");
1350 $$ = ConstantPacked::get(PTy, *$3);
1351 delete $1; delete $3;
1354 | Types '{' ConstVector '}' {
1355 const StructType *STy = dyn_cast<StructType>($1->get());
1357 GEN_ERROR("Cannot make struct constant with type: '" +
1358 (*$1)->getDescription() + "'!");
1360 if ($3->size() != STy->getNumContainedTypes())
1361 GEN_ERROR("Illegal number of initializers for structure type!");
1363 // Check to ensure that constants are compatible with the type initializer!
1364 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1365 if ((*$3)[i]->getType() != STy->getElementType(i))
1366 GEN_ERROR("Expected type '" +
1367 STy->getElementType(i)->getDescription() +
1368 "' for element #" + utostr(i) +
1369 " of structure initializer!");
1371 $$ = ConstantStruct::get(STy, *$3);
1372 delete $1; delete $3;
1376 const StructType *STy = dyn_cast<StructType>($1->get());
1378 GEN_ERROR("Cannot make struct constant with type: '" +
1379 (*$1)->getDescription() + "'!");
1381 if (STy->getNumContainedTypes() != 0)
1382 GEN_ERROR("Illegal number of initializers for structure type!");
1384 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1389 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1391 GEN_ERROR("Cannot make null pointer constant with type: '" +
1392 (*$1)->getDescription() + "'!");
1394 $$ = ConstantPointerNull::get(PTy);
1399 $$ = UndefValue::get($1->get());
1403 | Types SymbolicValueRef {
1404 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1406 GEN_ERROR("Global const reference must be a pointer type!");
1408 // ConstExprs can exist in the body of a function, thus creating
1409 // GlobalValues whenever they refer to a variable. Because we are in
1410 // the context of a function, getValNonImprovising will search the functions
1411 // symbol table instead of the module symbol table for the global symbol,
1412 // which throws things all off. To get around this, we just tell
1413 // getValNonImprovising that we are at global scope here.
1415 Function *SavedCurFn = CurFun.CurrentFunction;
1416 CurFun.CurrentFunction = 0;
1418 Value *V = getValNonImprovising(Ty, $2);
1421 CurFun.CurrentFunction = SavedCurFn;
1423 // If this is an initializer for a constant pointer, which is referencing a
1424 // (currently) undefined variable, create a stub now that shall be replaced
1425 // in the future with the right type of variable.
1428 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1429 const PointerType *PT = cast<PointerType>(Ty);
1431 // First check to see if the forward references value is already created!
1432 PerModuleInfo::GlobalRefsType::iterator I =
1433 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1435 if (I != CurModule.GlobalRefs.end()) {
1436 V = I->second; // Placeholder already exists, use it...
1440 if ($2.Type == ValID::NameVal) Name = $2.Name;
1442 // Create the forward referenced global.
1444 if (const FunctionType *FTy =
1445 dyn_cast<FunctionType>(PT->getElementType())) {
1446 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1447 CurModule.CurrentModule);
1449 GV = new GlobalVariable(PT->getElementType(), false,
1450 GlobalValue::ExternalLinkage, 0,
1451 Name, CurModule.CurrentModule);
1454 // Keep track of the fact that we have a forward ref to recycle it
1455 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1460 $$ = cast<GlobalValue>(V);
1461 delete $1; // Free the type handle
1465 if ($1->get() != $2->getType())
1466 GEN_ERROR("Mismatched types for constant expression!");
1471 | Types ZEROINITIALIZER {
1472 const Type *Ty = $1->get();
1473 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1474 GEN_ERROR("Cannot create a null initialized value of this type!");
1475 $$ = Constant::getNullValue(Ty);
1479 | SIntType ESINT64VAL { // integral constants
1480 if (!ConstantInt::isValueValidForType($1, $2))
1481 GEN_ERROR("Constant value doesn't fit in type!");
1482 $$ = ConstantInt::get($1, $2);
1485 | SIntType EUINT64VAL { // integral constants
1486 if (!ConstantInt::isValueValidForType($1, $2))
1487 GEN_ERROR("Constant value doesn't fit in type!");
1488 $$ = ConstantInt::get($1, $2);
1491 | UIntType EUINT64VAL { // integral constants
1492 if (!ConstantInt::isValueValidForType($1, $2))
1493 GEN_ERROR("Constant value doesn't fit in type!");
1494 $$ = ConstantInt::get($1, $2);
1497 | UIntType ESINT64VAL {
1498 if (!ConstantInt::isValueValidForType($1, $2))
1499 GEN_ERROR("Constant value doesn't fit in type!");
1500 $$ = ConstantInt::get($1, $2);
1503 | BOOL TRUETOK { // Boolean constants
1504 $$ = ConstantBool::getTrue();
1507 | BOOL FALSETOK { // Boolean constants
1508 $$ = ConstantBool::getFalse();
1511 | FPType FPVAL { // Float & Double constants
1512 if (!ConstantFP::isValueValidForType($1, $2))
1513 GEN_ERROR("Floating point constant invalid for type!!");
1514 $$ = ConstantFP::get($1, $2);
1519 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1521 const Type *Ty = $5->get();
1522 if (!Val->getType()->isFirstClassType())
1523 GEN_ERROR("cast constant expression from a non-primitive type: '" +
1524 Val->getType()->getDescription() + "'!");
1525 if (!Ty->isFirstClassType())
1526 GEN_ERROR("cast constant expression to a non-primitive type: '" +
1527 Ty->getDescription() + "'!");
1528 $$ = ConstantExpr::getCast($1, $3, $5->get());
1531 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1532 if (!isa<PointerType>($3->getType()))
1533 GEN_ERROR("GetElementPtr requires a pointer operand!");
1536 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1538 GEN_ERROR("Index list invalid for constant getelementptr!");
1540 std::vector<Constant*> IdxVec;
1541 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1542 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1543 IdxVec.push_back(C);
1545 GEN_ERROR("Indices to constant getelementptr must be constants!");
1549 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1552 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1553 if ($3->getType() != Type::BoolTy)
1554 GEN_ERROR("Select condition must be of boolean type!");
1555 if ($5->getType() != $7->getType())
1556 GEN_ERROR("Select operand types must match!");
1557 $$ = ConstantExpr::getSelect($3, $5, $7);
1560 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1561 if ($3->getType() != $5->getType())
1562 GEN_ERROR("Binary operator types must match!");
1564 $$ = ConstantExpr::get($1, $3, $5);
1566 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1567 if ($3->getType() != $5->getType())
1568 GEN_ERROR("Logical operator types must match!");
1569 if (!$3->getType()->isIntegral()) {
1570 if (!isa<PackedType>($3->getType()) ||
1571 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1572 GEN_ERROR("Logical operator requires integral operands!");
1574 $$ = ConstantExpr::get($1, $3, $5);
1577 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1578 if ($3->getType() != $5->getType())
1579 GEN_ERROR("setcc operand types must match!");
1580 $$ = ConstantExpr::get($1, $3, $5);
1583 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1584 if ($4->getType() != $6->getType())
1585 GEN_ERROR("icmp operand types must match!");
1586 $$ = ConstantExpr::getICmp($2, $4, $6);
1588 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1589 if ($4->getType() != $6->getType())
1590 GEN_ERROR("fcmp operand types must match!");
1591 $$ = ConstantExpr::getFCmp($2, $4, $6);
1593 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1594 if ($5->getType() != Type::UByteTy)
1595 GEN_ERROR("Shift count for shift constant must be unsigned byte!");
1596 if (!$3->getType()->isInteger())
1597 GEN_ERROR("Shift constant expression requires integer operand!");
1599 $$ = ConstantExpr::get($1, $3, $5);
1602 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1603 if (!ExtractElementInst::isValidOperands($3, $5))
1604 GEN_ERROR("Invalid extractelement operands!");
1605 $$ = ConstantExpr::getExtractElement($3, $5);
1608 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1609 if (!InsertElementInst::isValidOperands($3, $5, $7))
1610 GEN_ERROR("Invalid insertelement operands!");
1611 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1614 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1615 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1616 GEN_ERROR("Invalid shufflevector operands!");
1617 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1622 // ConstVector - A list of comma separated constants.
1623 ConstVector : ConstVector ',' ConstVal {
1624 ($$ = $1)->push_back($3);
1628 $$ = new std::vector<Constant*>();
1634 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1635 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1638 //===----------------------------------------------------------------------===//
1639 // Rules to match Modules
1640 //===----------------------------------------------------------------------===//
1642 // Module rule: Capture the result of parsing the whole file into a result
1645 Module : FunctionList {
1646 $$ = ParserResult = $1;
1647 CurModule.ModuleDone();
1651 // FunctionList - A list of functions, preceeded by a constant pool.
1653 FunctionList : FunctionList Function {
1655 CurFun.FunctionDone();
1658 | FunctionList FunctionProto {
1662 | FunctionList MODULE ASM_TOK AsmBlock {
1666 | FunctionList IMPLEMENTATION {
1671 $$ = CurModule.CurrentModule;
1672 // Emit an error if there are any unresolved types left.
1673 if (!CurModule.LateResolveTypes.empty()) {
1674 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1675 if (DID.Type == ValID::NameVal) {
1676 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1678 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1684 // ConstPool - Constants with optional names assigned to them.
1685 ConstPool : ConstPool OptAssign TYPE TypesV {
1686 // Eagerly resolve types. This is not an optimization, this is a
1687 // requirement that is due to the fact that we could have this:
1689 // %list = type { %list * }
1690 // %list = type { %list * } ; repeated type decl
1692 // If types are not resolved eagerly, then the two types will not be
1693 // determined to be the same type!
1695 ResolveTypeTo($2, *$4);
1697 if (!setTypeName(*$4, $2) && !$2) {
1699 // If this is a named type that is not a redefinition, add it to the slot
1701 CurModule.Types.push_back(*$4);
1707 | ConstPool FunctionProto { // Function prototypes can be in const pool
1710 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
1713 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1715 GEN_ERROR("Global value initializer is not a constant!");
1716 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1718 } GlobalVarAttributes {
1721 | ConstPool OptAssign EXTERNAL GlobalType Types {
1722 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1725 } GlobalVarAttributes {
1729 | ConstPool OptAssign DLLIMPORT GlobalType Types {
1730 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, *$5, 0);
1733 } GlobalVarAttributes {
1737 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
1739 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, *$5, 0);
1742 } GlobalVarAttributes {
1746 | ConstPool TARGET TargetDefinition {
1749 | ConstPool DEPLIBS '=' LibrariesDefinition {
1752 | /* empty: end of list */ {
1756 AsmBlock : STRINGCONSTANT {
1757 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1758 char *EndStr = UnEscapeLexed($1, true);
1759 std::string NewAsm($1, EndStr);
1762 if (AsmSoFar.empty())
1763 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1765 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1769 BigOrLittle : BIG { $$ = Module::BigEndian; };
1770 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1772 TargetDefinition : ENDIAN '=' BigOrLittle {
1773 CurModule.CurrentModule->setEndianness($3);
1776 | POINTERSIZE '=' EUINT64VAL {
1778 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1780 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1782 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1785 | TRIPLE '=' STRINGCONSTANT {
1786 CurModule.CurrentModule->setTargetTriple($3);
1789 | DATALAYOUT '=' STRINGCONSTANT {
1790 CurModule.CurrentModule->setDataLayout($3);
1794 LibrariesDefinition : '[' LibList ']';
1796 LibList : LibList ',' STRINGCONSTANT {
1797 CurModule.CurrentModule->addLibrary($3);
1802 CurModule.CurrentModule->addLibrary($1);
1806 | /* empty: end of list */ {
1811 //===----------------------------------------------------------------------===//
1812 // Rules to match Function Headers
1813 //===----------------------------------------------------------------------===//
1815 Name : VAR_ID | STRINGCONSTANT;
1816 OptName : Name | /*empty*/ { $$ = 0; };
1818 ArgVal : Types OptName {
1819 if (*$1 == Type::VoidTy)
1820 GEN_ERROR("void typed arguments are invalid!");
1821 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1825 ArgListH : ArgListH ',' ArgVal {
1832 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1838 ArgList : ArgListH {
1842 | ArgListH ',' DOTDOTDOT {
1844 $$->push_back(std::pair<PATypeHolder*,
1845 char*>(new PATypeHolder(Type::VoidTy), 0));
1849 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1850 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1858 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1859 OptSection OptAlign {
1861 std::string FunctionName($3);
1862 free($3); // Free strdup'd memory!
1864 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1865 GEN_ERROR("LLVM functions cannot return aggregate types!");
1867 std::vector<const Type*> ParamTypeList;
1868 if ($5) { // If there are arguments...
1869 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1870 I != $5->end(); ++I)
1871 ParamTypeList.push_back(I->first->get());
1874 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1875 if (isVarArg) ParamTypeList.pop_back();
1877 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1878 const PointerType *PFT = PointerType::get(FT);
1882 if (!FunctionName.empty()) {
1883 ID = ValID::create((char*)FunctionName.c_str());
1885 ID = ValID::create((int)CurModule.Values[PFT].size());
1889 // See if this function was forward referenced. If so, recycle the object.
1890 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1891 // Move the function to the end of the list, from whereever it was
1892 // previously inserted.
1893 Fn = cast<Function>(FWRef);
1894 CurModule.CurrentModule->getFunctionList().remove(Fn);
1895 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1896 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1897 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1898 // If this is the case, either we need to be a forward decl, or it needs
1900 if (!CurFun.isDeclare && !Fn->isExternal())
1901 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
1903 // Make sure to strip off any argument names so we can't get conflicts.
1904 if (Fn->isExternal())
1905 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1908 } else { // Not already defined?
1909 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1910 CurModule.CurrentModule);
1912 InsertValue(Fn, CurModule.Values);
1915 CurFun.FunctionStart(Fn);
1917 if (CurFun.isDeclare) {
1918 // If we have declaration, always overwrite linkage. This will allow us to
1919 // correctly handle cases, when pointer to function is passed as argument to
1920 // another function.
1921 Fn->setLinkage(CurFun.Linkage);
1923 Fn->setCallingConv($1);
1924 Fn->setAlignment($8);
1930 // Add all of the arguments we parsed to the function...
1931 if ($5) { // Is null if empty...
1932 if (isVarArg) { // Nuke the last entry
1933 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1934 "Not a varargs marker!");
1935 delete $5->back().first;
1936 $5->pop_back(); // Delete the last entry
1938 Function::arg_iterator ArgIt = Fn->arg_begin();
1939 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1940 I != $5->end(); ++I, ++ArgIt) {
1941 delete I->first; // Delete the typeholder...
1943 setValueName(ArgIt, I->second); // Insert arg into symtab...
1948 delete $5; // We're now done with the argument list
1953 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1955 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1956 $$ = CurFun.CurrentFunction;
1958 // Make sure that we keep track of the linkage type even if there was a
1959 // previous "declare".
1963 END : ENDTOK | '}'; // Allow end of '}' to end a function
1965 Function : BasicBlockList END {
1970 FnDeclareLinkage: /*default*/ |
1971 DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; } |
1972 EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; };
1974 FunctionProto : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
1975 $$ = CurFun.CurrentFunction;
1976 CurFun.FunctionDone();
1980 //===----------------------------------------------------------------------===//
1981 // Rules to match Basic Blocks
1982 //===----------------------------------------------------------------------===//
1984 OptSideEffect : /* empty */ {
1993 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1994 $$ = ValID::create($1);
1998 $$ = ValID::create($1);
2001 | FPVAL { // Perhaps it's an FP constant?
2002 $$ = ValID::create($1);
2006 $$ = ValID::create(ConstantBool::getTrue());
2010 $$ = ValID::create(ConstantBool::getFalse());
2014 $$ = ValID::createNull();
2018 $$ = ValID::createUndef();
2021 | ZEROINITIALIZER { // A vector zero constant.
2022 $$ = ValID::createZeroInit();
2025 | '<' ConstVector '>' { // Nonempty unsized packed vector
2026 const Type *ETy = (*$2)[0]->getType();
2027 int NumElements = $2->size();
2029 PackedType* pt = PackedType::get(ETy, NumElements);
2030 PATypeHolder* PTy = new PATypeHolder(
2038 // Verify all elements are correct type!
2039 for (unsigned i = 0; i < $2->size(); i++) {
2040 if (ETy != (*$2)[i]->getType())
2041 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2042 ETy->getDescription() +"' as required!\nIt is of type '" +
2043 (*$2)[i]->getType()->getDescription() + "'.");
2046 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2047 delete PTy; delete $2;
2051 $$ = ValID::create($1);
2054 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2055 char *End = UnEscapeLexed($3, true);
2056 std::string AsmStr = std::string($3, End);
2057 End = UnEscapeLexed($5, true);
2058 std::string Constraints = std::string($5, End);
2059 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2065 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2068 SymbolicValueRef : INTVAL { // Is it an integer reference...?
2069 $$ = ValID::create($1);
2072 | Name { // Is it a named reference...?
2073 $$ = ValID::create($1);
2077 // ValueRef - A reference to a definition... either constant or symbolic
2078 ValueRef : SymbolicValueRef | ConstValueRef;
2081 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2082 // type immediately preceeds the value reference, and allows complex constant
2083 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2084 ResolvedVal : Types ValueRef {
2085 $$ = getVal(*$1, $2); delete $1;
2089 BasicBlockList : BasicBlockList BasicBlock {
2093 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2099 // Basic blocks are terminated by branching instructions:
2100 // br, br/cc, switch, ret
2102 BasicBlock : InstructionList OptAssign BBTerminatorInst {
2103 setValueName($3, $2);
2107 $1->getInstList().push_back($3);
2113 InstructionList : InstructionList Inst {
2114 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2115 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2116 if (CI2->getParent() == 0)
2117 $1->getInstList().push_back(CI2);
2118 $1->getInstList().push_back($2);
2123 $$ = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2126 // Make sure to move the basic block to the correct location in the
2127 // function, instead of leaving it inserted wherever it was first
2129 Function::BasicBlockListType &BBL =
2130 CurFun.CurrentFunction->getBasicBlockList();
2131 BBL.splice(BBL.end(), BBL, $$);
2135 $$ = getBBVal(ValID::create($1), true);
2138 // Make sure to move the basic block to the correct location in the
2139 // function, instead of leaving it inserted wherever it was first
2141 Function::BasicBlockListType &BBL =
2142 CurFun.CurrentFunction->getBasicBlockList();
2143 BBL.splice(BBL.end(), BBL, $$);
2147 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2148 $$ = new ReturnInst($2);
2151 | RET VOID { // Return with no result...
2152 $$ = new ReturnInst();
2155 | BR LABEL ValueRef { // Unconditional Branch...
2156 BasicBlock* tmpBB = getBBVal($3);
2158 $$ = new BranchInst(tmpBB);
2159 } // Conditional Branch...
2160 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2161 BasicBlock* tmpBBA = getBBVal($6);
2163 BasicBlock* tmpBBB = getBBVal($9);
2165 Value* tmpVal = getVal(Type::BoolTy, $3);
2167 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2169 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2170 Value* tmpVal = getVal($2, $3);
2172 BasicBlock* tmpBB = getBBVal($6);
2174 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2177 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2179 for (; I != E; ++I) {
2180 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2181 S->addCase(CI, I->second);
2183 GEN_ERROR("Switch case is constant, but not a simple integer!");
2188 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2189 Value* tmpVal = getVal($2, $3);
2191 BasicBlock* tmpBB = getBBVal($6);
2193 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2197 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2198 TO LABEL ValueRef UNWIND LABEL ValueRef {
2199 const PointerType *PFTy;
2200 const FunctionType *Ty;
2202 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2203 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2204 // Pull out the types of all of the arguments...
2205 std::vector<const Type*> ParamTypes;
2207 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2209 ParamTypes.push_back((*I)->getType());
2212 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2213 if (isVarArg) ParamTypes.pop_back();
2215 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2216 PFTy = PointerType::get(Ty);
2219 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2221 BasicBlock *Normal = getBBVal($10);
2223 BasicBlock *Except = getBBVal($13);
2226 // Create the call node...
2227 if (!$6) { // Has no arguments?
2228 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2229 } else { // Has arguments?
2230 // Loop through FunctionType's arguments and ensure they are specified
2233 FunctionType::param_iterator I = Ty->param_begin();
2234 FunctionType::param_iterator E = Ty->param_end();
2235 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2237 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2238 if ((*ArgI)->getType() != *I)
2239 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2240 (*I)->getDescription() + "'!");
2242 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2243 GEN_ERROR("Invalid number of parameters detected!");
2245 $$ = new InvokeInst(V, Normal, Except, *$6);
2247 cast<InvokeInst>($$)->setCallingConv($2);
2254 $$ = new UnwindInst();
2258 $$ = new UnreachableInst();
2264 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2266 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2269 GEN_ERROR("May only switch on a constant pool value!");
2271 BasicBlock* tmpBB = getBBVal($6);
2273 $$->push_back(std::make_pair(V, tmpBB));
2275 | IntType ConstValueRef ',' LABEL ValueRef {
2276 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2277 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2281 GEN_ERROR("May only switch on a constant pool value!");
2283 BasicBlock* tmpBB = getBBVal($5);
2285 $$->push_back(std::make_pair(V, tmpBB));
2288 Inst : OptAssign InstVal {
2289 // Is this definition named?? if so, assign the name...
2290 setValueName($2, $1);
2297 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2298 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2299 Value* tmpVal = getVal(*$1, $3);
2301 BasicBlock* tmpBB = getBBVal($5);
2303 $$->push_back(std::make_pair(tmpVal, tmpBB));
2306 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2308 Value* tmpVal = getVal($1->front().first->getType(), $4);
2310 BasicBlock* tmpBB = getBBVal($6);
2312 $1->push_back(std::make_pair(tmpVal, tmpBB));
2316 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2317 $$ = new std::vector<Value*>();
2320 | ValueRefList ',' ResolvedVal {
2326 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2327 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2329 OptTailCall : TAIL CALL {
2338 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2339 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2340 !isa<PackedType>((*$2).get()))
2342 "Arithmetic operator requires integer, FP, or packed operands!");
2343 if (isa<PackedType>((*$2).get()) &&
2344 ($1 == Instruction::URem ||
2345 $1 == Instruction::SRem ||
2346 $1 == Instruction::FRem))
2347 GEN_ERROR("U/S/FRem not supported on packed types!");
2348 Value* val1 = getVal(*$2, $3);
2350 Value* val2 = getVal(*$2, $5);
2352 $$ = BinaryOperator::create($1, val1, val2);
2354 GEN_ERROR("binary operator returned null!");
2357 | LogicalOps Types ValueRef ',' ValueRef {
2358 if (!(*$2)->isIntegral()) {
2359 if (!isa<PackedType>($2->get()) ||
2360 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2361 GEN_ERROR("Logical operator requires integral operands!");
2363 Value* tmpVal1 = getVal(*$2, $3);
2365 Value* tmpVal2 = getVal(*$2, $5);
2367 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2369 GEN_ERROR("binary operator returned null!");
2372 | SetCondOps Types ValueRef ',' ValueRef {
2373 if(isa<PackedType>((*$2).get())) {
2375 "PackedTypes currently not supported in setcc instructions!");
2377 Value* tmpVal1 = getVal(*$2, $3);
2379 Value* tmpVal2 = getVal(*$2, $5);
2381 $$ = new SetCondInst($1, tmpVal1, tmpVal2);
2383 GEN_ERROR("binary operator returned null!");
2386 | ICMP IPredicates Types ValueRef ',' ValueRef {
2387 if (isa<PackedType>((*$3).get()))
2388 GEN_ERROR("Packed types not supported by icmp instruction");
2389 Value* tmpVal1 = getVal(*$3, $4);
2391 Value* tmpVal2 = getVal(*$3, $6);
2393 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2395 GEN_ERROR("icmp operator returned null!");
2397 | FCMP FPredicates Types ValueRef ',' ValueRef {
2398 if (isa<PackedType>((*$3).get()))
2399 GEN_ERROR("Packed types not supported by fcmp instruction");
2400 Value* tmpVal1 = getVal(*$3, $4);
2402 Value* tmpVal2 = getVal(*$3, $6);
2404 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2406 GEN_ERROR("fcmp operator returned null!");
2409 cerr << "WARNING: Use of eliminated 'not' instruction:"
2410 << " Replacing with 'xor'.\n";
2412 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2414 GEN_ERROR("Expected integral type for not instruction!");
2416 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2418 GEN_ERROR("Could not create a xor instruction!");
2421 | ShiftOps ResolvedVal ',' ResolvedVal {
2422 if ($4->getType() != Type::UByteTy)
2423 GEN_ERROR("Shift amount must be ubyte!");
2424 if (!$2->getType()->isInteger())
2425 GEN_ERROR("Shift constant expression requires integer operand!");
2427 $$ = new ShiftInst($1, $2, $4);
2430 | CastOps ResolvedVal TO Types {
2432 const Type* Ty = $4->get();
2433 if (!Val->getType()->isFirstClassType())
2434 GEN_ERROR("cast from a non-primitive type: '" +
2435 Val->getType()->getDescription() + "'!");
2436 if (!Ty->isFirstClassType())
2437 GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2438 $$ = CastInst::create($1, $2, $4->get());
2441 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2442 if ($2->getType() != Type::BoolTy)
2443 GEN_ERROR("select condition must be boolean!");
2444 if ($4->getType() != $6->getType())
2445 GEN_ERROR("select value types should match!");
2446 $$ = new SelectInst($2, $4, $6);
2449 | VAARG ResolvedVal ',' Types {
2450 $$ = new VAArgInst($2, *$4);
2454 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2455 if (!ExtractElementInst::isValidOperands($2, $4))
2456 GEN_ERROR("Invalid extractelement operands!");
2457 $$ = new ExtractElementInst($2, $4);
2460 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2461 if (!InsertElementInst::isValidOperands($2, $4, $6))
2462 GEN_ERROR("Invalid insertelement operands!");
2463 $$ = new InsertElementInst($2, $4, $6);
2466 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2467 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2468 GEN_ERROR("Invalid shufflevector operands!");
2469 $$ = new ShuffleVectorInst($2, $4, $6);
2473 const Type *Ty = $2->front().first->getType();
2474 if (!Ty->isFirstClassType())
2475 GEN_ERROR("PHI node operands must be of first class type!");
2476 $$ = new PHINode(Ty);
2477 ((PHINode*)$$)->reserveOperandSpace($2->size());
2478 while ($2->begin() != $2->end()) {
2479 if ($2->front().first->getType() != Ty)
2480 GEN_ERROR("All elements of a PHI node must be of the same type!");
2481 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2484 delete $2; // Free the list...
2487 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2488 const PointerType *PFTy = 0;
2489 const FunctionType *Ty = 0;
2491 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2492 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2493 // Pull out the types of all of the arguments...
2494 std::vector<const Type*> ParamTypes;
2496 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2498 ParamTypes.push_back((*I)->getType());
2501 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2502 if (isVarArg) ParamTypes.pop_back();
2504 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2505 GEN_ERROR("LLVM functions cannot return aggregate types!");
2507 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2508 PFTy = PointerType::get(Ty);
2511 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2514 // Create the call node...
2515 if (!$6) { // Has no arguments?
2516 // Make sure no arguments is a good thing!
2517 if (Ty->getNumParams() != 0)
2518 GEN_ERROR("No arguments passed to a function that "
2519 "expects arguments!");
2521 $$ = new CallInst(V, std::vector<Value*>());
2522 } else { // Has arguments?
2523 // Loop through FunctionType's arguments and ensure they are specified
2526 FunctionType::param_iterator I = Ty->param_begin();
2527 FunctionType::param_iterator E = Ty->param_end();
2528 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2530 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2531 if ((*ArgI)->getType() != *I)
2532 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2533 (*I)->getDescription() + "'!");
2535 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2536 GEN_ERROR("Invalid number of parameters detected!");
2538 $$ = new CallInst(V, *$6);
2540 cast<CallInst>($$)->setTailCall($1);
2541 cast<CallInst>($$)->setCallingConv($2);
2552 // IndexList - List of indices for GEP based instructions...
2553 IndexList : ',' ValueRefList {
2557 $$ = new std::vector<Value*>();
2561 OptVolatile : VOLATILE {
2572 MemoryInst : MALLOC Types OptCAlign {
2573 $$ = new MallocInst(*$2, 0, $3);
2577 | MALLOC Types ',' UINT ValueRef OptCAlign {
2578 Value* tmpVal = getVal($4, $5);
2580 $$ = new MallocInst(*$2, tmpVal, $6);
2583 | ALLOCA Types OptCAlign {
2584 $$ = new AllocaInst(*$2, 0, $3);
2588 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2589 Value* tmpVal = getVal($4, $5);
2591 $$ = new AllocaInst(*$2, tmpVal, $6);
2594 | FREE ResolvedVal {
2595 if (!isa<PointerType>($2->getType()))
2596 GEN_ERROR("Trying to free nonpointer type " +
2597 $2->getType()->getDescription() + "!");
2598 $$ = new FreeInst($2);
2602 | OptVolatile LOAD Types ValueRef {
2603 if (!isa<PointerType>($3->get()))
2604 GEN_ERROR("Can't load from nonpointer type: " +
2605 (*$3)->getDescription());
2606 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2607 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2608 (*$3)->getDescription());
2609 Value* tmpVal = getVal(*$3, $4);
2611 $$ = new LoadInst(tmpVal, "", $1);
2614 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2615 const PointerType *PT = dyn_cast<PointerType>($5->get());
2617 GEN_ERROR("Can't store to a nonpointer type: " +
2618 (*$5)->getDescription());
2619 const Type *ElTy = PT->getElementType();
2620 if (ElTy != $3->getType())
2621 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2622 "' into space of type '" + ElTy->getDescription() + "'!");
2624 Value* tmpVal = getVal(*$5, $6);
2626 $$ = new StoreInst($3, tmpVal, $1);
2629 | GETELEMENTPTR Types ValueRef IndexList {
2630 if (!isa<PointerType>($2->get()))
2631 GEN_ERROR("getelementptr insn requires pointer operand!");
2633 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2634 GEN_ERROR("Invalid getelementptr indices for type '" +
2635 (*$2)->getDescription()+ "'!");
2636 Value* tmpVal = getVal(*$2, $3);
2638 $$ = new GetElementPtrInst(tmpVal, *$4);
2646 void llvm::GenerateError(const std::string &message, int LineNo) {
2647 if (LineNo == -1) LineNo = llvmAsmlineno;
2648 // TODO: column number in exception
2650 TheParseError->setError(CurFilename, message, LineNo);
2654 int yyerror(const char *ErrorMsg) {
2656 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2657 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2658 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2659 if (yychar == YYEMPTY || yychar == 0)
2660 errMsg += "end-of-file.";
2662 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2663 GenerateError(errMsg);