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) llvm_cerr << X
65 #define YYERROR_VERBOSE 1
67 static bool NewVarArgs;
68 static GlobalVariable *CurGV;
71 // This contains info used when building the body of a function. It is
72 // destroyed when the function is completed.
74 typedef std::vector<Value *> ValueList; // Numbered defs
76 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
77 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
79 static struct PerModuleInfo {
80 Module *CurrentModule;
81 std::map<const Type *, ValueList> Values; // Module level numbered definitions
82 std::map<const Type *,ValueList> LateResolveValues;
83 std::vector<PATypeHolder> Types;
84 std::map<ValID, PATypeHolder> LateResolveTypes;
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
96 typedef std::map<std::pair<const PointerType *,
97 ValID>, GlobalValue*> GlobalRefsType;
98 GlobalRefsType GlobalRefs;
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
105 ResolveDefinitions(LateResolveValues);
109 // Check to make sure that all global value forward references have been
112 if (!GlobalRefs.empty()) {
113 std::string UndefinedReferences = "Unresolved global references exist:\n";
115 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
117 UndefinedReferences += " " + I->first.first->getDescription() + " " +
118 I->first.second.getName() + "\n";
120 GenerateError(UndefinedReferences);
124 Values.clear(); // Clear out function local definitions
129 // GetForwardRefForGlobal - Check to see if there is a forward reference
130 // for this global. If so, remove it from the GlobalRefs map and return it.
131 // If not, just return null.
132 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
133 // Check to see if there is a forward reference to this global variable...
134 // if there is, eliminate it and patch the reference to use the new def'n.
135 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
136 GlobalValue *Ret = 0;
137 if (I != GlobalRefs.end()) {
145 static struct PerFunctionInfo {
146 Function *CurrentFunction; // Pointer to current function being created
148 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
149 std::map<const Type*, ValueList> LateResolveValues;
150 bool isDeclare; // Is this function a forward declararation?
151 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
153 /// BBForwardRefs - When we see forward references to basic blocks, keep
154 /// track of them here.
155 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
156 std::vector<BasicBlock*> NumberedBlocks;
159 inline PerFunctionInfo() {
162 Linkage = GlobalValue::ExternalLinkage;
165 inline void FunctionStart(Function *M) {
170 void FunctionDone() {
171 NumberedBlocks.clear();
173 // Any forward referenced blocks left?
174 if (!BBForwardRefs.empty()) {
175 GenerateError("Undefined reference to label " +
176 BBForwardRefs.begin()->first->getName());
180 // Resolve all forward references now.
181 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
183 Values.clear(); // Clear out function local definitions
186 Linkage = GlobalValue::ExternalLinkage;
188 } CurFun; // Info for the current function...
190 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
193 //===----------------------------------------------------------------------===//
194 // Code to handle definitions of all the types
195 //===----------------------------------------------------------------------===//
197 static int InsertValue(Value *V,
198 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
199 if (V->hasName()) return -1; // Is this a numbered definition?
201 // Yes, insert the value into the value table...
202 ValueList &List = ValueTab[V->getType()];
204 return List.size()-1;
207 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
209 case ValID::NumberVal: // Is it a numbered definition?
210 // Module constants occupy the lowest numbered slots...
211 if ((unsigned)D.Num < CurModule.Types.size())
212 return CurModule.Types[(unsigned)D.Num];
214 case ValID::NameVal: // Is it a named definition?
215 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
216 D.destroy(); // Free old strdup'd memory...
221 GenerateError("Internal parser error: Invalid symbol type reference!");
225 // If we reached here, we referenced either a symbol that we don't know about
226 // or an id number that hasn't been read yet. We may be referencing something
227 // forward, so just create an entry to be resolved later and get to it...
229 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
232 if (inFunctionScope()) {
233 if (D.Type == ValID::NameVal) {
234 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
237 GenerateError("Reference to an undefined type: #" + itostr(D.Num));
242 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
243 if (I != CurModule.LateResolveTypes.end())
246 Type *Typ = OpaqueType::get();
247 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
251 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
252 SymbolTable &SymTab =
253 inFunctionScope() ? CurFun.CurrentFunction->getSymbolTable() :
254 CurModule.CurrentModule->getSymbolTable();
255 return SymTab.lookup(Ty, Name);
258 // getValNonImprovising - Look up the value specified by the provided type and
259 // the provided ValID. If the value exists and has already been defined, return
260 // it. Otherwise return null.
262 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
263 if (isa<FunctionType>(Ty)) {
264 GenerateError("Functions are not values and "
265 "must be referenced as pointers");
270 case ValID::NumberVal: { // Is it a numbered definition?
271 unsigned Num = (unsigned)D.Num;
273 // Module constants occupy the lowest numbered slots...
274 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
275 if (VI != CurModule.Values.end()) {
276 if (Num < VI->second.size())
277 return VI->second[Num];
278 Num -= VI->second.size();
281 // Make sure that our type is within bounds
282 VI = CurFun.Values.find(Ty);
283 if (VI == CurFun.Values.end()) return 0;
285 // Check that the number is within bounds...
286 if (VI->second.size() <= Num) return 0;
288 return VI->second[Num];
291 case ValID::NameVal: { // Is it a named definition?
292 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
293 if (N == 0) return 0;
295 D.destroy(); // Free old strdup'd memory...
299 // Check to make sure that "Ty" is an integral type, and that our
300 // value will fit into the specified type...
301 case ValID::ConstSIntVal: // Is it a constant pool reference??
302 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
303 GenerateError("Signed integral constant '" +
304 itostr(D.ConstPool64) + "' is invalid for type '" +
305 Ty->getDescription() + "'!");
308 return ConstantInt::get(Ty, D.ConstPool64);
310 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
311 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
312 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
313 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
314 "' is invalid or out of range!");
316 } else { // This is really a signed reference. Transmogrify.
317 return ConstantInt::get(Ty, D.ConstPool64);
320 return ConstantInt::get(Ty, D.UConstPool64);
323 case ValID::ConstFPVal: // Is it a floating point const pool reference?
324 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
325 GenerateError("FP constant invalid for type!!");
328 return ConstantFP::get(Ty, D.ConstPoolFP);
330 case ValID::ConstNullVal: // Is it a null value?
331 if (!isa<PointerType>(Ty)) {
332 GenerateError("Cannot create a a non pointer null!");
335 return ConstantPointerNull::get(cast<PointerType>(Ty));
337 case ValID::ConstUndefVal: // Is it an undef value?
338 return UndefValue::get(Ty);
340 case ValID::ConstZeroVal: // Is it a zero value?
341 return Constant::getNullValue(Ty);
343 case ValID::ConstantVal: // Fully resolved constant?
344 if (D.ConstantValue->getType() != Ty) {
345 GenerateError("Constant expression type different from required type!");
348 return D.ConstantValue;
350 case ValID::InlineAsmVal: { // Inline asm expression
351 const PointerType *PTy = dyn_cast<PointerType>(Ty);
352 const FunctionType *FTy =
353 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
354 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
355 GenerateError("Invalid type for asm constraint string!");
358 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
359 D.IAD->HasSideEffects);
360 D.destroy(); // Free InlineAsmDescriptor.
364 assert(0 && "Unhandled case!");
368 assert(0 && "Unhandled case!");
372 // getVal - This function is identical to getValNonImprovising, except that if a
373 // value is not already defined, it "improvises" by creating a placeholder var
374 // that looks and acts just like the requested variable. When the value is
375 // defined later, all uses of the placeholder variable are replaced with the
378 static Value *getVal(const Type *Ty, const ValID &ID) {
379 if (Ty == Type::LabelTy) {
380 GenerateError("Cannot use a basic block here");
384 // See if the value has already been defined.
385 Value *V = getValNonImprovising(Ty, ID);
387 if (TriggerError) return 0;
389 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
390 GenerateError("Invalid use of a composite type!");
394 // If we reached here, we referenced either a symbol that we don't know about
395 // or an id number that hasn't been read yet. We may be referencing something
396 // forward, so just create an entry to be resolved later and get to it...
398 V = new Argument(Ty);
400 // Remember where this forward reference came from. FIXME, shouldn't we try
401 // to recycle these things??
402 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
405 if (inFunctionScope())
406 InsertValue(V, CurFun.LateResolveValues);
408 InsertValue(V, CurModule.LateResolveValues);
412 /// getBBVal - This is used for two purposes:
413 /// * If isDefinition is true, a new basic block with the specified ID is being
415 /// * If isDefinition is true, this is a reference to a basic block, which may
416 /// or may not be a forward reference.
418 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
419 assert(inFunctionScope() && "Can't get basic block at global scope!");
425 GenerateError("Illegal label reference " + ID.getName());
427 case ValID::NumberVal: // Is it a numbered definition?
428 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
429 CurFun.NumberedBlocks.resize(ID.Num+1);
430 BB = CurFun.NumberedBlocks[ID.Num];
432 case ValID::NameVal: // Is it a named definition?
434 if (Value *N = CurFun.CurrentFunction->
435 getSymbolTable().lookup(Type::LabelTy, Name))
436 BB = cast<BasicBlock>(N);
440 // See if the block has already been defined.
442 // If this is the definition of the block, make sure the existing value was
443 // just a forward reference. If it was a forward reference, there will be
444 // an entry for it in the PlaceHolderInfo map.
445 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
446 // The existing value was a definition, not a forward reference.
447 GenerateError("Redefinition of label " + ID.getName());
451 ID.destroy(); // Free strdup'd memory.
455 // Otherwise this block has not been seen before.
456 BB = new BasicBlock("", CurFun.CurrentFunction);
457 if (ID.Type == ValID::NameVal) {
458 BB->setName(ID.Name);
460 CurFun.NumberedBlocks[ID.Num] = BB;
463 // If this is not a definition, keep track of it so we can use it as a forward
466 // Remember where this forward reference came from.
467 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
469 // The forward declaration could have been inserted anywhere in the
470 // function: insert it into the correct place now.
471 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
472 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
479 //===----------------------------------------------------------------------===//
480 // Code to handle forward references in instructions
481 //===----------------------------------------------------------------------===//
483 // This code handles the late binding needed with statements that reference
484 // values not defined yet... for example, a forward branch, or the PHI node for
487 // This keeps a table (CurFun.LateResolveValues) of all such forward references
488 // and back patchs after we are done.
491 // ResolveDefinitions - If we could not resolve some defs at parsing
492 // time (forward branches, phi functions for loops, etc...) resolve the
496 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
497 std::map<const Type*,ValueList> *FutureLateResolvers) {
498 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
499 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
500 E = LateResolvers.end(); LRI != E; ++LRI) {
501 ValueList &List = LRI->second;
502 while (!List.empty()) {
503 Value *V = List.back();
506 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
507 CurModule.PlaceHolderInfo.find(V);
508 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
510 ValID &DID = PHI->second.first;
512 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
516 V->replaceAllUsesWith(TheRealValue);
518 CurModule.PlaceHolderInfo.erase(PHI);
519 } else if (FutureLateResolvers) {
520 // Functions have their unresolved items forwarded to the module late
522 InsertValue(V, *FutureLateResolvers);
524 if (DID.Type == ValID::NameVal) {
525 GenerateError("Reference to an invalid definition: '" +DID.getName()+
526 "' of type '" + V->getType()->getDescription() + "'",
530 GenerateError("Reference to an invalid definition: #" +
531 itostr(DID.Num) + " of type '" +
532 V->getType()->getDescription() + "'",
540 LateResolvers.clear();
543 // ResolveTypeTo - A brand new type was just declared. This means that (if
544 // name is not null) things referencing Name can be resolved. Otherwise, things
545 // refering to the number can be resolved. Do this now.
547 static void ResolveTypeTo(char *Name, const Type *ToTy) {
549 if (Name) D = ValID::create(Name);
550 else D = ValID::create((int)CurModule.Types.size());
552 std::map<ValID, PATypeHolder>::iterator I =
553 CurModule.LateResolveTypes.find(D);
554 if (I != CurModule.LateResolveTypes.end()) {
555 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
556 CurModule.LateResolveTypes.erase(I);
560 // setValueName - Set the specified value to the name given. The name may be
561 // null potentially, in which case this is a noop. The string passed in is
562 // assumed to be a malloc'd string buffer, and is free'd by this function.
564 static void setValueName(Value *V, char *NameStr) {
566 std::string Name(NameStr); // Copy string
567 free(NameStr); // Free old string
569 if (V->getType() == Type::VoidTy) {
570 GenerateError("Can't assign name '" + Name+"' to value with void type!");
574 assert(inFunctionScope() && "Must be in function scope!");
575 SymbolTable &ST = CurFun.CurrentFunction->getSymbolTable();
576 if (ST.lookup(V->getType(), Name)) {
577 GenerateError("Redefinition of value named '" + Name + "' in the '" +
578 V->getType()->getDescription() + "' type plane!");
587 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
588 /// this is a declaration, otherwise it is a definition.
589 static GlobalVariable *
590 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
591 bool isConstantGlobal, const Type *Ty,
592 Constant *Initializer) {
593 if (isa<FunctionType>(Ty)) {
594 GenerateError("Cannot declare global vars of function type!");
598 const PointerType *PTy = PointerType::get(Ty);
602 Name = NameStr; // Copy string
603 free(NameStr); // Free old string
606 // See if this global value was forward referenced. If so, recycle the
610 ID = ValID::create((char*)Name.c_str());
612 ID = ValID::create((int)CurModule.Values[PTy].size());
615 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
616 // Move the global to the end of the list, from whereever it was
617 // previously inserted.
618 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
619 CurModule.CurrentModule->getGlobalList().remove(GV);
620 CurModule.CurrentModule->getGlobalList().push_back(GV);
621 GV->setInitializer(Initializer);
622 GV->setLinkage(Linkage);
623 GV->setConstant(isConstantGlobal);
624 InsertValue(GV, CurModule.Values);
628 // If this global has a name, check to see if there is already a definition
629 // of this global in the module. If so, merge as appropriate. Note that
630 // this is really just a hack around problems in the CFE. :(
632 // We are a simple redefinition of a value, check to see if it is defined
633 // the same as the old one.
634 if (GlobalVariable *EGV =
635 CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
636 // We are allowed to redefine a global variable in two circumstances:
637 // 1. If at least one of the globals is uninitialized or
638 // 2. If both initializers have the same value.
640 if (!EGV->hasInitializer() || !Initializer ||
641 EGV->getInitializer() == Initializer) {
643 // Make sure the existing global version gets the initializer! Make
644 // sure that it also gets marked const if the new version is.
645 if (Initializer && !EGV->hasInitializer())
646 EGV->setInitializer(Initializer);
647 if (isConstantGlobal)
648 EGV->setConstant(true);
649 EGV->setLinkage(Linkage);
653 GenerateError("Redefinition of global variable named '" + Name +
654 "' in the '" + Ty->getDescription() + "' type plane!");
659 // Otherwise there is no existing GV to use, create one now.
661 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
662 CurModule.CurrentModule);
663 InsertValue(GV, CurModule.Values);
667 // setTypeName - Set the specified type to the name given. The name may be
668 // null potentially, in which case this is a noop. The string passed in is
669 // assumed to be a malloc'd string buffer, and is freed by this function.
671 // This function returns true if the type has already been defined, but is
672 // allowed to be redefined in the specified context. If the name is a new name
673 // for the type plane, it is inserted and false is returned.
674 static bool setTypeName(const Type *T, char *NameStr) {
675 assert(!inFunctionScope() && "Can't give types function-local names!");
676 if (NameStr == 0) return false;
678 std::string Name(NameStr); // Copy string
679 free(NameStr); // Free old string
681 // We don't allow assigning names to void type
682 if (T == Type::VoidTy) {
683 GenerateError("Can't assign name '" + Name + "' to the void type!");
687 // Set the type name, checking for conflicts as we do so.
688 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
690 if (AlreadyExists) { // Inserting a name that is already defined???
691 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
692 assert(Existing && "Conflict but no matching type?");
694 // There is only one case where this is allowed: when we are refining an
695 // opaque type. In this case, Existing will be an opaque type.
696 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
697 // We ARE replacing an opaque type!
698 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
702 // Otherwise, this is an attempt to redefine a type. That's okay if
703 // the redefinition is identical to the original. This will be so if
704 // Existing and T point to the same Type object. In this one case we
705 // allow the equivalent redefinition.
706 if (Existing == T) return true; // Yes, it's equal.
708 // Any other kind of (non-equivalent) redefinition is an error.
709 GenerateError("Redefinition of type named '" + Name + "' in the '" +
710 T->getDescription() + "' type plane!");
716 //===----------------------------------------------------------------------===//
717 // Code for handling upreferences in type names...
720 // TypeContains - Returns true if Ty directly contains E in it.
722 static bool TypeContains(const Type *Ty, const Type *E) {
723 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
724 E) != Ty->subtype_end();
729 // NestingLevel - The number of nesting levels that need to be popped before
730 // this type is resolved.
731 unsigned NestingLevel;
733 // LastContainedTy - This is the type at the current binding level for the
734 // type. Every time we reduce the nesting level, this gets updated.
735 const Type *LastContainedTy;
737 // UpRefTy - This is the actual opaque type that the upreference is
741 UpRefRecord(unsigned NL, OpaqueType *URTy)
742 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
746 // UpRefs - A list of the outstanding upreferences that need to be resolved.
747 static std::vector<UpRefRecord> UpRefs;
749 /// HandleUpRefs - Every time we finish a new layer of types, this function is
750 /// called. It loops through the UpRefs vector, which is a list of the
751 /// currently active types. For each type, if the up reference is contained in
752 /// the newly completed type, we decrement the level count. When the level
753 /// count reaches zero, the upreferenced type is the type that is passed in:
754 /// thus we can complete the cycle.
756 static PATypeHolder HandleUpRefs(const Type *ty) {
757 // If Ty isn't abstract, or if there are no up-references in it, then there is
758 // nothing to resolve here.
759 if (!ty->isAbstract() || UpRefs.empty()) return ty;
762 UR_OUT("Type '" << Ty->getDescription() <<
763 "' newly formed. Resolving upreferences.\n" <<
764 UpRefs.size() << " upreferences active!\n");
766 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
767 // to zero), we resolve them all together before we resolve them to Ty. At
768 // the end of the loop, if there is anything to resolve to Ty, it will be in
770 OpaqueType *TypeToResolve = 0;
772 for (unsigned i = 0; i != UpRefs.size(); ++i) {
773 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
774 << UpRefs[i].second->getDescription() << ") = "
775 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
776 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
777 // Decrement level of upreference
778 unsigned Level = --UpRefs[i].NestingLevel;
779 UpRefs[i].LastContainedTy = Ty;
780 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
781 if (Level == 0) { // Upreference should be resolved!
782 if (!TypeToResolve) {
783 TypeToResolve = UpRefs[i].UpRefTy;
785 UR_OUT(" * Resolving upreference for "
786 << UpRefs[i].second->getDescription() << "\n";
787 std::string OldName = UpRefs[i].UpRefTy->getDescription());
788 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
789 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
790 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
792 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
793 --i; // Do not skip the next element...
799 UR_OUT(" * Resolving upreference for "
800 << UpRefs[i].second->getDescription() << "\n";
801 std::string OldName = TypeToResolve->getDescription());
802 TypeToResolve->refineAbstractTypeTo(Ty);
808 // common code from the two 'RunVMAsmParser' functions
809 static Module* RunParser(Module * M) {
811 llvmAsmlineno = 1; // Reset the current line number...
813 CurModule.CurrentModule = M;
815 // Check to make sure the parser succeeded
822 // Check to make sure that parsing produced a result
826 // Reset ParserResult variable while saving its value for the result.
827 Module *Result = ParserResult;
833 //===----------------------------------------------------------------------===//
834 // RunVMAsmParser - Define an interface to this parser
835 //===----------------------------------------------------------------------===//
837 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
840 CurFilename = Filename;
841 return RunParser(new Module(CurFilename));
844 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
845 set_scan_string(AsmString);
847 CurFilename = "from_memory";
849 return RunParser(new Module (CurFilename));
858 llvm::Module *ModuleVal;
859 llvm::Function *FunctionVal;
860 std::pair<llvm::PATypeHolder*, char*> *ArgVal;
861 llvm::BasicBlock *BasicBlockVal;
862 llvm::TerminatorInst *TermInstVal;
863 llvm::Instruction *InstVal;
864 llvm::Constant *ConstVal;
866 const llvm::Type *PrimType;
867 llvm::PATypeHolder *TypeVal;
868 llvm::Value *ValueVal;
870 std::vector<std::pair<llvm::PATypeHolder*,char*> > *ArgList;
871 std::vector<llvm::Value*> *ValueList;
872 std::list<llvm::PATypeHolder> *TypeList;
873 // Represent the RHS of PHI node
874 std::list<std::pair<llvm::Value*,
875 llvm::BasicBlock*> > *PHIList;
876 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
877 std::vector<llvm::Constant*> *ConstVector;
879 llvm::GlobalValue::LinkageTypes Linkage;
887 char *StrVal; // This memory is strdup'd!
888 llvm::ValID ValIDVal; // strdup'd memory maybe!
890 llvm::Instruction::BinaryOps BinaryOpVal;
891 llvm::Instruction::TermOps TermOpVal;
892 llvm::Instruction::MemoryOps MemOpVal;
893 llvm::Instruction::CastOps CastOpVal;
894 llvm::Instruction::OtherOps OtherOpVal;
895 llvm::Module::Endianness Endianness;
896 llvm::ICmpInst::Predicate IPredicate;
897 llvm::FCmpInst::Predicate FPredicate;
900 %type <ModuleVal> Module FunctionList
901 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
902 %type <BasicBlockVal> BasicBlock InstructionList
903 %type <TermInstVal> BBTerminatorInst
904 %type <InstVal> Inst InstVal MemoryInst
905 %type <ConstVal> ConstVal ConstExpr
906 %type <ConstVector> ConstVector
907 %type <ArgList> ArgList ArgListH
908 %type <ArgVal> ArgVal
909 %type <PHIList> PHIList
910 %type <ValueList> ValueRefList ValueRefListE // For call param lists
911 %type <ValueList> IndexList // For GEP derived indices
912 %type <TypeList> TypeListI ArgTypeListI
913 %type <JumpTable> JumpTable
914 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
915 %type <BoolVal> OptVolatile // 'volatile' or not
916 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
917 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
918 %type <Linkage> OptLinkage
919 %type <Endianness> BigOrLittle
921 // ValueRef - Unresolved reference to a definition or BB
922 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
923 %type <ValueVal> ResolvedVal // <type> <valref> pair
924 // Tokens and types for handling constant integer values
926 // ESINT64VAL - A negative number within long long range
927 %token <SInt64Val> ESINT64VAL
929 // EUINT64VAL - A positive number within uns. long long range
930 %token <UInt64Val> EUINT64VAL
931 %type <SInt64Val> EINT64VAL
933 %token <SIntVal> SINTVAL // Signed 32 bit ints...
934 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
935 %type <SIntVal> INTVAL
936 %token <FPVal> FPVAL // Float or Double constant
939 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
940 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
941 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
942 %token <PrimType> FLOAT DOUBLE TYPE LABEL
944 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
945 %type <StrVal> Name OptName OptAssign
946 %type <UIntVal> OptAlign OptCAlign
947 %type <StrVal> OptSection SectionString
949 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
950 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
951 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
952 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
953 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
954 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
955 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
956 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
958 %type <UIntVal> OptCallingConv
960 // Basic Block Terminating Operators
961 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
964 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
965 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
966 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
967 %token <OtherOpVal> ICMP FCMP
968 %type <IPredicate> IPredicates
969 %type <FPredicate> FPredicates
970 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
971 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
973 // Memory Instructions
974 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
977 %type <CastOpVal> CastOps
978 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
979 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
982 %type <OtherOpVal> ShiftOps
983 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
984 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
990 // Handle constant integer size restriction and conversion...
994 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
995 GEN_ERROR("Value too large for type!");
1001 EINT64VAL : ESINT64VAL; // These have same type and can't cause problems...
1002 EINT64VAL : EUINT64VAL {
1003 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1004 GEN_ERROR("Value too large for type!");
1009 // Operations that are notably excluded from this list include:
1010 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1012 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1013 LogicalOps : AND | OR | XOR;
1014 SetCondOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE;
1015 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1016 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1017 ShiftOps : SHL | LSHR | ASHR;
1019 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1020 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1021 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1022 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1023 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1027 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1028 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1029 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1030 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1031 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1032 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1033 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1034 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1035 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1038 // These are some types that allow classification if we only want a particular
1039 // thing... for example, only a signed, unsigned, or integral type.
1040 SIntType : LONG | INT | SHORT | SBYTE;
1041 UIntType : ULONG | UINT | USHORT | UBYTE;
1042 IntType : SIntType | UIntType;
1043 FPType : FLOAT | DOUBLE;
1045 // OptAssign - Value producing statements have an optional assignment component
1046 OptAssign : Name '=' {
1055 OptLinkage : INTERNAL { $$ = GlobalValue::InternalLinkage; } |
1056 LINKONCE { $$ = GlobalValue::LinkOnceLinkage; } |
1057 WEAK { $$ = GlobalValue::WeakLinkage; } |
1058 APPENDING { $$ = GlobalValue::AppendingLinkage; } |
1059 DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; } |
1060 DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; } |
1061 EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; } |
1062 /*empty*/ { $$ = GlobalValue::ExternalLinkage; };
1064 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1065 CCC_TOK { $$ = CallingConv::C; } |
1066 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
1067 FASTCC_TOK { $$ = CallingConv::Fast; } |
1068 COLDCC_TOK { $$ = CallingConv::Cold; } |
1069 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1070 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1072 if ((unsigned)$2 != $2)
1073 GEN_ERROR("Calling conv too large!");
1078 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1079 // a comma before it.
1080 OptAlign : /*empty*/ { $$ = 0; } |
1083 if ($$ != 0 && !isPowerOf2_32($$))
1084 GEN_ERROR("Alignment must be a power of two!");
1087 OptCAlign : /*empty*/ { $$ = 0; } |
1088 ',' ALIGN EUINT64VAL {
1090 if ($$ != 0 && !isPowerOf2_32($$))
1091 GEN_ERROR("Alignment must be a power of two!");
1096 SectionString : SECTION STRINGCONSTANT {
1097 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1098 if ($2[i] == '"' || $2[i] == '\\')
1099 GEN_ERROR("Invalid character in section name!");
1104 OptSection : /*empty*/ { $$ = 0; } |
1105 SectionString { $$ = $1; };
1107 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1108 // is set to be the global we are processing.
1110 GlobalVarAttributes : /* empty */ {} |
1111 ',' GlobalVarAttribute GlobalVarAttributes {};
1112 GlobalVarAttribute : SectionString {
1113 CurGV->setSection($1);
1117 | ALIGN EUINT64VAL {
1118 if ($2 != 0 && !isPowerOf2_32($2))
1119 GEN_ERROR("Alignment must be a power of two!");
1120 CurGV->setAlignment($2);
1124 //===----------------------------------------------------------------------===//
1125 // Types includes all predefined types... except void, because it can only be
1126 // used in specific contexts (function returning void for example). To have
1127 // access to it, a user must explicitly use TypesV.
1130 // TypesV includes all of 'Types', but it also includes the void type.
1131 TypesV : Types | VOID { $$ = new PATypeHolder($1); };
1132 UpRTypesV : UpRTypes | VOID { $$ = new PATypeHolder($1); };
1135 if (!UpRefs.empty())
1136 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1142 // Derived types are added later...
1144 PrimType : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT ;
1145 PrimType : LONG | ULONG | FLOAT | DOUBLE | TYPE | LABEL;
1147 $$ = new PATypeHolder(OpaqueType::get());
1151 $$ = new PATypeHolder($1);
1154 UpRTypes : SymbolicValueRef { // Named types are also simple types...
1155 const Type* tmp = getTypeVal($1);
1157 $$ = new PATypeHolder(tmp);
1160 // Include derived types in the Types production.
1162 UpRTypes : '\\' EUINT64VAL { // Type UpReference
1163 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1164 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1165 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1166 $$ = new PATypeHolder(OT);
1167 UR_OUT("New Upreference!\n");
1170 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1171 std::vector<const Type*> Params;
1172 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1173 E = $3->end(); I != E; ++I)
1174 Params.push_back(*I);
1175 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1176 if (isVarArg) Params.pop_back();
1178 $$ = new PATypeHolder(HandleUpRefs(FunctionType::get(*$1,Params,isVarArg)));
1179 delete $3; // Delete the argument list
1180 delete $1; // Delete the return type handle
1183 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1184 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1188 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1189 const llvm::Type* ElemTy = $4->get();
1190 if ((unsigned)$2 != $2)
1191 GEN_ERROR("Unsigned result not equal to signed result");
1192 if (!ElemTy->isPrimitiveType())
1193 GEN_ERROR("Elemental type of a PackedType must be primitive");
1194 if (!isPowerOf2_32($2))
1195 GEN_ERROR("Vector length should be a power of 2!");
1196 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1200 | '{' TypeListI '}' { // Structure type?
1201 std::vector<const Type*> Elements;
1202 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1203 E = $2->end(); I != E; ++I)
1204 Elements.push_back(*I);
1206 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1210 | '{' '}' { // Empty structure type?
1211 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1214 | UpRTypes '*' { // Pointer type?
1215 if (*$1 == Type::LabelTy)
1216 GEN_ERROR("Cannot form a pointer to a basic block");
1217 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1222 // TypeList - Used for struct declarations and as a basis for function type
1223 // declaration type lists
1225 TypeListI : UpRTypes {
1226 $$ = new std::list<PATypeHolder>();
1227 $$->push_back(*$1); delete $1;
1230 | TypeListI ',' UpRTypes {
1231 ($$=$1)->push_back(*$3); delete $3;
1235 // ArgTypeList - List of types for a function type declaration...
1236 ArgTypeListI : TypeListI
1237 | TypeListI ',' DOTDOTDOT {
1238 ($$=$1)->push_back(Type::VoidTy);
1242 ($$ = new std::list<PATypeHolder>())->push_back(Type::VoidTy);
1246 $$ = new std::list<PATypeHolder>();
1250 // ConstVal - The various declarations that go into the constant pool. This
1251 // production is used ONLY to represent constants that show up AFTER a 'const',
1252 // 'constant' or 'global' token at global scope. Constants that can be inlined
1253 // into other expressions (such as integers and constexprs) are handled by the
1254 // ResolvedVal, ValueRef and ConstValueRef productions.
1256 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1257 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1259 GEN_ERROR("Cannot make array constant with type: '" +
1260 (*$1)->getDescription() + "'!");
1261 const Type *ETy = ATy->getElementType();
1262 int NumElements = ATy->getNumElements();
1264 // Verify that we have the correct size...
1265 if (NumElements != -1 && NumElements != (int)$3->size())
1266 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1267 utostr($3->size()) + " arguments, but has size of " +
1268 itostr(NumElements) + "!");
1270 // Verify all elements are correct type!
1271 for (unsigned i = 0; i < $3->size(); i++) {
1272 if (ETy != (*$3)[i]->getType())
1273 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1274 ETy->getDescription() +"' as required!\nIt is of type '"+
1275 (*$3)[i]->getType()->getDescription() + "'.");
1278 $$ = ConstantArray::get(ATy, *$3);
1279 delete $1; delete $3;
1283 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1285 GEN_ERROR("Cannot make array constant with type: '" +
1286 (*$1)->getDescription() + "'!");
1288 int NumElements = ATy->getNumElements();
1289 if (NumElements != -1 && NumElements != 0)
1290 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1291 " arguments, but has size of " + itostr(NumElements) +"!");
1292 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1296 | Types 'c' STRINGCONSTANT {
1297 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1299 GEN_ERROR("Cannot make array constant with type: '" +
1300 (*$1)->getDescription() + "'!");
1302 int NumElements = ATy->getNumElements();
1303 const Type *ETy = ATy->getElementType();
1304 char *EndStr = UnEscapeLexed($3, true);
1305 if (NumElements != -1 && NumElements != (EndStr-$3))
1306 GEN_ERROR("Can't build string constant of size " +
1307 itostr((int)(EndStr-$3)) +
1308 " when array has size " + itostr(NumElements) + "!");
1309 std::vector<Constant*> Vals;
1310 if (ETy == Type::SByteTy) {
1311 for (signed char *C = (signed char *)$3; C != (signed char *)EndStr; ++C)
1312 Vals.push_back(ConstantInt::get(ETy, *C));
1313 } else if (ETy == Type::UByteTy) {
1314 for (unsigned char *C = (unsigned char *)$3;
1315 C != (unsigned char*)EndStr; ++C)
1316 Vals.push_back(ConstantInt::get(ETy, *C));
1319 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1322 $$ = ConstantArray::get(ATy, Vals);
1326 | Types '<' ConstVector '>' { // Nonempty unsized arr
1327 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1329 GEN_ERROR("Cannot make packed constant with type: '" +
1330 (*$1)->getDescription() + "'!");
1331 const Type *ETy = PTy->getElementType();
1332 int NumElements = PTy->getNumElements();
1334 // Verify that we have the correct size...
1335 if (NumElements != -1 && NumElements != (int)$3->size())
1336 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1337 utostr($3->size()) + " arguments, but has size of " +
1338 itostr(NumElements) + "!");
1340 // Verify all elements are correct type!
1341 for (unsigned i = 0; i < $3->size(); i++) {
1342 if (ETy != (*$3)[i]->getType())
1343 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1344 ETy->getDescription() +"' as required!\nIt is of type '"+
1345 (*$3)[i]->getType()->getDescription() + "'.");
1348 $$ = ConstantPacked::get(PTy, *$3);
1349 delete $1; delete $3;
1352 | Types '{' ConstVector '}' {
1353 const StructType *STy = dyn_cast<StructType>($1->get());
1355 GEN_ERROR("Cannot make struct constant with type: '" +
1356 (*$1)->getDescription() + "'!");
1358 if ($3->size() != STy->getNumContainedTypes())
1359 GEN_ERROR("Illegal number of initializers for structure type!");
1361 // Check to ensure that constants are compatible with the type initializer!
1362 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1363 if ((*$3)[i]->getType() != STy->getElementType(i))
1364 GEN_ERROR("Expected type '" +
1365 STy->getElementType(i)->getDescription() +
1366 "' for element #" + utostr(i) +
1367 " of structure initializer!");
1369 $$ = ConstantStruct::get(STy, *$3);
1370 delete $1; delete $3;
1374 const StructType *STy = dyn_cast<StructType>($1->get());
1376 GEN_ERROR("Cannot make struct constant with type: '" +
1377 (*$1)->getDescription() + "'!");
1379 if (STy->getNumContainedTypes() != 0)
1380 GEN_ERROR("Illegal number of initializers for structure type!");
1382 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1387 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1389 GEN_ERROR("Cannot make null pointer constant with type: '" +
1390 (*$1)->getDescription() + "'!");
1392 $$ = ConstantPointerNull::get(PTy);
1397 $$ = UndefValue::get($1->get());
1401 | Types SymbolicValueRef {
1402 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1404 GEN_ERROR("Global const reference must be a pointer type!");
1406 // ConstExprs can exist in the body of a function, thus creating
1407 // GlobalValues whenever they refer to a variable. Because we are in
1408 // the context of a function, getValNonImprovising will search the functions
1409 // symbol table instead of the module symbol table for the global symbol,
1410 // which throws things all off. To get around this, we just tell
1411 // getValNonImprovising that we are at global scope here.
1413 Function *SavedCurFn = CurFun.CurrentFunction;
1414 CurFun.CurrentFunction = 0;
1416 Value *V = getValNonImprovising(Ty, $2);
1419 CurFun.CurrentFunction = SavedCurFn;
1421 // If this is an initializer for a constant pointer, which is referencing a
1422 // (currently) undefined variable, create a stub now that shall be replaced
1423 // in the future with the right type of variable.
1426 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1427 const PointerType *PT = cast<PointerType>(Ty);
1429 // First check to see if the forward references value is already created!
1430 PerModuleInfo::GlobalRefsType::iterator I =
1431 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1433 if (I != CurModule.GlobalRefs.end()) {
1434 V = I->second; // Placeholder already exists, use it...
1438 if ($2.Type == ValID::NameVal) Name = $2.Name;
1440 // Create the forward referenced global.
1442 if (const FunctionType *FTy =
1443 dyn_cast<FunctionType>(PT->getElementType())) {
1444 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1445 CurModule.CurrentModule);
1447 GV = new GlobalVariable(PT->getElementType(), false,
1448 GlobalValue::ExternalLinkage, 0,
1449 Name, CurModule.CurrentModule);
1452 // Keep track of the fact that we have a forward ref to recycle it
1453 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1458 $$ = cast<GlobalValue>(V);
1459 delete $1; // Free the type handle
1463 if ($1->get() != $2->getType())
1464 GEN_ERROR("Mismatched types for constant expression!");
1469 | Types ZEROINITIALIZER {
1470 const Type *Ty = $1->get();
1471 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1472 GEN_ERROR("Cannot create a null initialized value of this type!");
1473 $$ = Constant::getNullValue(Ty);
1477 | SIntType EINT64VAL { // integral constants
1478 if (!ConstantInt::isValueValidForType($1, $2))
1479 GEN_ERROR("Constant value doesn't fit in type!");
1480 $$ = ConstantInt::get($1, $2);
1483 | UIntType EUINT64VAL { // integral constants
1484 if (!ConstantInt::isValueValidForType($1, $2))
1485 GEN_ERROR("Constant value doesn't fit in type!");
1486 $$ = ConstantInt::get($1, $2);
1489 | BOOL TRUETOK { // Boolean constants
1490 $$ = ConstantBool::getTrue();
1493 | BOOL FALSETOK { // Boolean constants
1494 $$ = ConstantBool::getFalse();
1497 | FPType FPVAL { // Float & Double constants
1498 if (!ConstantFP::isValueValidForType($1, $2))
1499 GEN_ERROR("Floating point constant invalid for type!!");
1500 $$ = ConstantFP::get($1, $2);
1505 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1507 const Type *Ty = $5->get();
1508 if (!Val->getType()->isFirstClassType())
1509 GEN_ERROR("cast constant expression from a non-primitive type: '" +
1510 Val->getType()->getDescription() + "'!");
1511 if (!Ty->isFirstClassType())
1512 GEN_ERROR("cast constant expression to a non-primitive type: '" +
1513 Ty->getDescription() + "'!");
1514 $$ = ConstantExpr::getCast($1, $3, $5->get());
1517 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1518 if (!isa<PointerType>($3->getType()))
1519 GEN_ERROR("GetElementPtr requires a pointer operand!");
1522 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1524 GEN_ERROR("Index list invalid for constant getelementptr!");
1526 std::vector<Constant*> IdxVec;
1527 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1528 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1529 IdxVec.push_back(C);
1531 GEN_ERROR("Indices to constant getelementptr must be constants!");
1535 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1538 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1539 if ($3->getType() != Type::BoolTy)
1540 GEN_ERROR("Select condition must be of boolean type!");
1541 if ($5->getType() != $7->getType())
1542 GEN_ERROR("Select operand types must match!");
1543 $$ = ConstantExpr::getSelect($3, $5, $7);
1546 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1547 if ($3->getType() != $5->getType())
1548 GEN_ERROR("Binary operator types must match!");
1550 $$ = ConstantExpr::get($1, $3, $5);
1552 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1553 if ($3->getType() != $5->getType())
1554 GEN_ERROR("Logical operator types must match!");
1555 if (!$3->getType()->isIntegral()) {
1556 if (!isa<PackedType>($3->getType()) ||
1557 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1558 GEN_ERROR("Logical operator requires integral operands!");
1560 $$ = ConstantExpr::get($1, $3, $5);
1563 | SetCondOps '(' ConstVal ',' ConstVal ')' {
1564 if ($3->getType() != $5->getType())
1565 GEN_ERROR("setcc operand types must match!");
1566 $$ = ConstantExpr::get($1, $3, $5);
1569 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1570 if ($4->getType() != $6->getType())
1571 GEN_ERROR("icmp operand types must match!");
1572 $$ = ConstantExpr::getICmp($2, $4, $6);
1574 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1575 if ($4->getType() != $6->getType())
1576 GEN_ERROR("fcmp operand types must match!");
1577 $$ = ConstantExpr::getFCmp($2, $4, $6);
1579 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1580 if ($5->getType() != Type::UByteTy)
1581 GEN_ERROR("Shift count for shift constant must be unsigned byte!");
1582 if (!$3->getType()->isInteger())
1583 GEN_ERROR("Shift constant expression requires integer operand!");
1585 $$ = ConstantExpr::get($1, $3, $5);
1588 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1589 if (!ExtractElementInst::isValidOperands($3, $5))
1590 GEN_ERROR("Invalid extractelement operands!");
1591 $$ = ConstantExpr::getExtractElement($3, $5);
1594 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1595 if (!InsertElementInst::isValidOperands($3, $5, $7))
1596 GEN_ERROR("Invalid insertelement operands!");
1597 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1600 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1601 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1602 GEN_ERROR("Invalid shufflevector operands!");
1603 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1608 // ConstVector - A list of comma separated constants.
1609 ConstVector : ConstVector ',' ConstVal {
1610 ($$ = $1)->push_back($3);
1614 $$ = new std::vector<Constant*>();
1620 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1621 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1624 //===----------------------------------------------------------------------===//
1625 // Rules to match Modules
1626 //===----------------------------------------------------------------------===//
1628 // Module rule: Capture the result of parsing the whole file into a result
1631 Module : FunctionList {
1632 $$ = ParserResult = $1;
1633 CurModule.ModuleDone();
1637 // FunctionList - A list of functions, preceeded by a constant pool.
1639 FunctionList : FunctionList Function {
1641 CurFun.FunctionDone();
1644 | FunctionList FunctionProto {
1648 | FunctionList MODULE ASM_TOK AsmBlock {
1652 | FunctionList IMPLEMENTATION {
1657 $$ = CurModule.CurrentModule;
1658 // Emit an error if there are any unresolved types left.
1659 if (!CurModule.LateResolveTypes.empty()) {
1660 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1661 if (DID.Type == ValID::NameVal) {
1662 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1664 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1670 // ConstPool - Constants with optional names assigned to them.
1671 ConstPool : ConstPool OptAssign TYPE TypesV {
1672 // Eagerly resolve types. This is not an optimization, this is a
1673 // requirement that is due to the fact that we could have this:
1675 // %list = type { %list * }
1676 // %list = type { %list * } ; repeated type decl
1678 // If types are not resolved eagerly, then the two types will not be
1679 // determined to be the same type!
1681 ResolveTypeTo($2, *$4);
1683 if (!setTypeName(*$4, $2) && !$2) {
1685 // If this is a named type that is not a redefinition, add it to the slot
1687 CurModule.Types.push_back(*$4);
1693 | ConstPool FunctionProto { // Function prototypes can be in const pool
1696 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
1699 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
1701 GEN_ERROR("Global value initializer is not a constant!");
1702 CurGV = ParseGlobalVariable($2, $3, $4, $5->getType(), $5);
1704 } GlobalVarAttributes {
1707 | ConstPool OptAssign EXTERNAL GlobalType Types {
1708 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, *$5, 0);
1711 } GlobalVarAttributes {
1715 | ConstPool OptAssign DLLIMPORT GlobalType Types {
1716 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, *$5, 0);
1719 } GlobalVarAttributes {
1723 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
1725 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, *$5, 0);
1728 } GlobalVarAttributes {
1732 | ConstPool TARGET TargetDefinition {
1735 | ConstPool DEPLIBS '=' LibrariesDefinition {
1738 | /* empty: end of list */ {
1742 AsmBlock : STRINGCONSTANT {
1743 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1744 char *EndStr = UnEscapeLexed($1, true);
1745 std::string NewAsm($1, EndStr);
1748 if (AsmSoFar.empty())
1749 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1751 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1755 BigOrLittle : BIG { $$ = Module::BigEndian; };
1756 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1758 TargetDefinition : ENDIAN '=' BigOrLittle {
1759 CurModule.CurrentModule->setEndianness($3);
1762 | POINTERSIZE '=' EUINT64VAL {
1764 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1766 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1768 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1771 | TRIPLE '=' STRINGCONSTANT {
1772 CurModule.CurrentModule->setTargetTriple($3);
1775 | DATALAYOUT '=' STRINGCONSTANT {
1776 CurModule.CurrentModule->setDataLayout($3);
1780 LibrariesDefinition : '[' LibList ']';
1782 LibList : LibList ',' STRINGCONSTANT {
1783 CurModule.CurrentModule->addLibrary($3);
1788 CurModule.CurrentModule->addLibrary($1);
1792 | /* empty: end of list */ {
1797 //===----------------------------------------------------------------------===//
1798 // Rules to match Function Headers
1799 //===----------------------------------------------------------------------===//
1801 Name : VAR_ID | STRINGCONSTANT;
1802 OptName : Name | /*empty*/ { $$ = 0; };
1804 ArgVal : Types OptName {
1805 if (*$1 == Type::VoidTy)
1806 GEN_ERROR("void typed arguments are invalid!");
1807 $$ = new std::pair<PATypeHolder*, char*>($1, $2);
1811 ArgListH : ArgListH ',' ArgVal {
1818 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1824 ArgList : ArgListH {
1828 | ArgListH ',' DOTDOTDOT {
1830 $$->push_back(std::pair<PATypeHolder*,
1831 char*>(new PATypeHolder(Type::VoidTy), 0));
1835 $$ = new std::vector<std::pair<PATypeHolder*,char*> >();
1836 $$->push_back(std::make_pair(new PATypeHolder(Type::VoidTy), (char*)0));
1844 FunctionHeaderH : OptCallingConv TypesV Name '(' ArgList ')'
1845 OptSection OptAlign {
1847 std::string FunctionName($3);
1848 free($3); // Free strdup'd memory!
1850 if (!(*$2)->isFirstClassType() && *$2 != Type::VoidTy)
1851 GEN_ERROR("LLVM functions cannot return aggregate types!");
1853 std::vector<const Type*> ParamTypeList;
1854 if ($5) { // If there are arguments...
1855 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1856 I != $5->end(); ++I)
1857 ParamTypeList.push_back(I->first->get());
1860 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
1861 if (isVarArg) ParamTypeList.pop_back();
1863 const FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
1864 const PointerType *PFT = PointerType::get(FT);
1868 if (!FunctionName.empty()) {
1869 ID = ValID::create((char*)FunctionName.c_str());
1871 ID = ValID::create((int)CurModule.Values[PFT].size());
1875 // See if this function was forward referenced. If so, recycle the object.
1876 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
1877 // Move the function to the end of the list, from whereever it was
1878 // previously inserted.
1879 Fn = cast<Function>(FWRef);
1880 CurModule.CurrentModule->getFunctionList().remove(Fn);
1881 CurModule.CurrentModule->getFunctionList().push_back(Fn);
1882 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
1883 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
1884 // If this is the case, either we need to be a forward decl, or it needs
1886 if (!CurFun.isDeclare && !Fn->isExternal())
1887 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
1889 // Make sure to strip off any argument names so we can't get conflicts.
1890 if (Fn->isExternal())
1891 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
1894 } else { // Not already defined?
1895 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
1896 CurModule.CurrentModule);
1898 InsertValue(Fn, CurModule.Values);
1901 CurFun.FunctionStart(Fn);
1903 if (CurFun.isDeclare) {
1904 // If we have declaration, always overwrite linkage. This will allow us to
1905 // correctly handle cases, when pointer to function is passed as argument to
1906 // another function.
1907 Fn->setLinkage(CurFun.Linkage);
1909 Fn->setCallingConv($1);
1910 Fn->setAlignment($8);
1916 // Add all of the arguments we parsed to the function...
1917 if ($5) { // Is null if empty...
1918 if (isVarArg) { // Nuke the last entry
1919 assert($5->back().first->get() == Type::VoidTy && $5->back().second == 0&&
1920 "Not a varargs marker!");
1921 delete $5->back().first;
1922 $5->pop_back(); // Delete the last entry
1924 Function::arg_iterator ArgIt = Fn->arg_begin();
1925 for (std::vector<std::pair<PATypeHolder*,char*> >::iterator I = $5->begin();
1926 I != $5->end(); ++I, ++ArgIt) {
1927 delete I->first; // Delete the typeholder...
1929 setValueName(ArgIt, I->second); // Insert arg into symtab...
1934 delete $5; // We're now done with the argument list
1939 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
1941 FunctionHeader : OptLinkage FunctionHeaderH BEGIN {
1942 $$ = CurFun.CurrentFunction;
1944 // Make sure that we keep track of the linkage type even if there was a
1945 // previous "declare".
1949 END : ENDTOK | '}'; // Allow end of '}' to end a function
1951 Function : BasicBlockList END {
1956 FnDeclareLinkage: /*default*/ |
1957 DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; } |
1958 EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; };
1960 FunctionProto : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
1961 $$ = CurFun.CurrentFunction;
1962 CurFun.FunctionDone();
1966 //===----------------------------------------------------------------------===//
1967 // Rules to match Basic Blocks
1968 //===----------------------------------------------------------------------===//
1970 OptSideEffect : /* empty */ {
1979 ConstValueRef : ESINT64VAL { // A reference to a direct constant
1980 $$ = ValID::create($1);
1984 $$ = ValID::create($1);
1987 | FPVAL { // Perhaps it's an FP constant?
1988 $$ = ValID::create($1);
1992 $$ = ValID::create(ConstantBool::getTrue());
1996 $$ = ValID::create(ConstantBool::getFalse());
2000 $$ = ValID::createNull();
2004 $$ = ValID::createUndef();
2007 | ZEROINITIALIZER { // A vector zero constant.
2008 $$ = ValID::createZeroInit();
2011 | '<' ConstVector '>' { // Nonempty unsized packed vector
2012 const Type *ETy = (*$2)[0]->getType();
2013 int NumElements = $2->size();
2015 PackedType* pt = PackedType::get(ETy, NumElements);
2016 PATypeHolder* PTy = new PATypeHolder(
2024 // Verify all elements are correct type!
2025 for (unsigned i = 0; i < $2->size(); i++) {
2026 if (ETy != (*$2)[i]->getType())
2027 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2028 ETy->getDescription() +"' as required!\nIt is of type '" +
2029 (*$2)[i]->getType()->getDescription() + "'.");
2032 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2033 delete PTy; delete $2;
2037 $$ = ValID::create($1);
2040 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2041 char *End = UnEscapeLexed($3, true);
2042 std::string AsmStr = std::string($3, End);
2043 End = UnEscapeLexed($5, true);
2044 std::string Constraints = std::string($5, End);
2045 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2051 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2054 SymbolicValueRef : INTVAL { // Is it an integer reference...?
2055 $$ = ValID::create($1);
2058 | Name { // Is it a named reference...?
2059 $$ = ValID::create($1);
2063 // ValueRef - A reference to a definition... either constant or symbolic
2064 ValueRef : SymbolicValueRef | ConstValueRef;
2067 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2068 // type immediately preceeds the value reference, and allows complex constant
2069 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2070 ResolvedVal : Types ValueRef {
2071 $$ = getVal(*$1, $2); delete $1;
2075 BasicBlockList : BasicBlockList BasicBlock {
2079 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2085 // Basic blocks are terminated by branching instructions:
2086 // br, br/cc, switch, ret
2088 BasicBlock : InstructionList OptAssign BBTerminatorInst {
2089 setValueName($3, $2);
2093 $1->getInstList().push_back($3);
2099 InstructionList : InstructionList Inst {
2100 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2101 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2102 if (CI2->getParent() == 0)
2103 $1->getInstList().push_back(CI2);
2104 $1->getInstList().push_back($2);
2109 $$ = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2112 // Make sure to move the basic block to the correct location in the
2113 // function, instead of leaving it inserted wherever it was first
2115 Function::BasicBlockListType &BBL =
2116 CurFun.CurrentFunction->getBasicBlockList();
2117 BBL.splice(BBL.end(), BBL, $$);
2121 $$ = getBBVal(ValID::create($1), true);
2124 // Make sure to move the basic block to the correct location in the
2125 // function, instead of leaving it inserted wherever it was first
2127 Function::BasicBlockListType &BBL =
2128 CurFun.CurrentFunction->getBasicBlockList();
2129 BBL.splice(BBL.end(), BBL, $$);
2133 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2134 $$ = new ReturnInst($2);
2137 | RET VOID { // Return with no result...
2138 $$ = new ReturnInst();
2141 | BR LABEL ValueRef { // Unconditional Branch...
2142 BasicBlock* tmpBB = getBBVal($3);
2144 $$ = new BranchInst(tmpBB);
2145 } // Conditional Branch...
2146 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2147 BasicBlock* tmpBBA = getBBVal($6);
2149 BasicBlock* tmpBBB = getBBVal($9);
2151 Value* tmpVal = getVal(Type::BoolTy, $3);
2153 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2155 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2156 Value* tmpVal = getVal($2, $3);
2158 BasicBlock* tmpBB = getBBVal($6);
2160 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2163 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2165 for (; I != E; ++I) {
2166 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2167 S->addCase(CI, I->second);
2169 GEN_ERROR("Switch case is constant, but not a simple integer!");
2174 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2175 Value* tmpVal = getVal($2, $3);
2177 BasicBlock* tmpBB = getBBVal($6);
2179 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2183 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2184 TO LABEL ValueRef UNWIND LABEL ValueRef {
2185 const PointerType *PFTy;
2186 const FunctionType *Ty;
2188 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2189 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2190 // Pull out the types of all of the arguments...
2191 std::vector<const Type*> ParamTypes;
2193 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2195 ParamTypes.push_back((*I)->getType());
2198 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2199 if (isVarArg) ParamTypes.pop_back();
2201 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2202 PFTy = PointerType::get(Ty);
2205 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2207 BasicBlock *Normal = getBBVal($10);
2209 BasicBlock *Except = getBBVal($13);
2212 // Create the call node...
2213 if (!$6) { // Has no arguments?
2214 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2215 } else { // Has arguments?
2216 // Loop through FunctionType's arguments and ensure they are specified
2219 FunctionType::param_iterator I = Ty->param_begin();
2220 FunctionType::param_iterator E = Ty->param_end();
2221 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2223 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2224 if ((*ArgI)->getType() != *I)
2225 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2226 (*I)->getDescription() + "'!");
2228 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2229 GEN_ERROR("Invalid number of parameters detected!");
2231 $$ = new InvokeInst(V, Normal, Except, *$6);
2233 cast<InvokeInst>($$)->setCallingConv($2);
2240 $$ = new UnwindInst();
2244 $$ = new UnreachableInst();
2250 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2252 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2255 GEN_ERROR("May only switch on a constant pool value!");
2257 BasicBlock* tmpBB = getBBVal($6);
2259 $$->push_back(std::make_pair(V, tmpBB));
2261 | IntType ConstValueRef ',' LABEL ValueRef {
2262 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2263 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2267 GEN_ERROR("May only switch on a constant pool value!");
2269 BasicBlock* tmpBB = getBBVal($5);
2271 $$->push_back(std::make_pair(V, tmpBB));
2274 Inst : OptAssign InstVal {
2275 // Is this definition named?? if so, assign the name...
2276 setValueName($2, $1);
2283 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2284 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2285 Value* tmpVal = getVal(*$1, $3);
2287 BasicBlock* tmpBB = getBBVal($5);
2289 $$->push_back(std::make_pair(tmpVal, tmpBB));
2292 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2294 Value* tmpVal = getVal($1->front().first->getType(), $4);
2296 BasicBlock* tmpBB = getBBVal($6);
2298 $1->push_back(std::make_pair(tmpVal, tmpBB));
2302 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2303 $$ = new std::vector<Value*>();
2306 | ValueRefList ',' ResolvedVal {
2312 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2313 ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; };
2315 OptTailCall : TAIL CALL {
2324 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2325 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2326 !isa<PackedType>((*$2).get()))
2328 "Arithmetic operator requires integer, FP, or packed operands!");
2329 if (isa<PackedType>((*$2).get()) &&
2330 ($1 == Instruction::URem ||
2331 $1 == Instruction::SRem ||
2332 $1 == Instruction::FRem))
2333 GEN_ERROR("U/S/FRem not supported on packed types!");
2334 Value* val1 = getVal(*$2, $3);
2336 Value* val2 = getVal(*$2, $5);
2338 $$ = BinaryOperator::create($1, val1, val2);
2340 GEN_ERROR("binary operator returned null!");
2343 | LogicalOps Types ValueRef ',' ValueRef {
2344 if (!(*$2)->isIntegral()) {
2345 if (!isa<PackedType>($2->get()) ||
2346 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2347 GEN_ERROR("Logical operator requires integral operands!");
2349 Value* tmpVal1 = getVal(*$2, $3);
2351 Value* tmpVal2 = getVal(*$2, $5);
2353 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2355 GEN_ERROR("binary operator returned null!");
2358 | SetCondOps Types ValueRef ',' ValueRef {
2359 if(isa<PackedType>((*$2).get())) {
2361 "PackedTypes currently not supported in setcc instructions!");
2363 Value* tmpVal1 = getVal(*$2, $3);
2365 Value* tmpVal2 = getVal(*$2, $5);
2367 $$ = new SetCondInst($1, tmpVal1, tmpVal2);
2369 GEN_ERROR("binary operator returned null!");
2372 | ICMP IPredicates Types ValueRef ',' ValueRef {
2373 if (isa<PackedType>((*$3).get()))
2374 GEN_ERROR("Packed types not supported by icmp instruction");
2375 Value* tmpVal1 = getVal(*$3, $4);
2377 Value* tmpVal2 = getVal(*$3, $6);
2379 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2381 GEN_ERROR("icmp operator returned null!");
2383 | FCMP FPredicates Types ValueRef ',' ValueRef {
2384 if (isa<PackedType>((*$3).get()))
2385 GEN_ERROR("Packed types not supported by fcmp instruction");
2386 Value* tmpVal1 = getVal(*$3, $4);
2388 Value* tmpVal2 = getVal(*$3, $6);
2390 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2392 GEN_ERROR("fcmp operator returned null!");
2395 llvm_cerr << "WARNING: Use of eliminated 'not' instruction:"
2396 << " Replacing with 'xor'.\n";
2398 Value *Ones = ConstantIntegral::getAllOnesValue($2->getType());
2400 GEN_ERROR("Expected integral type for not instruction!");
2402 $$ = BinaryOperator::create(Instruction::Xor, $2, Ones);
2404 GEN_ERROR("Could not create a xor instruction!");
2407 | ShiftOps ResolvedVal ',' ResolvedVal {
2408 if ($4->getType() != Type::UByteTy)
2409 GEN_ERROR("Shift amount must be ubyte!");
2410 if (!$2->getType()->isInteger())
2411 GEN_ERROR("Shift constant expression requires integer operand!");
2413 $$ = new ShiftInst($1, $2, $4);
2416 | CastOps ResolvedVal TO Types {
2418 const Type* Ty = $4->get();
2419 if (!Val->getType()->isFirstClassType())
2420 GEN_ERROR("cast from a non-primitive type: '" +
2421 Val->getType()->getDescription() + "'!");
2422 if (!Ty->isFirstClassType())
2423 GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2424 $$ = CastInst::create($1, $2, $4->get());
2427 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2428 if ($2->getType() != Type::BoolTy)
2429 GEN_ERROR("select condition must be boolean!");
2430 if ($4->getType() != $6->getType())
2431 GEN_ERROR("select value types should match!");
2432 $$ = new SelectInst($2, $4, $6);
2435 | VAARG ResolvedVal ',' Types {
2437 $$ = new VAArgInst($2, *$4);
2441 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2442 if (!ExtractElementInst::isValidOperands($2, $4))
2443 GEN_ERROR("Invalid extractelement operands!");
2444 $$ = new ExtractElementInst($2, $4);
2447 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2448 if (!InsertElementInst::isValidOperands($2, $4, $6))
2449 GEN_ERROR("Invalid insertelement operands!");
2450 $$ = new InsertElementInst($2, $4, $6);
2453 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2454 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2455 GEN_ERROR("Invalid shufflevector operands!");
2456 $$ = new ShuffleVectorInst($2, $4, $6);
2460 const Type *Ty = $2->front().first->getType();
2461 if (!Ty->isFirstClassType())
2462 GEN_ERROR("PHI node operands must be of first class type!");
2463 $$ = new PHINode(Ty);
2464 ((PHINode*)$$)->reserveOperandSpace($2->size());
2465 while ($2->begin() != $2->end()) {
2466 if ($2->front().first->getType() != Ty)
2467 GEN_ERROR("All elements of a PHI node must be of the same type!");
2468 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2471 delete $2; // Free the list...
2474 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
2475 const PointerType *PFTy = 0;
2476 const FunctionType *Ty = 0;
2478 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2479 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2480 // Pull out the types of all of the arguments...
2481 std::vector<const Type*> ParamTypes;
2483 for (std::vector<Value*>::iterator I = $6->begin(), E = $6->end();
2485 ParamTypes.push_back((*I)->getType());
2488 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2489 if (isVarArg) ParamTypes.pop_back();
2491 if (!(*$3)->isFirstClassType() && *$3 != Type::VoidTy)
2492 GEN_ERROR("LLVM functions cannot return aggregate types!");
2494 Ty = FunctionType::get($3->get(), ParamTypes, isVarArg);
2495 PFTy = PointerType::get(Ty);
2498 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2501 // Create the call node...
2502 if (!$6) { // Has no arguments?
2503 // Make sure no arguments is a good thing!
2504 if (Ty->getNumParams() != 0)
2505 GEN_ERROR("No arguments passed to a function that "
2506 "expects arguments!");
2508 $$ = new CallInst(V, std::vector<Value*>());
2509 } else { // Has arguments?
2510 // Loop through FunctionType's arguments and ensure they are specified
2513 FunctionType::param_iterator I = Ty->param_begin();
2514 FunctionType::param_iterator E = Ty->param_end();
2515 std::vector<Value*>::iterator ArgI = $6->begin(), ArgE = $6->end();
2517 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
2518 if ((*ArgI)->getType() != *I)
2519 GEN_ERROR("Parameter " +(*ArgI)->getName()+ " is not of type '" +
2520 (*I)->getDescription() + "'!");
2522 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2523 GEN_ERROR("Invalid number of parameters detected!");
2525 $$ = new CallInst(V, *$6);
2527 cast<CallInst>($$)->setTailCall($1);
2528 cast<CallInst>($$)->setCallingConv($2);
2539 // IndexList - List of indices for GEP based instructions...
2540 IndexList : ',' ValueRefList {
2544 $$ = new std::vector<Value*>();
2548 OptVolatile : VOLATILE {
2559 MemoryInst : MALLOC Types OptCAlign {
2560 $$ = new MallocInst(*$2, 0, $3);
2564 | MALLOC Types ',' UINT ValueRef OptCAlign {
2565 Value* tmpVal = getVal($4, $5);
2567 $$ = new MallocInst(*$2, tmpVal, $6);
2570 | ALLOCA Types OptCAlign {
2571 $$ = new AllocaInst(*$2, 0, $3);
2575 | ALLOCA Types ',' UINT ValueRef OptCAlign {
2576 Value* tmpVal = getVal($4, $5);
2578 $$ = new AllocaInst(*$2, tmpVal, $6);
2581 | FREE ResolvedVal {
2582 if (!isa<PointerType>($2->getType()))
2583 GEN_ERROR("Trying to free nonpointer type " +
2584 $2->getType()->getDescription() + "!");
2585 $$ = new FreeInst($2);
2589 | OptVolatile LOAD Types ValueRef {
2590 if (!isa<PointerType>($3->get()))
2591 GEN_ERROR("Can't load from nonpointer type: " +
2592 (*$3)->getDescription());
2593 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2594 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2595 (*$3)->getDescription());
2596 Value* tmpVal = getVal(*$3, $4);
2598 $$ = new LoadInst(tmpVal, "", $1);
2601 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2602 const PointerType *PT = dyn_cast<PointerType>($5->get());
2604 GEN_ERROR("Can't store to a nonpointer type: " +
2605 (*$5)->getDescription());
2606 const Type *ElTy = PT->getElementType();
2607 if (ElTy != $3->getType())
2608 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2609 "' into space of type '" + ElTy->getDescription() + "'!");
2611 Value* tmpVal = getVal(*$5, $6);
2613 $$ = new StoreInst($3, tmpVal, $1);
2616 | GETELEMENTPTR Types ValueRef IndexList {
2617 if (!isa<PointerType>($2->get()))
2618 GEN_ERROR("getelementptr insn requires pointer operand!");
2620 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2621 GEN_ERROR("Invalid getelementptr indices for type '" +
2622 (*$2)->getDescription()+ "'!");
2623 Value* tmpVal = getVal(*$2, $3);
2625 $$ = new GetElementPtrInst(tmpVal, *$4);
2633 void llvm::GenerateError(const std::string &message, int LineNo) {
2634 if (LineNo == -1) LineNo = llvmAsmlineno;
2635 // TODO: column number in exception
2637 TheParseError->setError(CurFilename, message, LineNo);
2641 int yyerror(const char *ErrorMsg) {
2643 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2644 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2645 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2646 if (yychar == YYEMPTY || yychar == 0)
2647 errMsg += "end-of-file.";
2649 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2650 GenerateError(errMsg);